SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
SET UNIQUE_CHECKS = 0;
SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';

-- ERP Java 数据库建库脚本
-- 生成时间: 2026-04-05
-- 数据库: erp_java

SET FOREIGN_KEY_CHECKS = 0;


-- 来源: /root/.openclaw/workspace/erp-java-backend/services/aftersale-service/src/main/resources/db/schema.sql
-- ============================================================================
-- ================================================================
-- 售后服务数据库初始化脚本
-- ================================================================

-- 售后主表
CREATE TABLE IF NOT EXISTS `after_sales` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    `short_id` VARCHAR(32) NOT NULL UNIQUE COMMENT '售后单短ID，如 AS20240401ABC123',
    `order_id` BIGINT UNSIGNED NOT NULL COMMENT '原订单ID',
    `order_short_id` VARCHAR(32) DEFAULT NULL COMMENT '原订单短ID',
    `platform_order_sn` VARCHAR(64) DEFAULT NULL COMMENT '平台订单号',
    `shop_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '店铺ID',
    `shop_name` VARCHAR(128) DEFAULT NULL COMMENT '店铺名称',
    `customer_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '客户ID',
    `customer_name` VARCHAR(64) DEFAULT NULL COMMENT '客户姓名',
    `customer_phone` VARCHAR(20) DEFAULT NULL COMMENT '客户电话',

    -- 售后类型与原因
    `type` VARCHAR(20) NOT NULL COMMENT '售后类型: refund(仅退款)/return(退货退款)/exchange(换货)/repair(维修)',
    `reason` VARCHAR(128) NOT NULL COMMENT '售后原因',
    `reason_detail` VARCHAR(512) DEFAULT NULL COMMENT '详细原因描述',
    `description` VARCHAR(1000) DEFAULT NULL COMMENT '客户描述',

    -- 金额信息
    `apply_amount` DECIMAL(12,2) NOT NULL DEFAULT '0.00' COMMENT '申请退款金额',
    `approve_amount` DECIMAL(12,2) DEFAULT NULL COMMENT '审核通过退款金额',
    `freight_refund` DECIMAL(12,2) DEFAULT '0.00' COMMENT '运费退款金额',
    `actual_refund` DECIMAL(12,2) DEFAULT NULL COMMENT '实际退款金额',

    -- 状态流转
    `status` VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT '售后状态: pending/approved/rejected/processing/completed/closed',
    `audit_status` VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT '审核状态: pending/approved/rejected',
    `previous_status` VARCHAR(20) DEFAULT NULL COMMENT '上一状态（用于撤销）',

    -- 审核信息
    `audit_comment` VARCHAR(512) DEFAULT NULL COMMENT '审核备注/驳回原因',
    `auditor_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '审核人ID',
    `auditor_name` VARCHAR(64) DEFAULT NULL COMMENT '审核人姓名',
    `audit_time` DATETIME DEFAULT NULL COMMENT '审核时间',

    -- 退款/收货信息
    `refund_time` DATETIME DEFAULT NULL COMMENT '退款时间',
    `return_tracking_no` VARCHAR(64) DEFAULT NULL COMMENT '退货快递单号',
    `return_express_company` VARCHAR(64) DEFAULT NULL COMMENT '退货快递公司',
    `receive_time` DATETIME DEFAULT NULL COMMENT '收到退货时间',
    `receive_comment` VARCHAR(512) DEFAULT NULL COMMENT '收货备注',

    -- 完成信息
    `complete_time` DATETIME DEFAULT NULL COMMENT '完成时间',
    `close_time` DATETIME DEFAULT NULL COMMENT '关闭时间',
    `close_reason` VARCHAR(512) DEFAULT NULL COMMENT '关闭原因',

    -- 图片凭证
    `images` TEXT DEFAULT NULL COMMENT '图片凭证JSON数组',

    -- 关联单据
    `exchange_order_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '换货新订单ID',
    `repair_order_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '维修工单ID',
    `finance_refund_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '财务退款记录ID',

    `version` INT UNSIGNED DEFAULT '0' COMMENT '乐观锁版本号',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `deleted` TINYINT UNSIGNED DEFAULT '0' COMMENT '逻辑删除标记: 0未删除 1已删除',

    INDEX `idx_short_id` (`short_id`),
    INDEX `idx_order_id` (`order_id`),
    INDEX `idx_platform_order_sn` (`platform_order_sn`),
    INDEX `idx_type` (`type`),
    INDEX `idx_status` (`status`),
    INDEX `idx_audit_status` (`audit_status`),
    INDEX `idx_customer_id` (`customer_id`),
    INDEX `idx_shop_id` (`shop_id`),
    INDEX `idx_created_at` (`created_at`),
    INDEX `idx_refund_time` (`refund_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='售后主表';

-- 售后明细表（售后关联的订单商品）
CREATE TABLE IF NOT EXISTS `after_sale_items` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    `after_sale_id` BIGINT UNSIGNED NOT NULL COMMENT '售后单ID',
    `order_item_id` BIGINT UNSIGNED NOT NULL COMMENT '原订单明细ID',
    `product_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '商品ID',
    `product_name` VARCHAR(256) DEFAULT NULL COMMENT '商品名称',
    `sku_id` BIGINT UNSIGNED DEFAULT NULL COMMENT 'SKU ID',
    `sku_code` VARCHAR(64) DEFAULT NULL COMMENT 'SKU编码',
    `sku_specs` VARCHAR(512) DEFAULT NULL COMMENT 'SKU规格描述',
    `image_url` VARCHAR(512) DEFAULT NULL COMMENT '商品图片',
    `unit_price` DECIMAL(12,2) DEFAULT '0.00' COMMENT '单价',
    `quantity` INT UNSIGNED DEFAULT '1' COMMENT '数量',
    `apply_quantity` INT UNSIGNED DEFAULT '1' COMMENT '申请售后数量',
    `approve_quantity` INT UNSIGNED DEFAULT NULL COMMENT '审核通过数量',
    `return_quantity` INT UNSIGNED DEFAULT '0' COMMENT '实际退货数量',
    `item_amount` DECIMAL(12,2) DEFAULT '0.00' COMMENT '小计金额',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `deleted` TINYINT UNSIGNED DEFAULT '0' COMMENT '逻辑删除标记',

    INDEX `idx_after_sale_id` (`after_sale_id`),
    INDEX `idx_order_item_id` (`order_item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='售后明细表';

-- 售后操作日志表
CREATE TABLE IF NOT EXISTS `after_sale_logs` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    `after_sale_id` BIGINT UNSIGNED NOT NULL COMMENT '售后单ID',
    `operator_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '操作人ID',
    `operator_name` VARCHAR(64) DEFAULT NULL COMMENT '操作人姓名',
    `operator_type` VARCHAR(20) DEFAULT 'user' COMMENT '操作人类型: user/system/admin',
    `action` VARCHAR(32) NOT NULL COMMENT '操作动作: create/audit/approve/reject/refund/complete/close/update',
    `from_status` VARCHAR(20) DEFAULT NULL COMMENT '操作前状态',
    `to_status` VARCHAR(20) DEFAULT NULL COMMENT '操作后状态',
    `content` VARCHAR(1000) DEFAULT NULL COMMENT '操作内容描述',
    `ip` VARCHAR(64) DEFAULT NULL COMMENT '操作IP',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',

    INDEX `idx_after_sale_id` (`after_sale_id`),
    INDEX `idx_operator_id` (`operator_id`),
    INDEX `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='售后操作日志表';

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/ai-service/sql/init.sql
-- ============================================================================
-- AI对话表
CREATE TABLE IF NOT EXISTS `ai_conversations` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
    `tenant_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '租户ID',
    `title` VARCHAR(255) NOT NULL COMMENT '对话标题',
    `model` VARCHAR(100) DEFAULT NULL COMMENT 'AI模型',
    `service` VARCHAR(50) DEFAULT NULL COMMENT 'AI服务提供商',
    `status` VARCHAR(20) DEFAULT 'active' COMMENT '状态: active, archived, deleted',
    `message_count` INT UNSIGNED DEFAULT 0 COMMENT '消息数量',
    `total_tokens` BIGINT UNSIGNED DEFAULT 0 COMMENT '总Token数',
    `last_message_at` DATETIME DEFAULT NULL COMMENT '最后消息时间',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `deleted` TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除标记',
    PRIMARY KEY (`id`),
    KEY `idx_user_id` (`user_id`),
    KEY `idx_tenant_id` (`tenant_id`),
    KEY `idx_status` (`status`),
    KEY `idx_last_message_at` (`last_message_at`),
    KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='AI对话表';

-- AI消息表
CREATE TABLE IF NOT EXISTS `ai_messages` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `conversation_id` BIGINT UNSIGNED NOT NULL COMMENT '对话ID',
    `role` VARCHAR(20) NOT NULL COMMENT '角色: user, assistant, system',
    `content` TEXT NOT NULL COMMENT '消息内容',
    `tokens` INT UNSIGNED DEFAULT 0 COMMENT 'Token数量',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `deleted` TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除标记',
    PRIMARY KEY (`id`),
    KEY `idx_conversation_id` (`conversation_id`),
    KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='AI消息表';

-- AI使用记录表（可选，用于更详细的统计）
CREATE TABLE IF NOT EXISTS `ai_usage_logs` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
    `tenant_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '租户ID',
    `service` VARCHAR(50) NOT NULL COMMENT 'AI服务',
    `model` VARCHAR(100) NOT NULL COMMENT '模型',
    `request_type` VARCHAR(50) NOT NULL COMMENT '请求类型: chat, task, test',
    `input_tokens` INT UNSIGNED DEFAULT 0 COMMENT '输入Token数',
    `output_tokens` INT UNSIGNED DEFAULT 0 COMMENT '输出Token数',
    `total_tokens` INT UNSIGNED DEFAULT 0 COMMENT '总Token数',
    `response_time_ms` INT UNSIGNED DEFAULT 0 COMMENT '响应时间(毫秒)',
    `status` VARCHAR(20) DEFAULT 'success' COMMENT '状态: success, failed',
    `error_message` TEXT DEFAULT NULL COMMENT '错误信息',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    PRIMARY KEY (`id`),
    KEY `idx_user_id` (`user_id`),
    KEY `idx_service_model` (`service`, `model`),
    KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='AI使用记录表';

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/approval-flow-service/src/main/resources/deployment/db-migration.sql
-- ============================================================================
-- ============================================
-- 审核流服务数据库初始化脚本
-- 数据库: erp_db
-- ============================================

-- 创建审核规则表
CREATE TABLE IF NOT EXISTS `audit_rules` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '规则ID',
    `tenant_id` BIGINT NOT NULL DEFAULT 0 COMMENT '租户ID',
    `name` VARCHAR(100) NOT NULL COMMENT '规则名称',
    `type` VARCHAR(20) NOT NULL COMMENT '规则类型：order-订单审核，refund-退款审核',
    `conditions` TEXT COMMENT '条件配置（JSON数组）',
    `actions` TEXT COMMENT '动作配置（JSON数组）',
    `priority` INT NOT NULL DEFAULT 9999 COMMENT '优先级（数字越小优先级越高）',
    `is_active` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用：0-禁用，1-启用',
    `description` VARCHAR(500) DEFAULT NULL COMMENT '描述',
    `created_by` BIGINT NOT NULL COMMENT '创建人',
    `updated_by` BIGINT NOT NULL COMMENT '更新人',
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `deleted_at` DATETIME DEFAULT NULL COMMENT '删除时间（软删除标记）',
    PRIMARY KEY (`id`),
    KEY `idx_tenant_id` (`tenant_id`),
    KEY `idx_type` (`type`),
    KEY `idx_is_active` (`is_active`),
    KEY `idx_priority` (`priority`),
    KEY `idx_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审核规则表';

-- 创建审核日志表
CREATE TABLE IF NOT EXISTS `audit_logs` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '日志ID',
    `tenant_id` BIGINT NOT NULL DEFAULT 0 COMMENT '租户ID',
    `user_id` BIGINT DEFAULT NULL COMMENT '用户ID',
    `user_name` VARCHAR(100) DEFAULT NULL COMMENT '用户名称',
    `module` VARCHAR(50) NOT NULL COMMENT '模块名称',
    `action` VARCHAR(50) NOT NULL COMMENT '操作类型：Create/Update/Delete/Approve/Reject',
    `target_type` VARCHAR(50) NOT NULL COMMENT '目标类型',
    `target_id` BIGINT NOT NULL COMMENT '目标ID',
    `old_values` TEXT COMMENT '修改前的值（JSON）',
    `new_values` TEXT COMMENT '修改后的值（JSON）',
    `ip` VARCHAR(50) DEFAULT NULL COMMENT 'IP地址',
    `user_agent` VARCHAR(500) DEFAULT NULL COMMENT 'User-Agent',
    `request_id` VARCHAR(100) DEFAULT NULL COMMENT '请求ID',
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    PRIMARY KEY (`id`),
    KEY `idx_tenant_id` (`tenant_id`),
    KEY `idx_module` (`module`),
    KEY `idx_action` (`action`),
    KEY `idx_user_id` (`user_id`),
    KEY `idx_target_type_id` (`target_type`, `target_id`),
    KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='审核日志表';

-- ============================================
-- 初始化示例数据（可选）
-- ============================================

-- 插入示例规则（仅租户0可见，生产环境请根据需要调整）
INSERT INTO `audit_rules` (`tenant_id`, `name`, `type`, `conditions`, `actions`, `priority`, `is_active`, `description`, `created_by`, `updated_by`) VALUES
(0, '高额订单自动审核', 'order', '[{"field":"total_amount","operator":"gte","value":10000}]', '[{"type":"pass","params":{}}]', 1, 1, '订单金额大于等于10000元自动通过', 1, 1),
(0, '高额退款需审批', 'refund', '[{"field":"refund_amount","operator":"gt","value":5000}]', '[{"type":"escalate","params":{"approver_role":"manager"}}]', 1, 1, '退款金额大于5000元需经理审批', 1, 1);

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/data-import-export-service/init.sql
-- ============================================================================
-- 数据导入导出服务初始化脚本
-- 创建日期: 2026-04-05

-- 创建导入任务表
CREATE TABLE IF NOT EXISTS `import_task` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `task_name` VARCHAR(200) NOT NULL COMMENT '任务名称',
    `biz_type` VARCHAR(50) NOT NULL COMMENT '业务类型',
    `file_format` VARCHAR(20) NOT NULL COMMENT '文件格式',
    `original_file_name` VARCHAR(500) NOT NULL COMMENT '原始文件名',
    `file_path` VARCHAR(1000) NOT NULL COMMENT '文件存储路径',
    `file_size` BIGINT DEFAULT 0 COMMENT '文件大小（字节）',
    `total_rows` INT DEFAULT 0 COMMENT '总行数',
    `success_rows` INT DEFAULT 0 COMMENT '成功行数',
    `fail_rows` INT DEFAULT 0 COMMENT '失败行数',
    `skip_rows` INT DEFAULT 0 COMMENT '跳过行数',
    `status` VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT '任务状态',
    `tenant_id` BIGINT NOT NULL COMMENT '租户ID',
    `creator_id` BIGINT NOT NULL COMMENT '创建人ID',
    `creator_name` VARCHAR(100) DEFAULT '' COMMENT '创建人名称',
    `finish_time` DATETIME DEFAULT NULL COMMENT '处理完成时间',
    `error_summary` TEXT DEFAULT NULL COMMENT '错误信息摘要',
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `deleted_at` DATETIME DEFAULT NULL COMMENT '删除时间（逻辑删除）',
    PRIMARY KEY (`id`),
    KEY `idx_tenant_id` (`tenant_id`),
    KEY `idx_biz_type` (`biz_type`),
    KEY `idx_status` (`status`),
    KEY `idx_created_at` (`created_at`),
    KEY `idx_creator_id` (`creator_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='导入任务表';

-- 创建导入记录表
CREATE TABLE IF NOT EXISTS `import_record` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `task_id` BIGINT NOT NULL COMMENT '导入任务ID',
    `row_number` INT NOT NULL COMMENT '行号',
    `original_data` TEXT DEFAULT NULL COMMENT '原始数据（JSON格式）',
    `processed_data` TEXT DEFAULT NULL COMMENT '处理后数据（JSON格式）',
    `target_id` BIGINT DEFAULT NULL COMMENT '目标表主键值',
    `result` VARCHAR(20) NOT NULL DEFAULT 'success' COMMENT '导入结果',
    `error_message` TEXT DEFAULT NULL COMMENT '错误信息',
    `error_field` VARCHAR(100) DEFAULT NULL COMMENT '错误字段',
    `tenant_id` BIGINT NOT NULL COMMENT '租户ID',
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    KEY `idx_task_id` (`task_id`),
    KEY `idx_result` (`result`),
    KEY `idx_row_number` (`row_number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='导入记录表';

-- 创建导入模板表
CREATE TABLE IF NOT EXISTS `import_template` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `template_name` VARCHAR(200) NOT NULL COMMENT '模板名称',
    `template_code` VARCHAR(100) NOT NULL COMMENT '模板编码',
    `biz_type` VARCHAR(50) NOT NULL COMMENT '业务类型',
    `description` VARCHAR(500) DEFAULT NULL COMMENT '模板描述',
    `file_path` VARCHAR(1000) DEFAULT NULL COMMENT '模板文件路径',
    `column_definition` TEXT DEFAULT NULL COMMENT '列定义（JSON格式）',
    `is_default` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否为默认模板',
    `tenant_id` BIGINT NOT NULL COMMENT '租户ID',
    `creator_id` BIGINT NOT NULL COMMENT '创建人ID',
    `creator_name` VARCHAR(100) DEFAULT '' COMMENT '创建人名称',
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `deleted_at` DATETIME DEFAULT NULL COMMENT '删除时间（逻辑删除）',
    PRIMARY KEY (`id`),
    KEY `idx_tenant_id` (`tenant_id`),
    KEY `idx_biz_type` (`biz_type`),
    KEY `idx_template_code` (`template_code`),
    KEY `idx_is_default` (`is_default`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='导入模板表';

-- 插入默认模板数据
INSERT INTO `import_template` (`template_name`, `template_code`, `biz_type`, `description`, `column_definition`, `is_default`, `tenant_id`, `creator_id`, `creator_name`) VALUES
('商品导入模板', 'goods_default', 'goods', '商品数据导入模板，包含商品基本信息', '[{"fieldName":"name","headerName":"商品名称","dataType":"string","required":true,"maxLength":200},{"fieldName":"code","headerName":"商品编码","dataType":"string","required":true,"maxLength":50},{"fieldName":"barcode","headerName":"条形码","dataType":"string","required":false,"maxLength":30},{"fieldName":"category","headerName":"商品分类","dataType":"string","required":false,"maxLength":100},{"fieldName":"unit","headerName":"单位","dataType":"string","required":false,"maxLength":20},{"fieldName":"retailPrice","headerName":"零售价","dataType":"decimal","required":false},{"fieldName":"costPrice","headerName":"成本价","dataType":"decimal","required":false}]', 1, 1, 1, '系统管理员'),
('客户导入模板', 'customer_default', 'customer', '客户数据导入模板，包含客户基本信息', '[{"fieldName":"name","headerName":"客户名称","dataType":"string","required":true,"maxLength":200},{"fieldName":"contact","headerName":"联系人","dataType":"string","required":false,"maxLength":100},{"fieldName":"phone","headerName":"联系电话","dataType":"string","required":false,"maxLength":20},{"fieldName":"address","headerName":"地址","dataType":"string","required":false,"maxLength":500},{"fieldName":"email","headerName":"邮箱","dataType":"string","required":false,"maxLength":100}]', 1, 1, 1, '系统管理员'),
('供应商导入模板', 'supplier_default', 'supplier', '供应商数据导入模板', '[{"fieldName":"name","headerName":"供应商名称","dataType":"string","required":true,"maxLength":200},{"fieldName":"contact","headerName":"联系人","dataType":"string","required":false,"maxLength":100},{"fieldName":"phone","headerName":"联系电话","dataType":"string","required":false,"maxLength":20},{"fieldName":"address","headerName":"地址","dataType":"string","required":false,"maxLength":500}]', 1, 1, 1, '系统管理员');

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/logistics-service/src/main/resources/db/init.sql
-- ============================================================================
-- =============================================
-- 物流轨迹服务数据库脚本
-- 适用于 MySQL 8.0+
-- =============================================

-- 创建数据库（如果不存在）
CREATE DATABASE IF NOT EXISTS erp_db DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

USE erp_db;

-- =============================================
-- 运单状态表
-- =============================================
CREATE TABLE IF NOT EXISTS logistics_waybill_status (
    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    waybill_no VARCHAR(50) NOT NULL COMMENT '运单号',
    carrier VARCHAR(20) NOT NULL COMMENT '物流商编码：SF-顺丰, YTO-圆通, ZTO-中通, YUNDA-韵达',
    status VARCHAR(30) DEFAULT 'PENDING' COMMENT '运单状态：PENDING-待发货, IN_TRANSIT-运输中, DELIVERING-派送中, SIGNED-已签收, RETURNING-退回中, RETURNED-已退回, EXCEPTION-异常',
    status_label VARCHAR(50) DEFAULT '待发货' COMMENT '状态标签（中文描述）',
    location VARCHAR(200) DEFAULT '' COMMENT '当前位置',
    description VARCHAR(500) DEFAULT '' COMMENT '状态描述',
    signed_time DATETIME DEFAULT NULL COMMENT '签收时间',
    last_trace_time DATETIME DEFAULT NULL COMMENT '最后轨迹时间',
    need_sync TINYINT(1) DEFAULT 1 COMMENT '是否需要同步：0-否, 1-是',
    sync_status TINYINT(1) DEFAULT 0 COMMENT '同步状态：0-未同步, 1-同步中, 2-已同步, 3-同步失败',
    sync_fail_reason VARCHAR(500) DEFAULT NULL COMMENT '同步失败原因',
    sync_retry_count INT DEFAULT 0 COMMENT '同步重试次数',
    order_id BIGINT DEFAULT NULL COMMENT '订单ID',
    order_no VARCHAR(50) DEFAULT NULL COMMENT '订单编号',
    receiver_name VARCHAR(100) DEFAULT '' COMMENT '收件人姓名',
    receiver_phone VARCHAR(20) DEFAULT '' COMMENT '收件人电话',
    receiver_address VARCHAR(500) DEFAULT '' COMMENT '收件人地址',
    deleted TINYINT(1) DEFAULT 0 COMMENT '逻辑删除：0-未删除, 1-已删除',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',

    INDEX idx_waybill_no (waybill_no),
    INDEX idx_carrier (carrier),
    INDEX idx_status (status),
    INDEX idx_order_id (order_id),
    INDEX idx_sync_status (sync_status),
    INDEX idx_need_sync (need_sync),
    INDEX idx_last_trace_time (last_trace_time),
    INDEX idx_updated_at (updated_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运单状态表';

-- =============================================
-- 物流轨迹记录表
-- =============================================
CREATE TABLE IF NOT EXISTS logistics_trace (
    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    waybill_no VARCHAR(50) NOT NULL COMMENT '运单号',
    carrier VARCHAR(20) NOT NULL COMMENT '物流商编码：SF-顺丰, YTO-圆通, ZTO-中通, YUNDA-韵达',
    status VARCHAR(30) DEFAULT '' COMMENT '轨迹节点状态',
    status_label VARCHAR(50) DEFAULT '' COMMENT '状态标签',
    location VARCHAR(200) DEFAULT '' COMMENT '轨迹发生地点',
    description VARCHAR(500) DEFAULT '' COMMENT '轨迹描述',
    trace_time DATETIME NOT NULL COMMENT '轨迹发生时间',
    raw_status_code VARCHAR(50) DEFAULT '' COMMENT '物流商返回的原始状态码',
    raw_data JSON DEFAULT NULL COMMENT '原始轨迹数据（JSON格式）',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    deleted TINYINT(1) DEFAULT 0 COMMENT '逻辑删除：0-未删除, 1-已删除',

    INDEX idx_waybill_no (waybill_no),
    INDEX idx_carrier (carrier),
    INDEX idx_trace_time (trace_time),
    INDEX idx_waybill_trace (waybill_no, trace_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='物流轨迹记录表';

-- =============================================
-- 初始化数据
-- =============================================

-- 插入示例运单数据
INSERT INTO logistics_waybill_status (waybill_no, carrier, status, status_label, location, description, need_sync, sync_status, order_id, order_no, receiver_name, receiver_phone, receiver_address)
VALUES
    ('SF1234567890', 'SF', 'IN_TRANSIT', '运输中', '深圳市', '快件已从深圳发出，正在运输途中', 1, 0, 10001, 'ORD20240404001', '张三', '13800138000', '广东省广州市天河区'),
    ('YT9876543210', 'YTO', 'DELIVERING', '派送中', '广州市', '快件正在派送中，请保持电话畅通', 1, 0, 10002, 'ORD20240404002', '李四', '13900139000', '广东省深圳市南山区'),
    ('ZTO1112223334', 'ZTO', 'SIGNED', '已签收', '上海市', '已签收，签收人：本人', 0, 2, 10003, 'ORD20240404003', '王五', '13700137000', '上海市浦东新区');

-- =============================================
-- 视图定义（方便查询）
-- =============================================

-- 运单状态视图
CREATE OR REPLACE VIEW v_waybill_status AS
SELECT
    w.id,
    w.waybill_no,
    w.carrier,
    CASE w.carrier
        WHEN 'SF' THEN '顺丰速运'
        WHEN 'YTO' THEN '圆通速递'
        WHEN 'ZTO' THEN '中通快递'
        WHEN 'YUNDA' THEN '韵达快递'
        ELSE w.carrier
    END AS carrier_name,
    w.status,
    w.status_label,
    w.location,
    w.description,
    w.last_trace_time,
    w.signed_time,
    w.need_sync,
    CASE w.sync_status
        WHEN 0 THEN '未同步'
        WHEN 1 THEN '同步中'
        WHEN 2 THEN '已同步'
        WHEN 3 THEN '同步失败'
        ELSE '未知'
    END AS sync_status_label,
    w.sync_fail_reason,
    w.order_id,
    w.order_no,
    w.receiver_name,
    w.updated_at
FROM logistics_waybill_status w
WHERE w.deleted = 0;

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/order-service/src/main/resources/db/schema.sql
-- ============================================================================
-- ================================================================
-- 订单服务数据库初始化脚本
-- ================================================================

-- 订单主表
CREATE TABLE IF NOT EXISTS `orders` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    `short_id` VARCHAR(32) NOT NULL UNIQUE COMMENT '订单短ID，如 O20240401ABC123',
    `platform_order_sn` VARCHAR(64) DEFAULT NULL COMMENT '平台订单号',
    `platform` VARCHAR(32) DEFAULT NULL COMMENT '平台：taobao/jd/pdd/douyin/weixin',
    `shop_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '店铺ID',
    `shop_name` VARCHAR(128) DEFAULT NULL COMMENT '店铺名称',
    `order_time` DATETIME DEFAULT NULL COMMENT '下单时间',
    `buyer_nick` VARCHAR(64) DEFAULT NULL COMMENT '买家昵称',
    `receiver_name` VARCHAR(64) DEFAULT NULL COMMENT '收货人姓名',
    `receiver_phone` VARCHAR(20) DEFAULT NULL COMMENT '收货人电话',
    `receiver_address` VARCHAR(512) DEFAULT NULL COMMENT '收货地址',
    `goods_amount` DECIMAL(12,2) DEFAULT '0.00' COMMENT '商品金额',
    `discount_amount` DECIMAL(12,2) DEFAULT '0.00' COMMENT '优惠金额',
    `freight` DECIMAL(12,2) DEFAULT '0.00' COMMENT '运费',
    `total_amount` DECIMAL(12,2) DEFAULT '0.00' COMMENT '订单总金额',
    `order_status` VARCHAR(20) DEFAULT 'pending' COMMENT '订单状态: pending/auditing/shipped/completed/cancelled',
    `platform_status` VARCHAR(64) DEFAULT NULL COMMENT '平台原始状态',
    `audit_status` VARCHAR(20) DEFAULT 'pending' COMMENT '审核状态: pending/approved/rejected',
    `delivery_status` VARCHAR(20) DEFAULT 'pending' COMMENT '发货状态: pending/delivered',
    `warehouse_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '仓库ID',
    `warehouse_name` VARCHAR(128) DEFAULT NULL COMMENT '仓库名称',
    `express_company` VARCHAR(64) DEFAULT NULL COMMENT '快递公司',
    `express_name` VARCHAR(64) DEFAULT NULL COMMENT '快递名称/简称',
    `express_no` VARCHAR(64) DEFAULT NULL COMMENT '快递单号',
    `delivery_time` DATETIME DEFAULT NULL COMMENT '发货时间',
    `end_time` DATETIME DEFAULT NULL COMMENT '订单完成时间',
    `audit_comment` VARCHAR(512) DEFAULT NULL COMMENT '审核备注/驳回原因',
    `remark` VARCHAR(1000) DEFAULT NULL COMMENT '订单备注',
    `version` INT UNSIGNED DEFAULT '0' COMMENT '乐观锁版本号',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `deleted` TINYINT UNSIGNED DEFAULT '0' COMMENT '逻辑删除标记: 0未删除 1已删除',
    INDEX `idx_platform` (`platform`),
    INDEX `idx_shop_id` (`shop_id`),
    INDEX `idx_order_status` (`order_status`),
    INDEX `idx_audit_status` (`audit_status`),
    INDEX `idx_delivery_status` (`delivery_status`),
    INDEX `idx_order_time` (`order_time`),
    INDEX `idx_short_id` (`short_id`),
    INDEX `idx_platform_order_sn` (`platform_order_sn`),
    INDEX `idx_receiver_phone` (`receiver_phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单主表';

-- 订单项表
CREATE TABLE IF NOT EXISTS `order_items` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    `order_id` BIGINT UNSIGNED NOT NULL COMMENT '订单ID',
    `goods_name` VARCHAR(256) DEFAULT NULL COMMENT '商品名称',
    `platform_sku` VARCHAR(64) DEFAULT NULL COMMENT '平台SKU',
    `sku_code` VARCHAR(64) DEFAULT NULL COMMENT 'ERP SKU编码',
    `erp_sku_id` BIGINT UNSIGNED DEFAULT NULL COMMENT 'ERP SKU ID',
    `quantity` INT UNSIGNED DEFAULT '1' COMMENT '购买数量',
    `price` DECIMAL(12,2) DEFAULT '0.00' COMMENT '单价',
    `total_amount` DECIMAL(12,2) DEFAULT '0.00' COMMENT '小计金额',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX `idx_order_id` (`order_id`),
    INDEX `idx_sku_code` (`sku_code`),
    INDEX `idx_erp_sku_id` (`erp_sku_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单项表';

-- 订单操作日志表
CREATE TABLE IF NOT EXISTS `order_operation_logs` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
    `order_id` BIGINT UNSIGNED NOT NULL COMMENT '订单ID',
    `operator_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '操作人ID',
    `operator_name` VARCHAR(64) DEFAULT NULL COMMENT '操作人名称',
    `action` VARCHAR(32) DEFAULT NULL COMMENT '操作类型',
    `action_text` VARCHAR(64) DEFAULT NULL COMMENT '操作类型文本',
    `content` VARCHAR(512) DEFAULT NULL COMMENT '操作内容',
    `before_status` VARCHAR(20) DEFAULT NULL COMMENT '操作前状态',
    `after_status` VARCHAR(20) DEFAULT NULL COMMENT '操作后状态',
    `ip` VARCHAR(45) DEFAULT NULL COMMENT 'IP地址',
    `user_agent` VARCHAR(512) DEFAULT NULL COMMENT 'User-Agent',
    `extra_data` TEXT DEFAULT NULL COMMENT '扩展数据JSON',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    INDEX `idx_order_id` (`order_id`),
    INDEX `idx_operator_id` (`operator_id`),
    INDEX `idx_action` (`action`),
    INDEX `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单操作日志表';

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/permission-service/deploy/db-migration.sql
-- ============================================================================
-- RBAC权限系统数据库迁移脚本
-- MySQL 8.0+

-- 创建角色表
CREATE TABLE IF NOT EXISTS `roles` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '角色ID',
    `name` VARCHAR(255) NOT NULL COMMENT '角色名称',
    `slug` VARCHAR(50) NOT NULL COMMENT '角色标识',
    `description` VARCHAR(500) DEFAULT NULL COMMENT '角色描述',
    `level` TINYINT UNSIGNED NOT NULL DEFAULT 50 COMMENT '角色级别(越大越高)',
    `guard_name` VARCHAR(50) NOT NULL DEFAULT 'web' COMMENT '守护名称',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `deleted_at` DATETIME DEFAULT NULL COMMENT '删除时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_roles_slug` (`slug`),
    KEY `idx_roles_level` (`level`),
    KEY `idx_roles_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='角色表';

-- 创建权限表
CREATE TABLE IF NOT EXISTS `permissions` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '权限ID',
    `name` VARCHAR(255) NOT NULL COMMENT '权限名称',
    `slug` VARCHAR(100) NOT NULL COMMENT '权限标识',
    `group_name` VARCHAR(100) DEFAULT NULL COMMENT '权限分组',
    `description` VARCHAR(500) DEFAULT NULL COMMENT '权限描述',
    `sort` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '排序',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `deleted_at` DATETIME DEFAULT NULL COMMENT '删除时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_permissions_slug` (`slug`),
    KEY `idx_permissions_group_name` (`group_name`),
    KEY `idx_permissions_deleted_at` (`deleted_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='权限表';

-- 创建角色权限关联表
CREATE TABLE IF NOT EXISTS `role_permissions` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `role_id` BIGINT UNSIGNED NOT NULL COMMENT '角色ID',
    `permission_id` BIGINT UNSIGNED NOT NULL COMMENT '权限ID',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_role_permissions_role_permission` (`role_id`, `permission_id`),
    KEY `idx_role_permissions_permission_id` (`permission_id`),
    CONSTRAINT `fk_role_permissions_role` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE,
    CONSTRAINT `fk_role_permissions_permission` FOREIGN KEY (`permission_id`) REFERENCES `permissions` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='角色权限关联表';

-- 创建用户角色关联表
CREATE TABLE IF NOT EXISTS `user_roles` (
    `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户ID',
    `role_id` BIGINT UNSIGNED NOT NULL COMMENT '角色ID',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_user_roles_user_role` (`user_id`, `role_id`),
    KEY `idx_user_roles_role_id` (`role_id`),
    CONSTRAINT `fk_user_roles_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
    CONSTRAINT `fk_user_roles_role` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户角色关联表';

-- 插入默认超级管理员角色
INSERT INTO `roles` (`name`, `slug`, `description`, `level`, `guard_name`) VALUES
('超级管理员', 'super_admin', '系统超级管理员，拥有所有权限', 100, 'web'),
('管理员', 'admin', '系统管理员，拥有大部分权限', 80, 'web'),
('普通用户', 'user', '普通用户，拥有基础权限', 50, 'web');

-- 插入默认权限
INSERT INTO `permissions` (`name`, `slug`, `group_name`, `description`, `sort`) VALUES
-- 用户模块
('用户查看', 'user.view', '用户模块', '查看用户信息', 1),
('用户创建', 'user.create', '用户模块', '创建新用户', 2),
('用户编辑', 'user.edit', '用户模块', '编辑用户信息', 3),
('用户删除', 'user.delete', '用户模块', '删除用户', 4),
-- 角色模块
('角色查看', 'role.view', '角色模块', '查看角色信息', 1),
('角色创建', 'role.create', '角色模块', '创建新角色', 2),
('角色编辑', 'role.edit', '角色模块', '编辑角色信息', 3),
('角色删除', 'role.delete', '角色模块', '删除角色', 4),
('角色分配权限', 'role.assign', '角色模块', '分配角色权限', 5),
-- 订单模块
('订单查看', 'order.view', '订单模块', '查看订单', 1),
('订单创建', 'order.create', '订单模块', '创建订单', 2),
('订单编辑', 'order.edit', '订单模块', '编辑订单', 3),
('订单删除', 'order.delete', '订单模块', '删除订单', 4),
-- 商品模块
('商品查看', 'goods.view', '商品模块', '查看商品', 1),
('商品创建', 'goods.create', '商品模块', '创建商品', 2),
('商品编辑', 'goods.edit', '商品模块', '编辑商品', 3),
('商品删除', 'goods.delete', '商品模块', '删除商品', 4),
-- 系统模块
('系统配置', 'system.config', '系统模块', '系统配置管理', 1),
('操作日志', 'system.log', '系统模块', '查看操作日志', 2);

-- 为超级管理员角色分配所有权限
INSERT INTO `role_permissions` (`role_id`, `permission_id`)
SELECT r.id, p.id FROM roles r, permissions p WHERE r.slug = 'super_admin';

-- 为管理员角色分配大部分权限（除了系统配置）
INSERT INTO `role_permissions` (`role_id`, `permission_id`)
SELECT r.id, p.id FROM roles r, permissions p 
WHERE r.slug = 'admin' AND p.slug != 'system.config';

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/print-service/src/main/resources/db/schema.sql
-- ============================================================================
-- =============================================
-- Print Service 数据库Schema
-- =============================================

-- 打印模板表
CREATE TABLE IF NOT EXISTS `print_template` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `template_code` VARCHAR(64) NOT NULL COMMENT '模板编码',
  `template_name` VARCHAR(128) NOT NULL COMMENT '模板名称',
  `template_type` VARCHAR(32) NOT NULL COMMENT '模板类型: invoice/receipt/label/express/shipping',
  `template_content` TEXT NOT NULL COMMENT '模板内容(HTML/JSON格式)',
  `description` VARCHAR(512) DEFAULT NULL COMMENT '模板描述',
  `width` DOUBLE DEFAULT NULL COMMENT '宽度(mm)',
  `height` DOUBLE DEFAULT NULL COMMENT '高度(mm)',
  `is_default` TINYINT(1) DEFAULT 0 COMMENT '是否默认: 0-否 1-是',
  `status` TINYINT(1) DEFAULT 1 COMMENT '状态: 0-禁用 1-启用',
  `creator_id` BIGINT DEFAULT NULL COMMENT '创建人ID',
  `creator_name` VARCHAR(64) DEFAULT NULL COMMENT '创建人名称',
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT(1) DEFAULT 0 COMMENT '逻辑删除标记',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_template_code` (`template_code`),
  KEY `idx_template_type` (`template_type`),
  KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='打印模板表';

-- 打印机表
CREATE TABLE IF NOT EXISTS `printer` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `printer_code` VARCHAR(64) NOT NULL COMMENT '打印机编码',
  `printer_name` VARCHAR(128) NOT NULL COMMENT '打印机名称',
  `printer_type` VARCHAR(32) NOT NULL COMMENT '打印机类型: laser/inkjet/thermal',
  `connection_type` VARCHAR(32) DEFAULT NULL COMMENT '连接方式: usb/parallel/serial/network',
  `ip_address` VARCHAR(64) DEFAULT NULL COMMENT 'IP地址(网络打印机)',
  `port` INT DEFAULT NULL COMMENT '端口',
  `mac_address` VARCHAR(64) DEFAULT NULL COMMENT '物理地址/MAC',
  `driver_name` VARCHAR(128) DEFAULT NULL COMMENT '驱动名称',
  `paper_size` VARCHAR(32) DEFAULT 'A4' COMMENT '纸张尺寸: A4/A5/58mm/80mm/custom',
  `status` TINYINT(1) DEFAULT 1 COMMENT '状态: 0-离线 1-在线 2-忙碌 3-错误',
  `description` VARCHAR(512) DEFAULT NULL COMMENT '打印机描述',
  `warehouse_id` BIGINT DEFAULT NULL COMMENT '仓库ID',
  `warehouse_name` VARCHAR(128) DEFAULT NULL COMMENT '仓库名称',
  `is_default` TINYINT(1) DEFAULT 0 COMMENT '是否默认: 0-否 1-是',
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT(1) DEFAULT 0 COMMENT '逻辑删除标记',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_printer_code` (`printer_code`),
  KEY `idx_status` (`status`),
  KEY `idx_warehouse_id` (`warehouse_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='打印机表';

-- 打印任务表
CREATE TABLE IF NOT EXISTS `print_task` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `task_no` VARCHAR(64) NOT NULL COMMENT '任务编号',
  `document_type` VARCHAR(32) DEFAULT NULL COMMENT '关联单据类型: order/invoice/delivery',
  `document_id` BIGINT DEFAULT NULL COMMENT '关联单据ID',
  `document_no` VARCHAR(64) DEFAULT NULL COMMENT '关联单据编号',
  `template_id` BIGINT NOT NULL COMMENT '模板ID',
  `template_name` VARCHAR(128) DEFAULT NULL COMMENT '模板名称',
  `printer_id` BIGINT DEFAULT NULL COMMENT '打印机ID',
  `printer_name` VARCHAR(128) DEFAULT NULL COMMENT '打印机名称',
  `copies` INT DEFAULT 1 COMMENT '打印份数',
  `task_status` VARCHAR(32) DEFAULT 'pending' COMMENT '打印状态: pending/processing/completed/failed/cancelled',
  `priority` INT DEFAULT 2 COMMENT '优先级: 1-低 2-中 3-高',
  `print_params` TEXT DEFAULT NULL COMMENT '打印参数(JSON格式)',
  `error_message` VARCHAR(512) DEFAULT NULL COMMENT '失败原因',
  `retry_count` INT DEFAULT 0 COMMENT '重试次数',
  `max_retries` INT DEFAULT 3 COMMENT '最大重试次数',
  `user_id` BIGINT DEFAULT NULL COMMENT '用户ID',
  `user_name` VARCHAR(64) DEFAULT NULL COMMENT '用户名称',
  `tenant_id` BIGINT DEFAULT NULL COMMENT '租户ID',
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `printed_at` DATETIME DEFAULT NULL COMMENT '打印完成时间',
  `deleted` TINYINT(1) DEFAULT 0 COMMENT '逻辑删除标记',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_task_no` (`task_no`),
  KEY `idx_task_status` (`task_status`),
  KEY `idx_document` (`document_type`, `document_id`),
  KEY `idx_created_at` (`created_at`),
  KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='打印任务表';

-- 打印记录表
CREATE TABLE IF NOT EXISTS `print_record` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `record_no` VARCHAR(64) NOT NULL COMMENT '记录编号',
  `task_id` BIGINT DEFAULT NULL COMMENT '任务ID',
  `task_no` VARCHAR(64) DEFAULT NULL COMMENT '任务编号',
  `template_id` BIGINT DEFAULT NULL COMMENT '模板ID',
  `template_name` VARCHAR(128) DEFAULT NULL COMMENT '模板名称',
  `printer_id` BIGINT DEFAULT NULL COMMENT '打印机ID',
  `printer_name` VARCHAR(128) DEFAULT NULL COMMENT '打印机名称',
  `document_type` VARCHAR(32) DEFAULT NULL COMMENT '单据类型',
  `document_id` BIGINT DEFAULT NULL COMMENT '单据ID',
  `document_no` VARCHAR(64) DEFAULT NULL COMMENT '单据编号',
  `copies` INT DEFAULT 1 COMMENT '打印份数',
  `print_status` VARCHAR(32) DEFAULT NULL COMMENT '打印状态: success/failed',
  `error_message` VARCHAR(512) DEFAULT NULL COMMENT '错误信息',
  `duration` BIGINT DEFAULT NULL COMMENT '打印耗时(ms)',
  `user_id` BIGINT DEFAULT NULL COMMENT '用户ID',
  `user_name` VARCHAR(64) DEFAULT NULL COMMENT '用户名称',
  `tenant_id` BIGINT DEFAULT NULL COMMENT '租户ID',
  `ip_address` VARCHAR(64) DEFAULT NULL COMMENT 'IP地址',
  `user_agent` VARCHAR(256) DEFAULT NULL COMMENT '用户代理',
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `deleted` TINYINT(1) DEFAULT 0 COMMENT '逻辑删除标记',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_record_no` (`record_no`),
  KEY `idx_task_id` (`task_id`),
  KEY `idx_document` (`document_type`, `document_id`),
  KEY `idx_print_status` (`print_status`),
  KEY `idx_created_at` (`created_at`),
  KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='打印记录表';

-- 打印配置表
CREATE TABLE IF NOT EXISTS `print_config` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `config_key` VARCHAR(128) NOT NULL COMMENT '配置键',
  `config_value` TEXT NOT NULL COMMENT '配置值',
  `config_type` VARCHAR(32) NOT NULL COMMENT '配置类型: system/tenant/template',
  `relation_id` BIGINT DEFAULT NULL COMMENT '关联ID(如租户ID/模板ID)',
  `description` VARCHAR(512) DEFAULT NULL COMMENT '配置描述',
  `status` TINYINT(1) DEFAULT 1 COMMENT '状态: 0-禁用 1-启用',
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT(1) DEFAULT 0 COMMENT '逻辑删除标记',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_config_key` (`config_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='打印配置表';

-- =============================================
-- 初始化默认配置数据
-- =============================================

-- 默认打印配置
INSERT INTO `print_config` (`config_key`, `config_value`, `config_type`, `description`, `status`) VALUES
('print.default.copies', '1', 'system', '默认打印份数', 1),
('print.default.priority', '2', 'system', '默认打印优先级', 1),
('print.task.max_retries', '3', 'system', '任务最大重试次数', 1),
('print.page.size', 'A4', 'system', '默认纸张大小', 1),
('print.encoding', 'UTF-8', 'system', '打印编码', 1);

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/product-service/init.sql
-- ============================================================================
-- SKU匹配相关表初始化脚本

-- ERP SKU表
CREATE TABLE IF NOT EXISTS `erp_skus` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `sku_code` VARCHAR(64) NOT NULL COMMENT 'SKU编码',
    `name` VARCHAR(255) NOT NULL COMMENT 'SKU名称',
    `platform_sku` VARCHAR(128) DEFAULT NULL COMMENT '平台SKU关联',
    `alias` VARCHAR(128) DEFAULT NULL COMMENT '别名（用于匹配）',
    `price` DECIMAL(10,2) DEFAULT NULL COMMENT '价格',
    `stock` INT DEFAULT 0 COMMENT '库存',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY `uk_sku_code` (`sku_code`),
    KEY `idx_alias` (`alias`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='ERP SKU表';

-- 平台SKU表
CREATE TABLE IF NOT EXISTS `platforms` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `shop_auth_id` BIGINT NOT NULL COMMENT '店铺授权ID',
    `platform_product_id` VARCHAR(128) NOT NULL COMMENT '平台商品ID',
    `platform_sku_id` VARCHAR(128) DEFAULT NULL COMMENT '平台SKU ID',
    `title` VARCHAR(512) DEFAULT NULL COMMENT '商品标题',
    `description` TEXT COMMENT '商品描述',
    `price` DECIMAL(10,2) DEFAULT NULL COMMENT '价格',
    `original_price` DECIMAL(10,2) DEFAULT NULL COMMENT '原价',
    `stock` INT DEFAULT 0 COMMENT '库存',
    `sold` INT DEFAULT 0 COMMENT '已售数量',
    `images` JSON DEFAULT NULL COMMENT '图片列表',
    `specs` JSON DEFAULT NULL COMMENT '规格属性',
    `status` VARCHAR(32) DEFAULT 'on_sale' COMMENT '状态：on_sale在售, off_sale下架, deleted已删除',
    `sync_status` VARCHAR(32) DEFAULT 'pending' COMMENT '同步状态',
    `last_sync_at` DATETIME DEFAULT NULL COMMENT '最后同步时间',
    `sync_error` TEXT COMMENT '同步错误信息',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY `idx_platform_product_id` (`platform_product_id`),
    KEY `idx_status` (`status`),
    KEY `idx_shop_auth_id` (`shop_auth_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='平台SKU表';

-- 平台SKU与ERP SKU绑定表
CREATE TABLE IF NOT EXISTS `platform_sku_bindings` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `platform_sku_id` BIGINT NOT NULL COMMENT '平台SKU ID',
    `erp_sku_id` BIGINT NOT NULL COMMENT 'ERP SKU ID',
    `is_active` TINYINT(1) DEFAULT TRUE COMMENT '是否生效',
    `bound_at` DATETIME DEFAULT NULL COMMENT '绑定时间',
    `unbound_at` DATETIME DEFAULT NULL COMMENT '解绑时间',
    `reason` VARCHAR(255) DEFAULT NULL COMMENT '绑定原因/方式',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY `idx_platform_sku_id` (`platform_sku_id`),
    KEY `idx_erp_sku_id` (`erp_sku_id`),
    KEY `idx_is_active` (`is_active`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='平台SKU与ERP SKU绑定表';

-- 匹配日志表
CREATE TABLE IF NOT EXISTS `match_logs` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `order_item_id` BIGINT NOT NULL COMMENT '订单明细ID',
    `platform_sku` VARCHAR(128) NOT NULL COMMENT '平台SKU编码',
    `erp_sku_id` BIGINT NOT NULL COMMENT '匹配的ERP SKU ID',
    `match_type` VARCHAR(32) NOT NULL COMMENT '匹配类型：manual手动, rule规则, ai',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    KEY `idx_order_item_id` (`order_item_id`),
    KEY `idx_platform_sku` (`platform_sku`),
    KEY `idx_match_type` (`match_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='匹配日志表';

-- 未匹配日志表
CREATE TABLE IF NOT EXISTS `unmatched_logs` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `order_item_id` BIGINT NOT NULL COMMENT '订单明细ID',
    `platform_sku` VARCHAR(128) NOT NULL COMMENT '平台SKU编码',
    `reason` VARCHAR(255) NOT NULL COMMENT '未匹配原因',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    KEY `idx_order_item_id` (`order_item_id`),
    KEY `idx_platform_sku` (`platform_sku`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='未匹配日志表';

-- 订单明细表（简化版，仅用于SKU匹配）
CREATE TABLE IF NOT EXISTS `order_items` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `order_id` BIGINT NOT NULL COMMENT '订单ID',
    `goods_name` VARCHAR(255) DEFAULT NULL COMMENT '商品名称',
    `platform_sku` VARCHAR(128) DEFAULT NULL COMMENT '平台SKU编码',
    `quantity` INT DEFAULT 1 COMMENT '数量',
    `price` DECIMAL(10,2) DEFAULT NULL COMMENT '单价',
    `total_amount` DECIMAL(10,2) DEFAULT NULL COMMENT '总金额',
    `match_status` TINYINT DEFAULT 0 COMMENT '匹配状态：0未匹配, 1已匹配',
    `erp_sku_id` BIGINT DEFAULT NULL COMMENT 'ERP SKU ID',
    `goods_id` BIGINT DEFAULT NULL COMMENT '商品ID',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY `idx_order_id` (`order_id`),
    KEY `idx_platform_sku` (`platform_sku`),
    KEY `idx_match_status` (`match_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单明细表';

-- 插入测试数据
INSERT INTO `erp_skus` (`sku_code`, `name`, `alias`, `price`, `stock`) VALUES
('ERP_SKU_001', '测试ERP商品', 'ERP_ALIAS_001', 89.99, 200),
('ERP_SKU_002', '另一个ERP商品', 'ERP_ALIAS_002', 79.99, 150),
('ERP_SKU_003', '平台商品A', NULL, 99.99, 100);

INSERT INTO `platforms` (`shop_auth_id`, `platform_product_id`, `platform_sku_id`, `title`, `price`, `stock`, `status`) VALUES
(1, 'PLATFORM_SKU_001', 'PSKU_001', '测试商品标题', 99.99, 100, 'on_sale'),
(1, 'PLATFORM_SKU_002', 'PSKU_002', '另一个测试商品', 88.88, 50, 'on_sale'),
(1, 'ERP_ALIAS_001', 'PSKU_003', '别名匹配测试商品', 77.77, 30, 'on_sale'),
(1, 'NO_MATCH_SKU', 'PSKU_004', '完全不匹配的商品标题XYZ', 66.66, 20, 'on_sale'),
(1, 'OFF_SALE_SKU', 'PSKU_005', '已下架商品', 55.55, 0, 'off_sale');

INSERT INTO `platform_sku_bindings` (`platform_sku_id`, `erp_sku_id`, `is_active`, `bound_at`, `reason`) VALUES
(1, 1, TRUE, NOW(), 'manual');

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/purchase-service/sql/schema.sql
-- ============================================================================
-- ============================================================
-- 采购管理模块数据库脚本
-- ============================================================

CREATE DATABASE IF NOT EXISTS purchase_db DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE purchase_db;

-- -----------------------------------------
-- 供应商表
-- -----------------------------------------
CREATE TABLE IF NOT EXISTS `supplier` (
  `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
  `supplier_code` VARCHAR(64) NOT NULL COMMENT '供应商编码',
  `name` VARCHAR(255) NOT NULL COMMENT '供应商名称',
  `contact` VARCHAR(100) COMMENT '联系人',
  `phone` VARCHAR(32) COMMENT '联系电话',
  `email` VARCHAR(128) COMMENT '电子邮箱',
  `address` VARCHAR(512) COMMENT '地址',
  `status` VARCHAR(32) NOT NULL DEFAULT 'active' COMMENT '状态: active/suspended/blacklisted',
  `tax_rate` DECIMAL(10,4) DEFAULT 0.1300 COMMENT '税率',
  `payment_method` VARCHAR(64) COMMENT '付款方式',
  `payment_period` INT COMMENT '付款周期(天)',
  `bank_name` VARCHAR(255) COMMENT '银行名称',
  `bank_account` VARCHAR(64) COMMENT '银行账号',
  `bank_branch` VARCHAR(255) COMMENT '开户行',
  `credit_code` VARCHAR(32) COMMENT '统一社会信用代码',
  `remark` VARCHAR(512) COMMENT '备注',
  `tenant_id` BIGINT UNSIGNED DEFAULT 0 COMMENT '租户ID',
  `create_by` BIGINT UNSIGNED COMMENT '创建人',
  `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_by` BIGINT UNSIGNED COMMENT '更新人',
  `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除: 0=未删除, 1=已删除',
  UNIQUE KEY `uk_supplier_code` (`supplier_code`),
  KEY `idx_status` (`status`),
  KEY `idx_name` (`name`),
  KEY `idx_tenant` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='供应商表';

-- -----------------------------------------
-- 采购订单表
-- -----------------------------------------
CREATE TABLE IF NOT EXISTS `purchase_order` (
  `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
  `order_no` VARCHAR(64) NOT NULL COMMENT '采购单号',
  `supplier_id` BIGINT UNSIGNED NOT NULL COMMENT '供应商ID',
  `supplier_name` VARCHAR(255) COMMENT '供应商名称',
  `warehouse_id` BIGINT UNSIGNED COMMENT '仓库ID',
  `warehouse_name` VARCHAR(255) COMMENT '仓库名称',
  `order_date` DATE COMMENT '订单日期',
  `expected_date` DATE COMMENT '预计到货日期',
  `status` VARCHAR(32) NOT NULL DEFAULT 'draft' COMMENT '状态: draft/pending/approved/partial_inbound/all_inbound/partial_return/completed/cancelled',
  `total_amount` DECIMAL(18,2) DEFAULT 0.00 COMMENT '订单总金额(未税)',
  `tax_rate` DECIMAL(10,4) DEFAULT 0.1300 COMMENT '税率',
  `tax_amount` DECIMAL(18,2) DEFAULT 0.00 COMMENT '税额',
  `total_with_tax` DECIMAL(18,2) DEFAULT 0.00 COMMENT '含税总金额',
  `inbound_amount` DECIMAL(18,2) DEFAULT 0.00 COMMENT '已入库金额',
  `paid_amount` DECIMAL(18,2) DEFAULT 0.00 COMMENT '已付款金额',
  `currency` VARCHAR(16) DEFAULT 'CNY' COMMENT '币种',
  `payment_method` VARCHAR(64) COMMENT '付款方式',
  `contact` VARCHAR(100) COMMENT '联系人',
  `phone` VARCHAR(32) COMMENT '联系电话',
  `delivery_address` VARCHAR(512) COMMENT '收货地址',
  `remark` VARCHAR(1024) COMMENT '备注',
  `approver_id` BIGINT UNSIGNED COMMENT '审批人',
  `approve_time` DATETIME COMMENT '审批时间',
  `approve_remark` VARCHAR(512) COMMENT '审批备注',
  `tenant_id` BIGINT UNSIGNED DEFAULT 0 COMMENT '租户ID',
  `create_by` BIGINT UNSIGNED COMMENT '创建人',
  `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_by` BIGINT UNSIGNED COMMENT '更新人',
  `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除',
  UNIQUE KEY `uk_order_no` (`order_no`),
  KEY `idx_supplier` (`supplier_id`),
  KEY `idx_status` (`status`),
  KEY `idx_order_date` (`order_date`),
  KEY `idx_tenant` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='采购订单表';

-- -----------------------------------------
-- 采购订单明细表（JSON存储在purchase_order.items）
-- 也可单独建表存储，以下为示例结构
-- -----------------------------------------
-- 采购入库单表
CREATE TABLE IF NOT EXISTS `purchase_inbound` (
  `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
  `inbound_no` VARCHAR(64) NOT NULL COMMENT '入库单号',
  `purchase_order_id` BIGINT UNSIGNED NOT NULL COMMENT '采购单ID',
  `purchase_order_no` VARCHAR(64) NOT NULL COMMENT '采购单号',
  `supplier_id` BIGINT UNSIGNED NOT NULL COMMENT '供应商ID',
  `supplier_name` VARCHAR(255) COMMENT '供应商名称',
  `warehouse_id` BIGINT UNSIGNED NOT NULL COMMENT '仓库ID',
  `warehouse_name` VARCHAR(255) COMMENT '仓库名称',
  `status` VARCHAR(32) NOT NULL DEFAULT 'pending' COMMENT '状态: pending/partial/completed/cancelled',
  `total_quantity` INT DEFAULT 0 COMMENT '入库总数量',
  `accepted_quantity` INT DEFAULT 0 COMMENT '已验收数量',
  `defective_quantity` INT DEFAULT 0 COMMENT '残次品数量',
  `total_amount` DECIMAL(18,2) DEFAULT 0.00 COMMENT '入库单总金额',
  `inbound_time` DATETIME COMMENT '实际入库时间',
  `expected_time` DATETIME COMMENT '期望到货时间',
  `remark` VARCHAR(1024) COMMENT '备注',
  `warehouse_inbound_no` VARCHAR(64) COMMENT '仓库入库单号',
  `operator_id` BIGINT UNSIGNED COMMENT '操作人ID',
  `operator_name` VARCHAR(100) COMMENT '操作人名称',
  `tenant_id` BIGINT UNSIGNED DEFAULT 0 COMMENT '租户ID',
  `create_by` BIGINT UNSIGNED COMMENT '创建人',
  `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_by` BIGINT UNSIGNED COMMENT '更新人',
  `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除',
  UNIQUE KEY `uk_inbound_no` (`inbound_no`),
  KEY `idx_purchase_order` (`purchase_order_id`),
  KEY `idx_supplier` (`supplier_id`),
  KEY `idx_warehouse` (`warehouse_id`),
  KEY `idx_status` (`status`),
  KEY `idx_tenant` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='采购入库单表';

-- -----------------------------------------
-- 采购退货单表
-- -----------------------------------------
CREATE TABLE IF NOT EXISTS `purchase_return` (
  `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
  `return_no` VARCHAR(64) NOT NULL COMMENT '退货单号',
  `purchase_order_id` BIGINT UNSIGNED NOT NULL COMMENT '采购单ID',
  `purchase_order_no` VARCHAR(64) NOT NULL COMMENT '采购单号',
  `supplier_id` BIGINT UNSIGNED NOT NULL COMMENT '供应商ID',
  `supplier_name` VARCHAR(255) COMMENT '供应商名称',
  `warehouse_id` BIGINT UNSIGNED NOT NULL COMMENT '仓库ID',
  `warehouse_name` VARCHAR(255) COMMENT '仓库名称',
  `status` VARCHAR(32) NOT NULL DEFAULT 'pending' COMMENT '状态: pending/partial/completed/cancelled',
  `total_quantity` INT DEFAULT 0 COMMENT '退货总数量',
  `total_amount` DECIMAL(18,2) DEFAULT 0.00 COMMENT '退货总金额',
  `refunded_amount` DECIMAL(18,2) DEFAULT 0.00 COMMENT '已退款金额',
  `return_reason` VARCHAR(512) COMMENT '退货原因',
  `return_type` VARCHAR(32) COMMENT '退货类型: quality/wrong/other',
  `outbound_time` DATETIME COMMENT '出库时间',
  `remark` VARCHAR(1024) COMMENT '备注',
  `warehouse_outbound_no` VARCHAR(64) COMMENT '仓库出库单号',
  `operator_id` BIGINT UNSIGNED COMMENT '操作人ID',
  `operator_name` VARCHAR(100) COMMENT '操作人名称',
  `tenant_id` BIGINT UNSIGNED DEFAULT 0 COMMENT '租户ID',
  `create_by` BIGINT UNSIGNED COMMENT '创建人',
  `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_by` BIGINT UNSIGNED COMMENT '更新人',
  `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT UNSIGNED DEFAULT 0 COMMENT '逻辑删除',
  UNIQUE KEY `uk_return_no` (`return_no`),
  KEY `idx_purchase_order` (`purchase_order_id`),
  KEY `idx_supplier` (`supplier_id`),
  KEY `idx_status` (`status`),
  KEY `idx_tenant` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='采购退货单表';

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/scheduled-task-service/deploy/docker/init.sql
-- ============================================================================
-- Docker环境初始化SQL
CREATE DATABASE IF NOT EXISTS erp_task DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE erp_task;

-- 定时任务表
CREATE TABLE IF NOT EXISTS scheduled_task (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    task_name VARCHAR(100) NOT NULL,
    description VARCHAR(500),
    task_group VARCHAR(50) NOT NULL,
    cron_expression VARCHAR(100) NOT NULL,
    task_class VARCHAR(500) NOT NULL,
    method_name VARCHAR(100),
    task_params TEXT,
    status VARCHAR(20) NOT NULL DEFAULT 'DRAFT',
    concurrent BOOLEAN NOT NULL DEFAULT TRUE,
    sync BOOLEAN NOT NULL DEFAULT FALSE,
    task_type VARCHAR(20) NOT NULL DEFAULT 'BEAN',
    xxl_job_id BIGINT,
    max_retries INT NOT NULL DEFAULT 3,
    retry_interval INT NOT NULL DEFAULT 60,
    timeout INT,
    alert_emails VARCHAR(500),
    alert_phones VARCHAR(200),
    alert_enabled BOOLEAN NOT NULL DEFAULT FALSE,
    misfire_policy VARCHAR(20) DEFAULT 'DO_NOTHING',
    next_fire_time DATETIME,
    prev_fire_time DATETIME,
    execute_count BIGINT NOT NULL DEFAULT 0,
    owner VARCHAR(50),
    remark VARCHAR(500),
    tenant_id VARCHAR(50),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    created_by VARCHAR(50),
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    updated_by VARCHAR(50),
    INDEX idx_task_name (task_name),
    INDEX idx_task_group (task_group),
    INDEX idx_task_status (status),
    INDEX idx_cron (cron_expression),
    UNIQUE KEY uk_name_group (task_name, task_group)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 任务执行日志表
CREATE TABLE IF NOT EXISTS task_execution_log (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    task_id BIGINT NOT NULL,
    task_name VARCHAR(100) NOT NULL,
    task_group VARCHAR(50),
    batch_no VARCHAR(64) NOT NULL,
    trigger_time DATETIME NOT NULL,
    start_time DATETIME,
    end_time DATETIME,
    status VARCHAR(20) NOT NULL,
    duration BIGINT,
    executor_node VARCHAR(50),
    result TEXT,
    error_trace TEXT,
    retry_count INT NOT NULL DEFAULT 0,
    is_retry BOOLEAN DEFAULT FALSE,
    task_params TEXT,
    tenant_id VARCHAR(50),
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_log_task_id (task_id),
    INDEX idx_log_status (status),
    INDEX idx_log_start_time (start_time),
    INDEX idx_log_trigger_time (trigger_time),
    INDEX idx_batch_no (batch_no)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/sku-match-service/sql/init.sql
-- ============================================================================
-- =============================================
-- SKU Match Service 数据库初始化脚本
-- =============================================

CREATE DATABASE IF NOT EXISTS erp_db;
USE erp_db;

-- ---------------------------------------------
-- 平台信息表
-- ---------------------------------------------
CREATE TABLE IF NOT EXISTS `platform_info` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '平台ID',
    `platform_code` VARCHAR(50) NOT NULL COMMENT '平台代码：taobao/jd/pdd/douyin',
    `platform_name` VARCHAR(100) NOT NULL COMMENT '平台名称',
    `logo_url` VARCHAR(500) COMMENT '平台Logo',
    `status` TINYINT DEFAULT 1 COMMENT '状态：0禁用 1启用',
    `sort_order` INT DEFAULT 0 COMMENT '排序',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY `uk_platform_code` (`platform_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='平台信息表';

-- ---------------------------------------------
-- 店铺表
-- ---------------------------------------------
CREATE TABLE IF NOT EXISTS `shop` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `platform_code` VARCHAR(50) NOT NULL COMMENT '平台代码',
    `shop_id` VARCHAR(100) NOT NULL COMMENT '店铺在平台的ID',
    `shop_name` VARCHAR(200) NOT NULL COMMENT '店铺名称',
    `auth_status` TINYINT DEFAULT 0 COMMENT '授权状态：0未授权 1已授权 2授权过期',
    `access_token` VARCHAR(500) COMMENT '访问令牌(加密存储)',
    `refresh_token` VARCHAR(500) COMMENT '刷新令牌',
    `token_expires_at` DATETIME COMMENT '令牌过期时间',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY `uk_platform_shop` (`platform_code`, `shop_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='店铺表';

-- ---------------------------------------------
-- 平台商品表（SPU）
-- ---------------------------------------------
CREATE TABLE IF NOT EXISTS `platform_spu` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `shop_id` BIGINT NOT NULL COMMENT '店铺ID',
    `platform_code` VARCHAR(50) NOT NULL COMMENT '平台代码',
    `spu_id` VARCHAR(100) NOT NULL COMMENT '平台SPU ID',
    `spu_name` VARCHAR(300) COMMENT '商品名称',
    `spu_code` VARCHAR(100) COMMENT '商品编码',
    `price` DECIMAL(12,2) COMMENT '售价',
    `original_price` DECIMAL(12,2) COMMENT '原价',
    `stock` INT DEFAULT 0 COMMENT '库存',
    `images` TEXT COMMENT '图片JSON',
    `specs` TEXT COMMENT '规格属性JSON',
    `status` VARCHAR(20) DEFAULT 'onsale' COMMENT '状态：onsale/off_sale/deleted',
    `sync_status` VARCHAR(20) DEFAULT 'synced' COMMENT '同步状态',
    `last_sync_at` DATETIME COMMENT '最后同步时间',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY `uk_shop_spu` (`shop_id`, `spu_id`),
    KEY `idx_platform_code` (`platform_code`),
    KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='平台商品SPU表';

-- ---------------------------------------------
-- 平台SKU表
-- ---------------------------------------------
CREATE TABLE IF NOT EXISTS `platform_sku` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `spu_id` BIGINT NOT NULL COMMENT 'SPU ID',
    `shop_id` BIGINT NOT NULL COMMENT '店铺ID',
    `platform_code` VARCHAR(50) NOT NULL COMMENT '平台代码',
    `sku_id` VARCHAR(100) NOT NULL COMMENT '平台SKU ID',
    `sku_code` VARCHAR(100) COMMENT 'SKU编码',
    `sku_name` VARCHAR(300) COMMENT 'SKU名称(规格组合)',
    `price` DECIMAL(12,2) COMMENT '售价',
    `stock` INT DEFAULT 0 COMMENT '库存',
    `status` VARCHAR(20) DEFAULT 'onsale' COMMENT '状态：onsale/off_sale/deleted',
    `erp_sku_id` BIGINT COMMENT '绑定的ERP SKU ID',
    `erp_sku_code` VARCHAR(100) COMMENT '绑定的ERP SKU编码',
    `erp_sku_name` VARCHAR(200) COMMENT '绑定的ERP SKU名称',
    `match_type` VARCHAR(20) COMMENT '匹配方式：manual手动/rule规则/ai',
    `match_time` DATETIME COMMENT '匹配时间',
    `matched_rule_id` BIGINT COMMENT '匹配的规则ID',
    `sync_status` VARCHAR(20) DEFAULT 'synced',
    `last_sync_at` DATETIME,
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY `uk_shop_sku` (`shop_id`, `sku_id`),
    KEY `idx_erp_sku_id` (`erp_sku_id`),
    KEY `idx_match_status` (`erp_sku_id`, `status`),
    KEY `idx_platform_code` (`platform_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='平台SKU表';

-- ---------------------------------------------
-- ERP商品SKU表（本地副本，用于匹配）
-- ---------------------------------------------
CREATE TABLE IF NOT EXISTS `erp_sku` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `sku_code` VARCHAR(100) NOT NULL COMMENT 'SKU编码',
    `sku_name` VARCHAR(200) NOT NULL COMMENT 'SKU名称',
    `barcode` VARCHAR(100) COMMENT '条形码',
    `category` VARCHAR(100) COMMENT '分类',
    `brand` VARCHAR(100) COMMENT '品牌',
    `price` DECIMAL(12,2) COMMENT '售价',
    `cost_price` DECIMAL(12,2) COMMENT '成本价',
    `stock` INT DEFAULT 0 COMMENT '库存',
    `status` VARCHAR(20) DEFAULT 'active' COMMENT '状态：active/inactive',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY `uk_sku_code` (`sku_code`),
    KEY `idx_barcode` (`barcode`),
    KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='ERP商品SKU表';

-- ---------------------------------------------
-- SKU匹配记录表（历史）
-- ---------------------------------------------
CREATE TABLE IF NOT EXISTS `sku_match_record` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `platform_sku_id` BIGINT NOT NULL COMMENT '平台SKU ID',
    `platform_sku_code` VARCHAR(100) NOT NULL COMMENT '平台SKU编码',
    `platform_sku_name` VARCHAR(300) COMMENT '平台SKU名称',
    `erp_sku_id` BIGINT NOT NULL COMMENT 'ERP SKU ID',
    `erp_sku_code` VARCHAR(100) NOT NULL COMMENT 'ERP SKU编码',
    `erp_sku_name` VARCHAR(200) COMMENT 'ERP SKU名称',
    `match_type` VARCHAR(20) NOT NULL COMMENT '匹配类型：manual手动/rule规则/ai',
    `match_rule_id` BIGINT COMMENT '匹配规则ID(rule类型时)',
    `confidence` DECIMAL(5,4) COMMENT '置信度(AI匹配)',
    `matched` TINYINT DEFAULT 1 COMMENT '是否匹配：0取消匹配 1匹配',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY `idx_platform_sku_id` (`platform_sku_id`),
    KEY `idx_erp_sku_id` (`erp_sku_id`),
    KEY `idx_match_type` (`match_type`),
    KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='SKU匹配记录表';

-- ---------------------------------------------
-- 匹配规则表
-- ---------------------------------------------
CREATE TABLE IF NOT EXISTS `sku_match_rule` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(100) NOT NULL COMMENT '规则名称',
    `priority` INT DEFAULT 0 COMMENT '优先级(数字越大优先级越高)',
    `platform` VARCHAR(50) COMMENT '适用平台，空表示全部',
    `field` VARCHAR(20) NOT NULL COMMENT '匹配字段：name名称/code编码/barcode',
    `pattern` VARCHAR(500) NOT NULL COMMENT '匹配模式/关键词',
    `replace_pattern` VARCHAR(500) COMMENT '替换模式',
    `match_type` VARCHAR(20) NOT NULL COMMENT '匹配方式：exact精确/contains包含/regex正则',
    `enabled` TINYINT DEFAULT 1 COMMENT '是否启用：0禁用 1启用',
    `match_count` INT DEFAULT 0 COMMENT '匹配次数',
    `success_count` INT DEFAULT 0 COMMENT '成功次数',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY `idx_platform` (`platform`),
    KEY `idx_enabled` (`enabled`),
    KEY `idx_priority` (`priority`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='SKU匹配规则表';

-- ---------------------------------------------
-- AI匹配配置表
-- ---------------------------------------------
CREATE TABLE IF NOT EXISTS `ai_match_config` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `enabled` TINYINT DEFAULT 0 COMMENT '是否启用AI匹配',
    `model` VARCHAR(100) DEFAULT 'gpt-4' COMMENT 'AI模型',
    `threshold` DECIMAL(5,4) DEFAULT 0.8000 COMMENT '相似度阈值',
    `auto_match` TINYINT DEFAULT 0 COMMENT '是否自动匹配(超过阈值自动绑定)',
    `similarity_field` VARCHAR(20) DEFAULT 'name' COMMENT '相似度字段：name/name+code/embedding',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='AI匹配配置表';

-- 初始化默认AI配置
INSERT INTO `ai_match_config` (`id`, `enabled`, `model`, `threshold`, `auto_match`, `similarity_field`) 
VALUES (1, 0, 'gpt-4', 0.8000, 0, 'name') ON DUPLICATE KEY UPDATE updated_at = CURRENT_TIMESTAMP;

-- ---------------------------------------------
-- 匹配任务表
-- ---------------------------------------------
CREATE TABLE IF NOT EXISTS `sku_match_task` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `task_id` VARCHAR(100) NOT NULL COMMENT '任务ID',
    `task_type` VARCHAR(20) NOT NULL COMMENT '任务类型：rule规则/ai',
    `platform` VARCHAR(50) COMMENT '执行平台',
    `status` VARCHAR(20) DEFAULT 'pending' COMMENT '状态：pending/running/completed/failed',
    `total_count` INT DEFAULT 0 COMMENT '总SKU数',
    `matched_count` INT DEFAULT 0 COMMENT '匹配成功数',
    `failed_count` INT DEFAULT 0 COMMENT '失败数',
    `error_msg` TEXT COMMENT '错误信息',
    `started_at` DATETIME COMMENT '开始时间',
    `completed_at` DATETIME COMMENT '完成时间',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY `uk_task_id` (`task_id`),
    KEY `idx_status` (`status`),
    KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='匹配任务表';

-- ---------------------------------------------
-- 初始化平台数据
-- ---------------------------------------------
INSERT INTO `platform_info` (`platform_code`, `platform_name`, `logo_url`, `status`, `sort_order`) VALUES
('taobao', '淘宝', 'https://img.alicdn.com/tfs/TB1XlF3RpXXXXc6XXXXXXXXXXXX-200-200.png', 1, 1),
('jd', '京东', 'https://img1.360buyimg.com/pop_jdshop/imgs/200-200.png', 1, 2),
('pdd', '拼多多', 'https://static.pinduoduo.com/favicon.ico', 1, 3),
('douyin', '抖音', 'https://www.douyin.com/favicon.ico', 1, 4)
ON DUPLICATE KEY UPDATE updated_at = CURRENT_TIMESTAMP;

-- ---------------------------------------------
-- 示例店铺数据
-- ---------------------------------------------
INSERT INTO `shop` (`platform_code`, `shop_id`, `shop_name`, `auth_status`) VALUES
('taobao', 'tb1', '淘宝官方旗舰店', 1),
('taobao', 'tb2', '淘宝专营店', 1),
('jd', 'jd1', '京东自营店', 1),
('jd', 'jd2', '京东专营店', 1),
('pdd', 'pdd1', '拼多多官方旗舰店', 1),
('pdd', 'pdd2', '拼多多专营店', 1),
('douyin', 'dy1', '抖音小店', 1),
('douyin', 'dy2', '抖音专营店', 1)
ON DUPLICATE KEY UPDATE updated_at = CURRENT_TIMESTAMP;

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/supplier-service/scripts/init.sql
-- ============================================================================
-- ============================================
-- Supplier Service 数据库初始化脚本
-- ============================================

-- 供应商表
CREATE TABLE IF NOT EXISTS `suppliers` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `supplier_code` VARCHAR(50) NOT NULL COMMENT '供应商编码' unique,
  `supplier_name` VARCHAR(200) NOT NULL COMMENT '供应商名称',
  `supplier_type` VARCHAR(50) COMMENT '供应商类型: manufacturer/trader/agent/individual',
  `industry` VARCHAR(100) COMMENT '所属行业',
  `business_license` VARCHAR(100) COMMENT '统一社会信用代码',
  `registered_capital` DECIMAL(15,2) COMMENT '注册资本',
  `establishment_date` VARCHAR(20) COMMENT '成立日期',
  `legal_person` VARCHAR(100) COMMENT '法定代表人',
  `phone` VARCHAR(50) COMMENT '联系电话',
  `email` VARCHAR(100) COMMENT '电子邮箱',
  `website` VARCHAR(200) COMMENT '官方网站',
  `province` VARCHAR(50) COMMENT '省份',
  `city` VARCHAR(50) COMMENT '城市',
  `district` VARCHAR(50) COMMENT '区县',
  `address` VARCHAR(500) COMMENT '详细地址',
  `main_business` TEXT COMMENT '主营业务',
  `status` VARCHAR(50) DEFAULT 'pending' COMMENT '合作状态: pending/active/inactive/blacklist',
  `grade` VARCHAR(10) DEFAULT 'C' COMMENT '供应商等级: A/B/C/D',
  `credit_score` INT DEFAULT 60 COMMENT '信用评分 (0-100)',
  `is_internal` INT DEFAULT 0 COMMENT '是否为内供: 0-外部 1-内部',
  `cooperation_start_date` VARCHAR(20) COMMENT '合作开始日期',
  `cooperation_end_date` VARCHAR(20) COMMENT '合作结束日期',
  `settlement_method` VARCHAR(50) COMMENT '结算方式: prepaid/postpaid/monthly',
  `payment_days` INT COMMENT '付款周期(天)',
  `minimum_order_quantity` DECIMAL(15,3) COMMENT '最低起订量',
  `remark` TEXT COMMENT '备注',
  `attachments` TEXT COMMENT '附件(JSON数组)',
  `audit_status` VARCHAR(50) DEFAULT 'pending' COMMENT '审核状态: pending/approved/rejected',
  `audit_comment` TEXT COMMENT '审核备注',
  `auditor_id` BIGINT COMMENT '审核人ID',
  `audit_time` DATETIME COMMENT '审核时间',
  `version` INT DEFAULT 0 COMMENT '乐观锁版本号',
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` INT DEFAULT 0 COMMENT '逻辑删除标记',
  PRIMARY KEY (`id`),
  INDEX `idx_supplier_code` (`supplier_code`),
  INDEX `idx_supplier_name` (`supplier_name`),
  INDEX `idx_status` (`status`),
  INDEX `idx_grade` (`grade`),
  INDEX `idx_audit_status` (`audit_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='供应商主表';

-- 供应商联系人表
CREATE TABLE IF NOT EXISTS `supplier_contacts` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `supplier_id` BIGINT NOT NULL COMMENT '供应商ID',
  `contact_name` VARCHAR(100) NOT NULL COMMENT '联系人姓名',
  `gender` VARCHAR(10) COMMENT '性别: male/female',
  `department` VARCHAR(100) COMMENT '部门',
  `position` VARCHAR(100) COMMENT '职务',
  `mobile` VARCHAR(50) COMMENT '手机号码',
  `phone` VARCHAR(50) COMMENT '固定电话',
  `email` VARCHAR(100) COMMENT '电子邮箱',
  `qq` VARCHAR(50) COMMENT 'QQ号码',
  `wechat` VARCHAR(100) COMMENT '微信',
  `is_primary` INT DEFAULT 0 COMMENT '是否为主要联系人: 0-否 1-是',
  `is_emergency` INT DEFAULT 0 COMMENT '是否为紧急联系人: 0-否 1-是',
  `remark` TEXT COMMENT '备注',
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` INT DEFAULT 0 COMMENT '逻辑删除标记',
  PRIMARY KEY (`id`),
  INDEX `idx_supplier_id` (`supplier_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='供应商联系人表';

-- 供应商银行账户表
CREATE TABLE IF NOT EXISTS `supplier_bank_accounts` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `supplier_id` BIGINT NOT NULL COMMENT '供应商ID',
  `account_name` VARCHAR(200) NOT NULL COMMENT '开户名称',
  `bank_name` VARCHAR(200) NOT NULL COMMENT '开户银行',
  `bank_account` VARCHAR(100) NOT NULL COMMENT '银行账号',
  `branch_name` VARCHAR(200) COMMENT '开户支行',
  `branch_code` VARCHAR(50) COMMENT '银行联行号',
  `province` VARCHAR(50) COMMENT '开户省份',
  `city` VARCHAR(50) COMMENT '开户城市',
  `account_type` VARCHAR(50) COMMENT '账户类型: basic/general/reserve',
  `is_default` INT DEFAULT 0 COMMENT '是否为默认账户: 0-否 1-是',
  `balance` DECIMAL(15,2) DEFAULT 0 COMMENT '账户余额',
  `reserved_phone` VARCHAR(50) COMMENT '银行预留手机号',
  `remark` TEXT COMMENT '备注',
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` INT DEFAULT 0 COMMENT '逻辑删除标记',
  PRIMARY KEY (`id`),
  INDEX `idx_supplier_id` (`supplier_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='供应商银行账户表';

-- 供应商评级表
CREATE TABLE IF NOT EXISTS `supplier_ratings` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `supplier_id` BIGINT NOT NULL COMMENT '供应商ID',
  `rating_period` VARCHAR(50) COMMENT '评价周期: monthly/quarterly/annual',
  `rating_year` INT COMMENT '评价年份',
  `rating_month` INT COMMENT '评价月份',
  `quality_score` DECIMAL(5,2) COMMENT '质量评分(0-100)',
  `delivery_score` DECIMAL(5,2) COMMENT '交期评分(0-100)',
  `price_score` DECIMAL(5,2) COMMENT '价格评分(0-100)',
  `service_score` DECIMAL(5,2) COMMENT '服务评分(0-100)',
  `overall_score` DECIMAL(5,2) COMMENT '综合评分(0-100)',
  `grade` VARCHAR(10) COMMENT '供应商等级: A/B/C/D',
  `evaluator_id` BIGINT COMMENT '评价人ID',
  `evaluator_name` VARCHAR(100) COMMENT '评价人姓名',
  `evaluation_time` DATETIME COMMENT '评价时间',
  `strengths` TEXT COMMENT '优点',
  `weaknesses` TEXT COMMENT '不足',
  `suggestions` TEXT COMMENT '改进建议',
  `remark` TEXT COMMENT '备注',
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` INT DEFAULT 0 COMMENT '逻辑删除标记',
  PRIMARY KEY (`id`),
  INDEX `idx_supplier_id` (`supplier_id`),
  INDEX `idx_rating_year_month` (`rating_year`, `rating_month`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='供应商评级表';

-- 采购询价表
CREATE TABLE IF NOT EXISTS `procurement_inquiries` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `inquiry_no` VARCHAR(50) NOT NULL COMMENT '询价单号' unique,
  `supplier_id` BIGINT NOT NULL COMMENT '供应商ID',
  `supplier_name` VARCHAR(200) COMMENT '供应商名称',
  `inquiry_type` VARCHAR(50) COMMENT '询价类型: product/material/service',
  `product_id` BIGINT COMMENT '商品ID',
  `product_name` VARCHAR(200) COMMENT '商品名称',
  `product_spec` VARCHAR(200) COMMENT '商品规格',
  `unit` VARCHAR(20) COMMENT '商品单位',
  `quantity` DECIMAL(15,3) COMMENT '询价数量',
  `expected_delivery_date` VARCHAR(20) COMMENT '期望交货日期',
  `inquiry_status` VARCHAR(50) DEFAULT 'draft' COMMENT '询价状态: draft/sent/replied/compared/confirmed/cancelled',
  `inquiry_date` DATETIME COMMENT '询价日期',
  `quote_deadline` VARCHAR(20) COMMENT '报价截止日期',
  `quoted_price` DECIMAL(15,4) COMMENT '报价金额',
  `currency` VARCHAR(10) DEFAULT 'CNY' COMMENT '报价币种',
  `quote_valid_until` VARCHAR(20) COMMENT '报价有效期',
  `delivery_cycle` INT COMMENT '交货周期(天)',
  `quality_standard` VARCHAR(500) COMMENT '质量标准',
  `payment_terms` VARCHAR(200) COMMENT '付款方式',
  `remark` TEXT COMMENT '备注',
  `is_selected` INT DEFAULT 0 COMMENT '是否已选择: 0-否 1-是',
  `selection_reason` TEXT COMMENT '选择原因',
  `creator_id` BIGINT COMMENT '创建人ID',
  `creator_name` VARCHAR(100) COMMENT '创建人姓名',
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` INT DEFAULT 0 COMMENT '逻辑删除标记',
  PRIMARY KEY (`id`),
  INDEX `idx_inquiry_no` (`inquiry_no`),
  INDEX `idx_supplier_id` (`supplier_id`),
  INDEX `idx_inquiry_status` (`inquiry_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='采购询价表';

-- 供应商操作日志表
CREATE TABLE IF NOT EXISTS `supplier_operation_logs` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `supplier_id` BIGINT NOT NULL COMMENT '供应商ID',
  `operator_id` BIGINT COMMENT '操作人ID',
  `operator_name` VARCHAR(100) COMMENT '操作人姓名',
  `operation_type` VARCHAR(100) COMMENT '操作类型',
  `operation_desc` VARCHAR(500) COMMENT '操作描述',
  `before_data` TEXT COMMENT '操作前数据(JSON)',
  `after_data` TEXT COMMENT '操作后数据(JSON)',
  `ip` VARCHAR(50) COMMENT 'IP地址',
  `user_agent` VARCHAR(500) COMMENT 'User-Agent',
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`),
  INDEX `idx_supplier_id` (`supplier_id`),
  INDEX `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='供应商操作日志表';

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/system-tool-service/sql/schema.sql
-- ============================================================================
-- System Tool Service Database Schema
-- Run this script to create required tables

-- System Configs Table
CREATE TABLE IF NOT EXISTS `system_configs` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `tenant_id` INT NOT NULL DEFAULT 1,
    `config_group` VARCHAR(64) NOT NULL COMMENT 'Config group name',
    `config_key` VARCHAR(128) NOT NULL COMMENT 'Config key',
    `config_value` TEXT COMMENT 'Config value',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY `uk_tenant_group_key` (`tenant_id`, `config_group`, `config_key`),
    INDEX `idx_tenant_group` (`tenant_id`, `config_group`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='System configuration table';

-- Operation Logs Table
CREATE TABLE IF NOT EXISTS `operation_logs` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `tenant_id` INT NOT NULL DEFAULT 1,
    `user_id` INT COMMENT 'User ID',
    `user_name` VARCHAR(64) COMMENT 'User name',
    `module` VARCHAR(64) COMMENT 'Module name',
    `action` VARCHAR(64) COMMENT 'Action name',
    `method` VARCHAR(10) COMMENT 'HTTP method',
    `path` VARCHAR(255) COMMENT 'Request path',
    `ip` VARCHAR(45) COMMENT 'Client IP',
    `user_agent` VARCHAR(512) COMMENT 'User agent',
    `request_params` TEXT COMMENT 'Request parameters',
    `response_code` INT COMMENT 'HTTP response code',
    `execution_time` INT COMMENT 'Execution time in ms',
    `remark` VARCHAR(512) COMMENT 'Remark',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX `idx_user_id` (`user_id`),
    INDEX `idx_module` (`module`),
    INDEX `idx_created_at` (`created_at`),
    INDEX `idx_user_module_action` (`user_id`, `module`, `action`),
    INDEX `idx_tenant_created` (`tenant_id`, `created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Operation logs table';

-- Audit Logs Table
CREATE TABLE IF NOT EXISTS `audit_logs` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `tenant_id` INT NOT NULL DEFAULT 1,
    `user_id` INT COMMENT 'User ID',
    `user_name` VARCHAR(64) COMMENT 'User name',
    `module` VARCHAR(64) COMMENT 'Module name',
    `action` VARCHAR(64) COMMENT 'Action name',
    `target_type` VARCHAR(64) COMMENT 'Target entity type',
    `target_id` BIGINT COMMENT 'Target entity ID',
    `old_value` TEXT COMMENT 'Old value (JSON)',
    `new_value` TEXT COMMENT 'New value (JSON)',
    `ip` VARCHAR(45) COMMENT 'Client IP',
    `user_agent` VARCHAR(512) COMMENT 'User agent',
    `result` VARCHAR(32) COMMENT 'Operation result',
    `error_message` VARCHAR(512) COMMENT 'Error message if failed',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX `idx_module_action` (`module`, `action`),
    INDEX `idx_user_id` (`user_id`),
    INDEX `idx_target` (`target_type`, `target_id`),
    INDEX `idx_created_at` (`created_at`),
    INDEX `idx_tenant_created` (`tenant_id`, `created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Audit logs table';

-- Pull Records Table (for data cleanup)
CREATE TABLE IF NOT EXISTS `pull_records` (
    `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
    `tenant_id` INT NOT NULL DEFAULT 1,
    `platform` VARCHAR(32) COMMENT 'Platform name (pdd/jd/dy)',
    `pull_type` VARCHAR(32) COMMENT 'Pull type (order/product/waybill)',
    `status` VARCHAR(32) COMMENT 'Status (pending/success/failed)',
    `start_time` DATETIME COMMENT 'Pull start time',
    `end_time` DATETIME COMMENT 'Pull end time',
    `total_count` INT DEFAULT 0 COMMENT 'Total pulled count',
    `success_count` INT DEFAULT 0 COMMENT 'Success count',
    `fail_count` INT DEFAULT 0 COMMENT 'Failed count',
    `error_message` VARCHAR(1024) COMMENT 'Error message if failed',
    `request_params` TEXT COMMENT 'Request parameters',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX `idx_platform` (`platform`),
    INDEX `idx_created_at` (`created_at`),
    INDEX `idx_tenant_status` (`tenant_id`, `status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Pull records table for tracking sync operations';

-- Insert default system configs
INSERT INTO `system_configs` (`tenant_id`, `config_group`, `config_key`, `config_value`) VALUES
(1, 'basic', 'site_name', 'ERP SaaS 系统'),
(1, 'basic', 'site_url', 'https://erp.example.com'),
(1, 'basic', 'site_logo', '/logo.png'),
(1, 'basic', 'copyright', '© 2024 ERP SaaS'),
(1, 'order', 'auto_approve', 'false'),
(1, 'order', 'approve_timeout_minutes', '30'),
(1, 'order', 'auto_reject_timeout_minutes', '60'),
(1, 'order', 'enable_stock_freeze', 'true'),
(1, 'order', 'enable_audit_log', 'true'),
(1, 'stock', 'enable_warning', 'true'),
(1, 'stock', 'default_warning_threshold', '10'),
(1, 'stock', 'enable_negative_stock', 'false'),
(1, 'stock', 'auto_adjust_warning', 'false'),
(1, 'express', 'default_express', 'SF'),
(1, 'express', 'enable_electronic_waybill', 'true'),
(1, 'express', 'waybill_cache_hours', '24'),
(1, 'notify', 'enable_dingtalk', 'false'),
(1, 'notify', 'dingtalk_webhook', ''),
(1, 'notify', 'enable_sms', 'false'),
(1, 'notify', 'sms_provider', 'aliyun'),
(1, 'notify', 'notify_audit_timeout', 'true'),
(1, 'notify', 'notify_stock_warning', 'true'),
(1, 'security', 'enable_mfa', 'true'),
(1, 'security', 'session_timeout_minutes', '120'),
(1, 'security', 'max_login_attempts', '5'),
(1, 'security', 'password_min_length', '8'),
(1, 'security', 'enable_captcha', 'true'),
(1, 'storage', 'driver', 'local'),
(1, 'storage', 'local_path', '/storage/uploads'),
(1, 'storage', 'cos_bucket', ''),
(1, 'storage', 'cos_region', 'ap-guangzhou'),
(1, 'storage', 'cos_secret_id', ''),
(1, 'storage', 'cos_secret_key', '')
ON DUPLICATE KEY UPDATE `config_value` = VALUES(`config_value`);

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/warehouse-service/sql/init.sql
-- ============================================================================
-- ============================================
-- 云仓服务数据库初始化脚本
-- ============================================

-- 创建仓库表
CREATE TABLE IF NOT EXISTS `warehouse` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '仓库ID',
    `name` VARCHAR(255) NOT NULL COMMENT '仓库名称',
    `type` VARCHAR(20) NOT NULL COMMENT '仓库类型: erp=ERP仓库, cloud=云仓',
    `cloud_system` VARCHAR(50) DEFAULT NULL COMMENT '云仓系统: jst=聚水潭, wdt=旺店通, qimen=奇门',
    `owner_code` VARCHAR(100) DEFAULT NULL COMMENT '货主编码',
    `cloud_code` VARCHAR(100) DEFAULT NULL COMMENT '云仓编码',
    `app_key` VARCHAR(255) DEFAULT NULL COMMENT 'AppKey',
    `app_secret` VARCHAR(255) DEFAULT NULL COMMENT 'AppSecret',
    `api_url` VARCHAR(500) DEFAULT NULL COMMENT 'API地址',
    `remark` TEXT DEFAULT NULL COMMENT '备注',
    `enabled` TINYINT(1) DEFAULT 1 COMMENT '是否启用',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    KEY `idx_name` (`name`),
    KEY `idx_type` (`type`),
    KEY `idx_cloud_system` (`cloud_system`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='仓库表';

-- 创建仓库模板绑定表
CREATE TABLE IF NOT EXISTS `warehouse_template_binding` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '绑定ID',
    `warehouse_id` BIGINT NOT NULL COMMENT '仓库ID',
    `platform` VARCHAR(50) NOT NULL COMMENT '平台: taobao, jd, douyin, etc.',
    `template_id` BIGINT NOT NULL COMMENT '模板ID',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_warehouse_platform` (`warehouse_id`, `platform`),
    KEY `idx_warehouse_id` (`warehouse_id`),
    KEY `idx_platform` (`platform`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='仓库模板绑定表';

-- 创建云仓订单同步日志表
CREATE TABLE IF NOT EXISTS `cloud_order_sync_log` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '日志ID',
    `warehouse_id` BIGINT NOT NULL COMMENT '仓库ID',
    `order_type` VARCHAR(20) NOT NULL COMMENT '订单类型: purchase=采购, sale=销售',
    `order_no` VARCHAR(100) NOT NULL COMMENT '订单号',
    `push_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '推送时间',
    `status` VARCHAR(20) NOT NULL COMMENT '状态: pending=待处理, success=成功, failed=失败',
    `request_data` TEXT DEFAULT NULL COMMENT '请求数据',
    `response_data` TEXT DEFAULT NULL COMMENT '响应数据',
    `error_message` TEXT DEFAULT NULL COMMENT '错误信息',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    PRIMARY KEY (`id`),
    KEY `idx_warehouse_id` (`warehouse_id`),
    KEY `idx_order_no` (`order_no`),
    KEY `idx_status` (`status`),
    KEY `idx_push_time` (`push_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='云仓订单同步日志表';

-- 创建云仓库存同步日志表
CREATE TABLE IF NOT EXISTS `cloud_stock_sync_log` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '日志ID',
    `warehouse_id` BIGINT NOT NULL COMMENT '仓库ID',
    `sku_code` VARCHAR(100) NOT NULL COMMENT 'SKU编码',
    `sync_type` VARCHAR(20) NOT NULL COMMENT '同步类型: query=查询, adjust=调整',
    `quantity` INT DEFAULT NULL COMMENT '库存数量',
    `sync_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '同步时间',
    `status` VARCHAR(20) NOT NULL COMMENT '状态: pending=待处理, success=成功, failed=失败',
    `response_data` TEXT DEFAULT NULL COMMENT '响应数据',
    `error_message` TEXT DEFAULT NULL COMMENT '错误信息',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    PRIMARY KEY (`id`),
    KEY `idx_warehouse_id` (`warehouse_id`),
    KEY `idx_sku_code` (`sku_code`),
    KEY `idx_sync_time` (`sync_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='云仓库存同步日志表';

-- ============================================
-- 初始化测试数据
-- ============================================

-- 插入测试仓库
INSERT INTO `warehouse` (`name`, `type`, `cloud_system`, `owner_code`, `cloud_code`, `app_key`, `app_secret`, `api_url`, `remark`, `enabled`)
VALUES 
    ('ERP主仓库', 'erp', NULL, NULL, NULL, NULL, NULL, NULL, 'ERP系统主仓库', 1),
    ('聚水潭云仓', 'cloud', 'jst', 'OWNER001', 'WH_JST_001', 'jst_app_key_xxx', 'jst_app_secret_xxx', 'https://open.jushuitan.com/api', '聚水潭测试云仓', 1),
    ('旺店通云仓', 'cloud', 'wdt', 'OWNER002', 'WH_WDT_001', 'wdt_app_key_xxx', 'wdt_app_secret_xxx', 'https://api.wdtms.com', '旺店通测试云仓', 1);

-- ============================================
-- ERP本地库存相关表
-- ============================================

-- 库存表
CREATE TABLE IF NOT EXISTS `stock` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '库存ID',
    `sku_code` VARCHAR(100) NOT NULL COMMENT 'SKU编码',
    `sku_name` VARCHAR(255) DEFAULT NULL COMMENT 'SKU名称',
    `warehouse_id` BIGINT NOT NULL COMMENT '仓库ID',
    `quantity` INT DEFAULT 0 COMMENT '总库存数量',
    `locked_quantity` INT DEFAULT 0 COMMENT '锁定数量',
    `reserved_quantity` INT DEFAULT 0 COMMENT '预扣数量（冻结）',
    `defective_quantity` INT DEFAULT 0 COMMENT '残次品数量',
    `warning_threshold` INT DEFAULT 10 COMMENT '预警阈值',
    `version` INT DEFAULT 0 COMMENT '乐观锁版本号',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_sku_warehouse` (`sku_code`, `warehouse_id`),
    KEY `idx_warehouse_id` (`warehouse_id`),
    KEY `idx_sku_code` (`sku_code`),
    KEY `idx_warning_threshold` (`warning_threshold`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='库存表';

-- 库存流水日志表
CREATE TABLE IF NOT EXISTS `stock_log` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '日志ID',
    `sku_code` VARCHAR(100) NOT NULL COMMENT 'SKU编码',
    `warehouse_id` BIGINT NOT NULL COMMENT '仓库ID',
    `change_type` VARCHAR(50) NOT NULL COMMENT '变更类型: inbound/outbound/lock/unlock/reserve/confirm/cancel/ship/defective_inbound/adjust',
    `before_quantity` INT DEFAULT 0 COMMENT '变更前库存',
    `change_quantity` INT NOT NULL COMMENT '变更数量',
    `after_quantity` INT DEFAULT 0 COMMENT '变更后库存',
    `order_id` BIGINT DEFAULT NULL COMMENT '关联订单ID',
    `related_no` VARCHAR(100) DEFAULT NULL COMMENT '关联单号',
    `delivery_no` VARCHAR(100) DEFAULT NULL COMMENT '运单号',
    `remark` TEXT DEFAULT NULL COMMENT '备注',
    `operator_id` BIGINT DEFAULT NULL COMMENT '操作人ID',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    PRIMARY KEY (`id`),
    KEY `idx_sku_code` (`sku_code`),
    KEY `idx_warehouse_id` (`warehouse_id`),
    KEY `idx_change_type` (`change_type`),
    KEY `idx_order_id` (`order_id`),
    KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='库存流水日志表';

-- 入库单表
CREATE TABLE IF NOT EXISTS `inbound_order` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '入库单ID',
    `inbound_no` VARCHAR(50) NOT NULL COMMENT '入库单号',
    `inbound_type` VARCHAR(20) NOT NULL COMMENT '入库类型: purchase=采购入库, return=退货入库, transfer=调拨入库',
    `warehouse_id` BIGINT NOT NULL COMMENT '仓库ID',
    `related_no` VARCHAR(100) DEFAULT NULL COMMENT '关联单号',
    `supplier_id` BIGINT DEFAULT NULL COMMENT '供应商ID',
    `supplier_name` VARCHAR(255) DEFAULT NULL COMMENT '供应商名称',
    `status` VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT '状态: pending=待入库, partial=部分入库, completed=已完成, cancelled=已取消',
    `remark` TEXT DEFAULT NULL COMMENT '备注',
    `operator_id` BIGINT DEFAULT NULL COMMENT '操作人ID',
    `operator_name` VARCHAR(100) DEFAULT NULL COMMENT '操作人名称',
    `expected_time` DATETIME DEFAULT NULL COMMENT '预计到货时间',
    `inbound_time` DATETIME DEFAULT NULL COMMENT '实际入库时间',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_inbound_no` (`inbound_no`),
    KEY `idx_warehouse_id` (`warehouse_id`),
    KEY `idx_inbound_type` (`inbound_type`),
    KEY `idx_status` (`status`),
    KEY `idx_related_no` (`related_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='入库单表';

-- 出库单表
CREATE TABLE IF NOT EXISTS `outbound_order` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '出库单ID',
    `outbound_no` VARCHAR(50) NOT NULL COMMENT '出库单号',
    `outbound_type` VARCHAR(20) NOT NULL COMMENT '出库类型: sale=销售出库, transfer=调拨出库',
    `warehouse_id` BIGINT NOT NULL COMMENT '仓库ID',
    `target_warehouse_id` BIGINT DEFAULT NULL COMMENT '目标仓库ID（调拨出库时）',
    `related_no` VARCHAR(100) DEFAULT NULL COMMENT '关联订单号',
    `customer_id` BIGINT DEFAULT NULL COMMENT '客户ID',
    `customer_name` VARCHAR(255) DEFAULT NULL COMMENT '客户名称',
    `status` VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT '状态: pending=待出库, partial=部分出库, completed=已完成, cancelled=已取消',
    `logistics_company` VARCHAR(100) DEFAULT NULL COMMENT '物流公司',
    `tracking_no` VARCHAR(100) DEFAULT NULL COMMENT '运单号',
    `remark` TEXT DEFAULT NULL COMMENT '备注',
    `operator_id` BIGINT DEFAULT NULL COMMENT '操作人ID',
    `operator_name` VARCHAR(100) DEFAULT NULL COMMENT '操作人名称',
    `outbound_time` DATETIME DEFAULT NULL COMMENT '出库时间',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_outbound_no` (`outbound_no`),
    KEY `idx_warehouse_id` (`warehouse_id`),
    KEY `idx_outbound_type` (`outbound_type`),
    KEY `idx_status` (`status`),
    KEY `idx_related_no` (`related_no`),
    KEY `idx_tracking_no` (`tracking_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='出库单表';

-- 调拨单表
CREATE TABLE IF NOT EXISTS `transfer_order` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '调拨单ID',
    `transfer_no` VARCHAR(50) NOT NULL COMMENT '调拨单号',
    `source_warehouse_id` BIGINT NOT NULL COMMENT '源仓库ID',
    `target_warehouse_id` BIGINT NOT NULL COMMENT '目标仓库ID',
    `status` VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT '状态: pending=待调拨, in_transit=调拨中, received=已收货, cancelled=已取消',
    `remark` TEXT DEFAULT NULL COMMENT '备注',
    `operator_id` BIGINT DEFAULT NULL COMMENT '操作人ID',
    `operator_name` VARCHAR(100) DEFAULT NULL COMMENT '操作人名称',
    `expected_ship_time` DATETIME DEFAULT NULL COMMENT '预计发货时间',
    `ship_time` DATETIME DEFAULT NULL COMMENT '实际发货时间',
    `receive_time` DATETIME DEFAULT NULL COMMENT '收货时间',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_transfer_no` (`transfer_no`),
    KEY `idx_source_warehouse_id` (`source_warehouse_id`),
    KEY `idx_target_warehouse_id` (`target_warehouse_id`),
    KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='调拨单表';

-- 库存预警配置表
CREATE TABLE IF NOT EXISTS `stock_alert_config` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '配置ID',
    `tenant_id` BIGINT NOT NULL COMMENT '租户ID',
    `global_threshold` INT DEFAULT 10 COMMENT '全局预警阈值',
    `enabled` TINYINT(1) DEFAULT 1 COMMENT '是否启用',
    `auto_check_enabled` TINYINT(1) DEFAULT 0 COMMENT '是否自动检查',
    `check_interval_minutes` INT DEFAULT 60 COMMENT '检查间隔（分钟）',
    `notify_only_when_critical` TINYINT(1) DEFAULT 0 COMMENT '仅严重时通知',
    `alert_channels` VARCHAR(500) DEFAULT '["system"]' COMMENT '预警渠道JSON',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='库存预警配置表';

-- 库存预警通知配置表
CREATE TABLE IF NOT EXISTS `stock_alert_notification` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '配置ID',
    `tenant_id` BIGINT NOT NULL COMMENT '租户ID',
    `email_enabled` TINYINT(1) DEFAULT 0 COMMENT '邮箱通知是否启用',
    `email_recipients` VARCHAR(500) DEFAULT NULL COMMENT '邮箱收件人（逗号分隔）',
    `dingtalk_enabled` TINYINT(1) DEFAULT 0 COMMENT '钉钉通知是否启用',
    `dingtalk_webhook_url` VARCHAR(500) DEFAULT NULL COMMENT '钉钉Webhook URL',
    `dingtalk_secret` VARCHAR(200) DEFAULT NULL COMMENT '钉钉签名密钥',
    `dingtalk_at_mobiles` VARCHAR(500) DEFAULT NULL COMMENT '钉钉@手机号（逗号分隔）',
    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='库存预警通知配置表';

-- 来源: /root/.openclaw/workspace/erp-java-backend/services/waybill-service/deploy/sql/init.sql
-- ============================================================================
-- ===============================================
-- 运单服务数据库初始化脚本
-- 数据库: erp_db
-- ===============================================

-- ----------------------------
-- 1. 运单表 waybills
-- ----------------------------
CREATE TABLE IF NOT EXISTS `waybills` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `order_id` BIGINT NOT NULL COMMENT '订单ID',
    `express_code` VARCHAR(50) NOT NULL COMMENT '快递公司编码',
    `waybill_no` VARCHAR(100) NOT NULL COMMENT '运单号',
    `print_content` TEXT COMMENT '电子面单打印内容(JSON)',
    `status` VARCHAR(20) NOT NULL DEFAULT 'unused' COMMENT '状态: unused-未使用, used-已使用, cancelled-已取消, void-已作废',
    `used_at` DATETIME COMMENT '使用时间',
    `cancelled_at` DATETIME COMMENT '取消时间',
    `cancel_reason` VARCHAR(500) COMMENT '取消原因',
    `voided_at` DATETIME COMMENT '作废时间',
    `void_reason` VARCHAR(500) COMMENT '作废原因',
    `tenant_id` BIGINT COMMENT '租户ID',
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `deleted_at` DATETIME COMMENT '删除时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_waybill_no` (`waybill_no`),
    KEY `idx_order_id` (`order_id`),
    KEY `idx_express_code` (`express_code`),
    KEY `idx_status` (`status`),
    KEY `idx_tenant_id` (`tenant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运单表';

-- ----------------------------
-- 2. 运单状态跟踪表 waybill_status
-- ----------------------------
CREATE TABLE IF NOT EXISTS `waybill_status` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `waybill_no` VARCHAR(100) NOT NULL COMMENT '运单号',
    `carrier` VARCHAR(50) COMMENT '快递公司编码',
    `status` VARCHAR(30) COMMENT '状态',
    `location` VARCHAR(255) COMMENT '当前位置',
    `description` VARCHAR(500) COMMENT '状态描述',
    `last_trace_time` DATETIME COMMENT '最后轨迹时间',
    `signed_time` DATETIME COMMENT '签收时间',
    `receiver_name` VARCHAR(100) COMMENT '签收人姓名',
    `receiver_phone` VARCHAR(20) COMMENT '签收人电话',
    `tenant_id` BIGINT COMMENT '租户ID',
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    PRIMARY KEY (`id`),
    UNIQUE KEY `uk_waybill_no` (`waybill_no`),
    KEY `idx_carrier` (`carrier`),
    KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='运单状态跟踪表';

-- ----------------------------
-- 3. 物流轨迹明细表 logistics_traces
-- ----------------------------
CREATE TABLE IF NOT EXISTS `logistics_traces` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `waybill_no` VARCHAR(100) NOT NULL COMMENT '运单号',
    `carrier` VARCHAR(50) COMMENT '快递公司编码',
    `status` VARCHAR(50) COMMENT '状态',
    `location` VARCHAR(255) COMMENT '地点',
    `description` VARCHAR(500) COMMENT '轨迹描述',
    `trace_time` DATETIME COMMENT '轨迹时间',
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    PRIMARY KEY (`id`),
    KEY `idx_waybill_no` (`waybill_no`),
    KEY `idx_trace_time` (`trace_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='物流轨迹明细表';

-- ----------------------------
-- 4. 打印日志表 print_logs
-- ----------------------------
CREATE TABLE IF NOT EXISTS `print_logs` (
    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
    `order_id` BIGINT NOT NULL COMMENT '订单ID',
    `action` VARCHAR(20) NOT NULL COMMENT '操作类型: print-打印, reprint-补打, change-换单',
    `operator_id` BIGINT COMMENT '操作人ID',
    `old_waybill_no` VARCHAR(100) COMMENT '原运单号',
    `new_waybill_no` VARCHAR(100) COMMENT '新运单号',
    `reason` VARCHAR(500) COMMENT '原因',
    `tenant_id` BIGINT COMMENT '租户ID',
    `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    PRIMARY KEY (`id`),
    KEY `idx_order_id` (`order_id`),
    KEY `idx_action` (`action`),
    KEY `idx_operator_id` (`operator_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='打印日志表';

-- ===============================================
-- 运单状态说明
-- ===============================================
-- waybills.status:
--   unused    - 未使用（面单申请后默认状态）
--   used     - 已使用（扫描出库等操作后）
--   cancelled - 已取消（向快递公司取消成功）
--   void     - 已作废（系统内部作废）
--
-- waybill_status.status:
--   pending          - 待揽收
--   in_transit       - 运输中
--   out_for_delivery - 派送中
--   signed           - 已签收
--   rejected         - 拒收
--   returned         - 退回
--   exception        - 异常
-- ===============================================
