diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9b3e2f4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +# 发布包与历史对照目录不进入源码仓库 +/push/ +/zx/ + +# 演示页、源码压缩备份和不再由导出代码读取的年份模板不进入源码仓库 +/Lifecycle/productLifecycleManagement/public/workhour-demo.html +/Lifecycle/productLifecycleManagement/scripts/sync-workhour-demo.mjs +/Lifecycle/productLifecycleManagement/src/src.zip +/Lifecycle/productLifecycleManagement/src/backup.zip +/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Templates/Workhour/*.xlsx diff --git a/SK_ERP_WebService/.editorconfig b/Lifecycle/SK_ERP_WebService/.editorconfig similarity index 100% rename from SK_ERP_WebService/.editorconfig rename to Lifecycle/SK_ERP_WebService/.editorconfig diff --git a/SK_ERP_WebService/.gitattributes b/Lifecycle/SK_ERP_WebService/.gitattributes similarity index 100% rename from SK_ERP_WebService/.gitattributes rename to Lifecycle/SK_ERP_WebService/.gitattributes diff --git a/SK_ERP_WebService/.gitignore b/Lifecycle/SK_ERP_WebService/.gitignore similarity index 100% rename from SK_ERP_WebService/.gitignore rename to Lifecycle/SK_ERP_WebService/.gitignore diff --git a/Lifecycle/SK_ERP_WebService/Database/workhour_erp_snapshot_migration.sql b/Lifecycle/SK_ERP_WebService/Database/workhour_erp_snapshot_migration.sql new file mode 100644 index 0000000..9938bcb --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/Database/workhour_erp_snapshot_migration.sql @@ -0,0 +1,17 @@ +-- 工时模块 ERP 工单快照表。 +-- 仅新增工时模块自己的表,不修改原有 work_order_info / dict_box_type。 +USE lifecircle; + +CREATE TABLE IF NOT EXISTS workhour_order_product ( + work_order_code VARCHAR(64) NOT NULL, + dev_code VARCHAR(100) NOT NULL, + product_number VARCHAR(128) NULL, + product_name VARCHAR(255) NULL, + product_mode VARCHAR(255) NULL, + manu_num INT NOT NULL DEFAULT 0, + inbound_num INT NOT NULL DEFAULT 0, + last_fetched_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (work_order_code, dev_code), + KEY ix_workhour_order_product_dev (dev_code), + KEY ix_workhour_order_product_fetched (last_fetched_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; diff --git a/Lifecycle/SK_ERP_WebService/Database/workhour_non_order_abnormal_migration.sql b/Lifecycle/SK_ERP_WebService/Database/workhour_non_order_abnormal_migration.sql new file mode 100644 index 0000000..f315ccc --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/Database/workhour_non_order_abnormal_migration.sql @@ -0,0 +1,23 @@ +-- Enable non-normal work-hour records without an ERP work order. +-- Compatible with MySQL 5.7; run after workhour_schema.sql. +USE lifecircle; + +ALTER TABLE workhour_record + MODIFY COLUMN work_order_code VARCHAR(64) NULL, + MODIFY COLUMN dev_code VARCHAR(100) NULL; + +SET @workhour_product_name_exists = ( + SELECT COUNT(*) + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 'workhour_record' + AND column_name = 'product_name' +); +SET @workhour_product_name_sql = IF( + @workhour_product_name_exists = 0, + 'ALTER TABLE workhour_record ADD COLUMN product_name VARCHAR(255) NULL AFTER dev_code', + 'SELECT 1' +); +PREPARE workhour_product_name_stmt FROM @workhour_product_name_sql; +EXECUTE workhour_product_name_stmt; +DEALLOCATE PREPARE workhour_product_name_stmt; diff --git a/Lifecycle/SK_ERP_WebService/Database/workhour_schema.sql b/Lifecycle/SK_ERP_WebService/Database/workhour_schema.sql new file mode 100644 index 0000000..9087df2 --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/Database/workhour_schema.sql @@ -0,0 +1,182 @@ +-- 工时模块初始化脚本。目标数据库为 MySqlDbContext 使用的 lifecircle。 +-- 正常工时按流程大类授权;非正常工时在独立分组中按基板、调试、总装、包装授权。 +-- 基板和调试的正常工时按板件与工序维护;整机权限拆成整机调试、整机总装、包装三类。 + +USE lifecircle; + +CREATE TABLE IF NOT EXISTS dict_process ( + process_id INT NOT NULL AUTO_INCREMENT, + dict_type VARCHAR(24) NOT NULL, + category VARCHAR(32) NOT NULL, + group_name VARCHAR(64) NOT NULL, + process_name VARCHAR(128) NOT NULL, + sort INT NOT NULL DEFAULT 10, + is_valid TINYINT(1) NOT NULL DEFAULT 1, + PRIMARY KEY (process_id), + UNIQUE KEY uq_dict_process (dict_type, category, group_name, process_name), + KEY ix_dict_process_lookup (dict_type, category, is_valid, sort) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS rela_user_workhour_scope ( + user_id INT NOT NULL, + category VARCHAR(32) NOT NULL, + PRIMARY KEY (user_id, category), + KEY ix_user_workhour_scope_category (category) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +CREATE TABLE IF NOT EXISTS workhour_record ( + record_id BIGINT NOT NULL AUTO_INCREMENT, + work_order_code VARCHAR(64) NULL, + dev_code VARCHAR(100) NULL, + product_name VARCHAR(255) NULL, + mfg_month CHAR(7) NOT NULL, + business_segment VARCHAR(32) NULL COMMENT '智慧用电/智能家居/安防报警', + category VARCHAR(32) NOT NULL, + group_name VARCHAR(64) NOT NULL, + process_name VARCHAR(128) NOT NULL, + dict_type VARCHAR(24) NOT NULL, + qty INT NOT NULL, + minutes INT NOT NULL, + user_id INT NOT NULL, + work_date DATE NULL, + remark TEXT NULL, + create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (record_id), + KEY ix_workhour_record_scope (category, group_name, process_name, dict_type), + KEY ix_workhour_record_order (work_order_code, dev_code, category, group_name, process_name, dict_type), + KEY ix_workhour_record_month (mfg_month, category, dict_type), + KEY ix_workhour_record_segment_month (business_segment, mfg_month, dict_type), + KEY ix_workhour_record_user (user_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- 工时模块独立保存金蝶工单产品快照,不写入原有 work_order_info / dict_box_type。 +CREATE TABLE IF NOT EXISTS workhour_order_product ( + work_order_code VARCHAR(64) NOT NULL, + dev_code VARCHAR(100) NOT NULL, + product_number VARCHAR(128) NULL, + product_name VARCHAR(255) NULL, + product_mode VARCHAR(255) NULL, + manu_num INT NOT NULL DEFAULT 0, + inbound_num INT NOT NULL DEFAULT 0, + last_fetched_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (work_order_code, dev_code), + KEY ix_workhour_order_product_dev (dev_code), + KEY ix_workhour_order_product_fetched (last_fetched_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +INSERT INTO dict_process (dict_type, category, group_name, process_name, sort, is_valid) VALUES +('正常工时', '基板', '主板', '贴片', 10, 1), +('正常工时', '基板', '主板', '锡检', 20, 1), +('正常工时', '基板', '主板', '插补', 30, 1), +('正常工时', '基板', '主板', '加工', 40, 1), +('正常工时', '基板', '小板', '贴片', 10, 1), +('正常工时', '基板', '小板', '锡检', 20, 1), +('正常工时', '基板', '小板', '插补', 30, 1), +('正常工时', '基板', '小板', '加工', 40, 1), +('正常工时', '基板', '按键板', '贴片', 10, 1), +('正常工时', '基板', '按键板', '锡检', 20, 1), +('正常工时', '基板', '按键板', '插补', 30, 1), +('正常工时', '基板', '按键板', '加工', 40, 1), +('正常工时', '基板', '整机', '贴片', 10, 1), +('正常工时', '基板', '整机', '锡检', 20, 1), +('正常工时', '基板', '整机', '插补', 30, 1), +('正常工时', '基板', '整机', '加工', 40, 1), +('正常工时', '基板', '显示板', '贴片', 10, 1), +('正常工时', '基板', '显示板', '锡检', 20, 1), +('正常工时', '基板', '显示板', '插补', 30, 1), +('正常工时', '基板', '显示板', '加工', 40, 1), +('正常工时', '基板', '模块小板', '贴片', 10, 1), +('正常工时', '基板', '模块小板', '锡检', 20, 1), +('正常工时', '基板', '模块小板', '插补', 30, 1), +('正常工时', '基板', '模块小板', '加工', 40, 1), +('正常工时', '基板', '灯板', '贴片', 10, 1), +('正常工时', '基板', '灯板', '锡检', 20, 1), +('正常工时', '基板', '电源板', '贴片', 10, 1), +('正常工时', '基板', '电源板', '锡检', 20, 1), +('正常工时', '基板', '电源板', '插补', 30, 1), +('正常工时', '基板', '电源板', '加工', 40, 1), +('正常工时', '基板', '计数模块小板', '贴片', 10, 1), +('正常工时', '基板', '计数模块小板', '锡检', 20, 1), +('正常工时', '基板', '计数模块小板', '插补', 30, 1), +('正常工时', '基板', '转接板', '贴片', 10, 1), +('正常工时', '基板', '转接板', '锡检', 20, 1), +('正常工时', '基板', '通讯板', '贴片', 10, 1), +('正常工时', '基板', '通讯板', '锡检', 20, 1), +('正常工时', '基板', '通讯板', '插补', 30, 1), +('正常工时', '基板', '通讯板', '加工', 40, 1), +('正常工时', '基板', '采集板', '贴片', 10, 1), +('正常工时', '基板', '采集板', '锡检', 20, 1), +('正常工时', '基板', '采集板', '插补', 30, 1), +('正常工时', '基板', '采集板', '加工', 40, 1), +('正常工时', '基板', '面板', '贴片', 10, 1), +('正常工时', '基板', '面板', '锡检', 20, 1), +('正常工时', '基板', '面板', '插补', 30, 1), +('正常工时', '基板', '面板', '加工', 40, 1), +('正常工时', '整机', '整机', '整机调试', 10, 1), +('正常工时', '整机', '整机', '整机总装', 20, 1), +('正常工时', '整机', '整机', '包装', 30, 1), +('非正常工时', '全部组别', '全部组别', '程序升级', 10, 1), +('非正常工时', '全部组别', '全部组别', '硬件升级', 20, 1), +('非正常工时', '全部组别', '全部组别', '其他', 30, 1) +ON DUPLICATE KEY UPDATE sort = VALUES(sort), is_valid = VALUES(is_valid); + +-- 按模板大类维护工序:基板与调试工序都按板件选择。 +UPDATE dict_process +SET is_valid = 0 +WHERE dict_type = '正常工时' + AND category = '基板' + AND process_name NOT IN ('贴片', '锡检', '插补', '加工'); + +UPDATE dict_process +SET is_valid = 0 +WHERE dict_type = '正常工时' + AND category = '基板' + AND group_name = '整机'; + +UPDATE dict_process +SET is_valid = 0 +WHERE dict_type = '正常工时' + AND category = '整机'; + +UPDATE dict_process +SET is_valid = 0 +WHERE dict_type = '正常工时' + AND category = '调试'; + +UPDATE workhour_record +SET category = '调试' +WHERE dict_type = '正常工时' + AND category IN ('基板', '整机', '调试') + AND process_name IN ('烧写程序', '打二维码', '调试', '刷三防漆'); + +INSERT INTO dict_process (dict_type, category, group_name, process_name, sort, is_valid) +SELECT '正常工时', '基板', board.group_name, process.process_name, process.sort, 1 +FROM ( + SELECT '主板' AS group_name UNION ALL SELECT '单板' UNION ALL SELECT '小板' + UNION ALL SELECT '按键板' UNION ALL SELECT '显示板' UNION ALL SELECT '模块小板' + UNION ALL SELECT '灯板' UNION ALL SELECT '电源板' UNION ALL SELECT '计数模块小板' + UNION ALL SELECT '转接板' UNION ALL SELECT '通讯板' UNION ALL SELECT '采集板' + UNION ALL SELECT '面板' +) AS board +CROSS JOIN ( + SELECT 10 AS sort, '贴片' AS process_name UNION ALL SELECT 20, '锡检' + UNION ALL SELECT 30, '插补' UNION ALL SELECT 40, '加工' +) AS process +WHERE 1 = 1 +ON DUPLICATE KEY UPDATE sort = VALUES(sort), is_valid = VALUES(is_valid); + +INSERT INTO dict_process (dict_type, category, group_name, process_name, sort, is_valid) +SELECT '正常工时', '调试', board.group_name, process.process_name, process.sort, 1 +FROM ( + SELECT '主板' AS group_name UNION ALL SELECT '单板' UNION ALL SELECT '小板' + UNION ALL SELECT '按键板' UNION ALL SELECT '显示板' UNION ALL SELECT '模块小板' + UNION ALL SELECT '灯板' UNION ALL SELECT '电源板' UNION ALL SELECT '计数模块小板' + UNION ALL SELECT '转接板' UNION ALL SELECT '通讯板' UNION ALL SELECT '采集板' + UNION ALL SELECT '面板' +) AS board +CROSS JOIN ( + SELECT 10 AS sort, '烧写程序' AS process_name UNION ALL SELECT 20, '打二维码' + UNION ALL SELECT 30, '调试' UNION ALL SELECT 40, '刷三防漆' +) AS process +WHERE 1 = 1 +ON DUPLICATE KEY UPDATE sort = VALUES(sort), is_valid = VALUES(is_valid); diff --git a/Lifecycle/SK_ERP_WebService/Database/workhour_template_segment_migration.sql b/Lifecycle/SK_ERP_WebService/Database/workhour_template_segment_migration.sql new file mode 100644 index 0000000..61c8d07 --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/Database/workhour_template_segment_migration.sql @@ -0,0 +1,148 @@ +-- Existing workhour_record tables: keep historical records with a NULL segment +-- until an administrator assigns their real board. New submissions require a segment. +USE lifecircle; + +SET @workhour_segment_sql = ( + SELECT IF(COUNT(*) = 0, + 'ALTER TABLE workhour_record ADD COLUMN business_segment VARCHAR(32) NULL COMMENT ''智慧用电/智能家居/安防报警'' AFTER mfg_month', + 'SELECT 1') + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 'workhour_record' + AND column_name = 'business_segment' +); +PREPARE workhour_segment_stmt FROM @workhour_segment_sql; +EXECUTE workhour_segment_stmt; +DEALLOCATE PREPARE workhour_segment_stmt; + +SET @workhour_segment_index_sql = ( + SELECT IF(COUNT(*) = 0, + 'CREATE INDEX ix_workhour_record_segment_month ON workhour_record (business_segment, mfg_month, dict_type)', + 'SELECT 1') + FROM information_schema.statistics + WHERE table_schema = DATABASE() + AND table_name = 'workhour_record' + AND index_name = 'ix_workhour_record_segment_month' +); +PREPARE workhour_segment_index_stmt FROM @workhour_segment_index_sql; +EXECUTE workhour_segment_index_stmt; +DEALLOCATE PREPARE workhour_segment_index_stmt; + +-- Board names and normal process rows mirror the product/board matrix in the supplied templates. +INSERT IGNORE INTO dict_process (dict_type, category, group_name, process_name, sort, is_valid) VALUES +('正常工时', '基板', '主板', '贴片', 10, 1), +('正常工时', '基板', '主板', '锡检', 20, 1), +('正常工时', '基板', '主板', '插补', 30, 1), +('正常工时', '基板', '主板', '加工', 40, 1), +('正常工时', '基板', '单板', '贴片', 10, 1), +('正常工时', '基板', '单板', '锡检', 20, 1), +('正常工时', '基板', '单板', '插补', 30, 1), +('正常工时', '基板', '单板', '加工', 40, 1), +('正常工时', '基板', '小板', '贴片', 10, 1), +('正常工时', '基板', '小板', '锡检', 20, 1), +('正常工时', '基板', '小板', '插补', 30, 1), +('正常工时', '基板', '小板', '加工', 40, 1), +('正常工时', '基板', '按键板', '贴片', 10, 1), +('正常工时', '基板', '按键板', '锡检', 20, 1), +('正常工时', '基板', '按键板', '插补', 30, 1), +('正常工时', '基板', '按键板', '加工', 40, 1), +('正常工时', '基板', '显示板', '贴片', 10, 1), +('正常工时', '基板', '显示板', '锡检', 20, 1), +('正常工时', '基板', '显示板', '插补', 30, 1), +('正常工时', '基板', '显示板', '加工', 40, 1), +('正常工时', '基板', '模块小板', '贴片', 10, 1), +('正常工时', '基板', '模块小板', '锡检', 20, 1), +('正常工时', '基板', '模块小板', '插补', 30, 1), +('正常工时', '基板', '模块小板', '加工', 40, 1), +('正常工时', '基板', '灯板', '贴片', 10, 1), +('正常工时', '基板', '灯板', '锡检', 20, 1), +('正常工时', '基板', '灯板', '插补', 30, 1), +('正常工时', '基板', '灯板', '加工', 40, 1), +('正常工时', '基板', '电源板', '贴片', 10, 1), +('正常工时', '基板', '电源板', '锡检', 20, 1), +('正常工时', '基板', '电源板', '插补', 30, 1), +('正常工时', '基板', '电源板', '加工', 40, 1), +('正常工时', '基板', '计数模块小板', '贴片', 10, 1), +('正常工时', '基板', '计数模块小板', '锡检', 20, 1), +('正常工时', '基板', '计数模块小板', '插补', 30, 1), +('正常工时', '基板', '计数模块小板', '加工', 40, 1), +('正常工时', '基板', '转接板', '贴片', 10, 1), +('正常工时', '基板', '转接板', '锡检', 20, 1), +('正常工时', '基板', '转接板', '插补', 30, 1), +('正常工时', '基板', '转接板', '加工', 40, 1), +('正常工时', '基板', '通讯板', '贴片', 10, 1), +('正常工时', '基板', '通讯板', '锡检', 20, 1), +('正常工时', '基板', '通讯板', '插补', 30, 1), +('正常工时', '基板', '通讯板', '加工', 40, 1), +('正常工时', '基板', '采集板', '贴片', 10, 1), +('正常工时', '基板', '采集板', '锡检', 20, 1), +('正常工时', '基板', '采集板', '插补', 30, 1), +('正常工时', '基板', '采集板', '加工', 40, 1), +('正常工时', '基板', '面板', '贴片', 10, 1), +('正常工时', '基板', '面板', '锡检', 20, 1), +('正常工时', '基板', '面板', '插补', 30, 1), +('正常工时', '基板', '面板', '加工', 40, 1), +('正常工时', '基板', '面板', '刷三防漆', 80, 1); + +-- 把错分的调试记录归回“调试”,保留填报时选定的板件。 +UPDATE workhour_record +SET category = '调试' +WHERE dict_type = '正常工时' + AND category IN ('基板', '整机', '调试') + AND process_name IN ('烧写程序', '打二维码', '调试', '刷三防漆'); + +-- 停用旧字典中的错分工序和旧版整机汇总行。 +UPDATE dict_process +SET is_valid = 0 +WHERE dict_type = '正常工时' + AND category = '基板' + AND process_name NOT IN ('贴片', '锡检', '插补', '加工'); + +UPDATE dict_process +SET is_valid = 0 +WHERE dict_type = '正常工时' + AND category = '基板' + AND group_name = '整机'; + +UPDATE dict_process +SET is_valid = 0 +WHERE dict_type = '正常工时' + AND category = '整机'; + +UPDATE dict_process +SET is_valid = 0 +WHERE dict_type = '正常工时' + AND category = '调试'; + +-- 基板与调试流程都按板件区分;整机直填仍固定在“整机”组内。 +INSERT INTO dict_process (dict_type, category, group_name, process_name, sort, is_valid) +SELECT '正常工时', '基板', board.group_name, process.process_name, process.sort, 1 +FROM ( + SELECT '主板' AS group_name UNION ALL SELECT '单板' UNION ALL SELECT '小板' + UNION ALL SELECT '按键板' UNION ALL SELECT '显示板' UNION ALL SELECT '模块小板' + UNION ALL SELECT '灯板' UNION ALL SELECT '电源板' UNION ALL SELECT '计数模块小板' + UNION ALL SELECT '转接板' UNION ALL SELECT '通讯板' UNION ALL SELECT '采集板' + UNION ALL SELECT '面板' +) AS board +CROSS JOIN ( + SELECT 10 AS sort, '贴片' AS process_name UNION ALL SELECT 20, '锡检' + UNION ALL SELECT 30, '插补' UNION ALL SELECT 40, '加工' +) AS process +WHERE 1 = 1 +ON DUPLICATE KEY UPDATE sort = VALUES(sort), is_valid = VALUES(is_valid); + +INSERT INTO dict_process (dict_type, category, group_name, process_name, sort, is_valid) +SELECT '正常工时', '调试', board.group_name, process.process_name, process.sort, 1 +FROM ( + SELECT '主板' AS group_name UNION ALL SELECT '单板' UNION ALL SELECT '小板' + UNION ALL SELECT '按键板' UNION ALL SELECT '显示板' UNION ALL SELECT '模块小板' + UNION ALL SELECT '灯板' UNION ALL SELECT '电源板' UNION ALL SELECT '计数模块小板' + UNION ALL SELECT '转接板' UNION ALL SELECT '通讯板' UNION ALL SELECT '采集板' + UNION ALL SELECT '面板' +) AS board +CROSS JOIN ( + SELECT 10 AS sort, '烧写程序' AS process_name UNION ALL SELECT 20, '打二维码' + UNION ALL SELECT 30, '调试' UNION ALL SELECT 40, '刷三防漆' +) AS process +WHERE 1 = 1 +ON DUPLICATE KEY UPDATE sort = VALUES(sort), is_valid = VALUES(is_valid); diff --git a/SK_ERP_WebService/SK_ERP_WebService.sln b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService.sln similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService.sln rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService.sln diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/ERP/SGMRAAController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/ERP/SGMRAAController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/ERP/SGMRAAController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/ERP/SGMRAAController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Open/DeviceController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Open/DeviceController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Open/DeviceController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Open/DeviceController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Open/ProductController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Open/ProductController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Open/ProductController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Open/ProductController.cs diff --git a/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Open/QrcodeController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Open/QrcodeController.cs new file mode 100644 index 0000000..4f061b3 --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Open/QrcodeController.cs @@ -0,0 +1,72 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; +using NSwag.Annotations; +using SK_ERP_WebService.Model; +using SK_ERP_WebService.Model.MySql; +using SK_ERP_WebService.Service; +using SqlSugar; + +namespace SK_ERP_WebService.Controllers.Open +{ + /// + /// 产品相关接口 + /// + [Route("api/open/[controller]/[action]")] + [ApiController] + [ApiExplorerSettings(GroupName = "open")] + [OpenApiTag("Qrcode", Description = "产品相关接口")] + public class QrcodeController : ControllerBase + { + /// + /// 日志组件 + /// + private readonly ILogger _logger; + + /// + /// 构造函数 + /// + /// + /// + public QrcodeController( + ILogger logger) + { + _logger = logger; + } + + /// + /// 设备入库 + /// + /// 记录内容 + /// + [HttpPost] + public async Task> Record( + [FromServices] QRCodeContext qrCode, + [FromBody] QRRecordCreateModel model) + { + _logger.LogInformation("设备唯一码入库-D:{model}", JsonConvert.SerializeObject(model)); + var box = await qrCode.Queryable() + .Where(it => it.UniqueCode == model.UniqueCode) + .FirstAsync(); + if (box != null) + { + return SKResponseResult.Get(SKResponseCode.Fail, "唯一码已经重复了", false); + } + ZHCodeInfo record = new() + { + UniqueCode = model.UniqueCode, + Operator = model.Operator, + PanelType = model.PanelType, + MFDate = DateTime.Now, + ICCID = model.ICCID, + IMEI = model.IMEI + }; + var result = await qrCode.Insertable(record).ExecuteCommandAsync() > 0; + if (result) + { + return SKResponseResult.Get(SKResponseCode.OK, SKResponseJsonMsg.OPERATION_SUCCESS, result); + } + return SKResponseResult.Get(SKResponseCode.Fail, SKResponseJsonMsg.OPERATION_FAIL, result); + } + } +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/BoxController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/BoxController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/BoxController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/BoxController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ClientController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ClientController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ClientController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ClientController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/CustomerController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/CustomerController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/CustomerController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/CustomerController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/DeviceController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/DeviceController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/DeviceController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/DeviceController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/DictController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/DictController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/DictController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/DictController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/InstockController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/InstockController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/InstockController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/InstockController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/LogisticsController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/LogisticsController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/LogisticsController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/LogisticsController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ManuRepairController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ManuRepairController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ManuRepairController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ManuRepairController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/OrderController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/OrderController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/OrderController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/OrderController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/OutstockController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/OutstockController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/OutstockController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/OutstockController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ProductController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ProductController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ProductController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ProductController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RemodifyController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RemodifyController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RemodifyController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RemodifyController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RepairController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RepairController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RepairController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RepairController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RepairCountController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RepairCountController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RepairCountController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RepairCountController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RetstockController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RetstockController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RetstockController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RetstockController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ReworkController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ReworkController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ReworkController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/ReworkController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RoleController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RoleController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RoleController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/RoleController.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/UserController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/UserController.cs similarity index 61% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/UserController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/UserController.cs index c66ad2a..45eb399 100644 --- a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/UserController.cs +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/UserController.cs @@ -52,7 +52,7 @@ namespace SK_ERP_WebService.Controllers [FromQuery] string account, [FromQuery] string password) { - _logger.LogInformation("用户登陆,账号:{account},密码:{password},来源:{address}", account, password, HttpContext.Connection.RemoteIpAddress?.ToString() ?? "未知"); + _logger.LogInformation("用户登陆,账号:{account},来源:{address}", account, HttpContext.Connection.RemoteIpAddress?.ToString() ?? "未知"); //获取用户信息 var user = await _mysql.Queryable() .Where(it => it.Account == account) @@ -113,23 +113,83 @@ namespace SK_ERP_WebService.Controllers var userNewData = await _mysql.Queryable() .Where(it => it.UserId == user.UserId) .FirstAsync(); + if (userNewData == null) + { + return SKResponseResult.Get(SKResponseCode.Fail, "用户信息错误", null); + } + + var workhourCategories = await _mysql.Queryable() + .Where(it => it.UserId == userNewData.UserId) + .Select(it => it.Category) + .ToListAsync(); + userNewData.WorkhourCategories = workhourCategories.Distinct().ToList(); + //获取角色信息及角色权限 var role = await _mysql.Queryable() - .Where(it => it.RoleId == user.RoleId) + .Where(it => it.RoleId == userNewData.RoleId) .Includes(it => it.Menus) .FirstAsync(); - if(role.Menus != null && role.Menus.Count > 0) + if (role == null) { - var ids = role.Menus.Select(it => it.MenuId).Cast().ToArray();//要过滤的ID列表 - var menus = await _mysql.Queryable() - .ToTreeAsync(it => it.Child, it => it.LeadId, 0, ids);//有特殊处理,没上级的会自动构建 - role.Menus = menus; + return SKResponseResult.Get(SKResponseCode.Fail, "用户角色信息错误", null); + } + if (role.Menus != null && role.Menus.Count > 0) + { + var ids = role.Menus.Select(it => it.MenuId).Cast().ToArray(); + role.Menus = await _mysql.Queryable() + .ToTreeAsync(it => it.Child, it => it.LeadId, 0, ids); + } + role.Menus ??= new List(); + // 工时入口由逐人分配的流程范围控制,不受角色菜单授权影响。 + RemoveWorkhourMenus(role.Menus); + if (userNewData.WorkhourCategories.Count > 0) + { + role.Menus.Add(new DictMenu + { + MenuId = -1, + MenuName = "工时填报", + MenuUrl = "/workhour", + LeadId = 0, + Child = new List() + }); + role.Menus.Add(new DictMenu + { + MenuId = -2, + MenuName = "工时统计", + MenuUrl = "/workhourStat", + LeadId = 0, + Child = new List() + }); + } + if (userNewData.RoleId < 3) + { + role.Menus.Add(new DictMenu + { + MenuId = -3, + MenuName = "工序字典", + MenuUrl = "/workhourProcess", + LeadId = 0, + Child = new List() + }); } - userNewData.Role = role;//赋值最新的角色数据及其权限并返回 + userNewData.Role = role; return SKResponseResult.Get(SKResponseCode.OK, "获取成功", userNewData); } + private static void RemoveWorkhourMenus(List menus) + { + foreach (var menu in menus) + { + if (menu.Child != null) + { + RemoveWorkhourMenus(menu.Child); + } + } + menus.RemoveAll(it => it.MenuUrl != null + && it.MenuUrl.StartsWith("/workhour", StringComparison.Ordinal)); + } + /// /// 用户列表 /// @@ -149,6 +209,7 @@ namespace SK_ERP_WebService.Controllers .Where(it => it.RoleId >= user.RoleId) .Includes(it => it.Role) .ToListAsync(); + await AttachWorkhourCategories(list); return SKResponseResult.Get(SKResponseCode.OK, "获取成功", list); } else @@ -160,6 +221,7 @@ namespace SK_ERP_WebService.Controllers .Where(it => it.Account.StartsWith(code)) .Includes(it => it.Role) .ToListAsync(); + await AttachWorkhourCategories(list); return SKResponseResult.Get(SKResponseCode.OK, "获取成功", list); } else @@ -168,12 +230,148 @@ namespace SK_ERP_WebService.Controllers .Where(it => it.UserId == user.UserId) .Includes(it => it.Role) .ToListAsync(); + await AttachWorkhourCategories(list); return SKResponseResult.Get(SKResponseCode.OK, "获取成功", list); } } } + /// + /// 工时权限选项。包含正常工时大类与非正常工时分组。 + /// + [HttpGet] + [TokenFilter] + public async Task?>> WorkhourScopeOptions() + { + if (HttpContext.Items["user"] is not UserBasicInfo actor || !CanManageAnyWorkhourScope(actor)) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "无权限", null); + } + return SKResponseResult.Get(SKResponseCode.OK, "获取成功", await GetWorkhourScopeOptions()); + } + + /// + /// 获取指定人员当前的工时填报范围。 + /// + [HttpGet] + [TokenFilter] + public async Task?>> WorkhourScopeList([FromQuery] int userId) + { + if (HttpContext.Items["user"] is not UserBasicInfo actor) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "用户信息错误", null); + } + var target = await _mysql.Queryable().Where(it => it.UserId == userId).FirstAsync(); + if (target == null || !CanManageWorkhourScope(actor, target)) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "无权限或人员不存在", null); + } + var categories = await _mysql.Queryable() + .Where(it => it.UserId == userId) + .Select(it => it.Category) + .ToListAsync(); + return SKResponseResult.Get(SKResponseCode.OK, "获取成功", categories.Distinct().ToList()); + } + + /// + /// 设置指定人员的工时填报范围;空列表表示撤销其全部填报权限。 + /// + [HttpPost] + [TokenFilter] + public async Task> WorkhourScopeUpdate([FromBody] UserWorkhourScopeUpdateModel model) + { + if (HttpContext.Items["user"] is not UserBasicInfo actor) + { + return SKResponseResult.Get(SKResponseCode.Fail, "用户信息错误", false); + } + var target = await _mysql.Queryable().Where(it => it.UserId == model.UserId).FirstAsync(); + if (target == null || !CanManageWorkhourScope(actor, target)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "无权限或人员不存在", false); + } + + var options = await GetWorkhourScopeOptions(); + var categories = (model.Categories ?? new List()) + .Where(it => !string.IsNullOrWhiteSpace(it)) + .Distinct() + .ToList(); + if (categories.Any(it => !options.Contains(it))) + { + return SKResponseResult.Get(SKResponseCode.Fail, "工时权限包含无效选项", false); + } + + _mysql.Ado.BeginTran(); + try + { + await _mysql.Deleteable() + .Where(it => it.UserId == model.UserId) + .ExecuteCommandAsync(); + if (categories.Count > 0) + { + var rows = categories.Select(it => new UserWorkhourScope + { + UserId = model.UserId, + Category = it + }).ToList(); + await _mysql.Insertable(rows).ExecuteCommandAsync(); + } + _mysql.Ado.CommitTran(); + return SKResponseResult.Get(SKResponseCode.OK, "保存成功", true); + } + catch (Exception ex) + { + _mysql.Ado.RollbackTran(); + _logger.LogError(ex, "保存人员工时填报权限失败,userId={UserId}", model.UserId); + return SKResponseResult.Get(SKResponseCode.Fail, "保存失败", false); + } + } + + private static Task> GetWorkhourScopeOptions() + { + return Task.FromResult(WorkhourScopeDefinitions.AllScopes.ToList()); + } + + private async Task AttachWorkhourCategories(List users) + { + if (users.Count == 0) + { + return; + } + var userIds = users.Select(it => it.UserId).ToList(); + var scopes = await _mysql.Queryable() + .Where(it => userIds.Contains(it.UserId)) + .ToListAsync(); + foreach (var item in users) + { + item.WorkhourCategories = scopes + .Where(it => it.UserId == item.UserId) + .Select(it => it.Category) + .Distinct() + .ToList(); + } + } + + private static bool CanManageAnyWorkhourScope(UserBasicInfo actor) + { + return actor.RoleId < 3 + || (actor.Account.Length > 2 && actor.Account.EndsWith("01", StringComparison.Ordinal)); + } + + private static bool CanManageWorkhourScope(UserBasicInfo actor, UserBasicInfo target) + { + if (actor.RoleId < 3) + { + return true; + } + if (actor.Account.Length <= 2 || !actor.Account.EndsWith("01", StringComparison.Ordinal)) + { + return false; + } + var accountPrefix = actor.Account[..^2]; + return target.Account.StartsWith(accountPrefix, StringComparison.OrdinalIgnoreCase); + } + /// /// 用户列表 /// diff --git a/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/WorkOrderController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/WorkOrderController.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/WorkOrderController.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/WorkOrderController.cs diff --git a/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/WorkhourController.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/WorkhourController.cs new file mode 100644 index 0000000..f745c0c --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Controllers/Web/WorkhourController.cs @@ -0,0 +1,1264 @@ +using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; +using NSwag.Annotations; +using SK_ERP_WebService.Filter; +using SK_ERP_WebService.Jdy.Util; +using SK_ERP_WebService.Model; +using SK_ERP_WebService.Service; +using SqlSugar; + +namespace SK_ERP_WebService.Controllers.Web +{ + /// + /// 工时填报、统计和工序字典接口。 + /// 工时记录及 ERP 工单产品快照使用工时专用表。 + /// + [Route("api/[controller]/[action]")] + [ApiController] + [ApiExplorerSettings(GroupName = "web")] + [OpenApiTag("Workhour", Description = "工时填报相关接口")] + [TokenFilter] + public class WorkhourController : ControllerBase + { + private static readonly string[] BusinessSegments = ["智慧用电", "智能家居", "安防报警"]; + private readonly ILogger _logger; + + private readonly MySqlDbContext _mysql; + + public WorkhourController( + ILogger logger, + MySqlDbContext mysql) + { + _logger = logger; + _mysql = mysql; + } + + #region 工单产品 / 工序进度(填报弹窗) + + /// + /// 输入工单号查询金蝶产品明细,并更新工时模块的工单产品快照。 + /// + /// 工单号 + /// + [HttpGet] + public async Task?>> OrderProductList( + [FromQuery] string? workOrderCode, + [FromServices] JdyService jdyService) + { + var assignedScopes = await GetCurrentWorkhourScopes(); + if (assignedScopes.Count == 0) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "当前账号未分配工时填报权限", null); + } + if (string.IsNullOrEmpty(workOrderCode)) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "工单号不能为空", null); + } + ErrorMessage? kingdeeResponse = null; + if (!jdyService.GetWorkhourOrderDetail(workOrderCode, ref kingdeeResponse)) + { + _logger.LogWarning("工时查询金蝶工单失败,工单:{WorkOrderCode},错误码:{ErrorCode},错误:{ErrorMessage}", + workOrderCode, kingdeeResponse?.ErrCode, kingdeeResponse?.ErrMsg); + return SKResponseResult.Get?>(SKResponseCode.Fail, "ERP 查询失败,请检查工单号或服务端连接,详情已记入服务日志", null); + } + if (kingdeeResponse?.Data is not SubmWorkorderRow kingdeeOrder) + { + _logger.LogWarning("工时查询金蝶返回数据格式不符合预期,工单:{WorkOrderCode},错误码:{ErrorCode},错误:{ErrorMessage}", + workOrderCode, kingdeeResponse?.ErrCode, kingdeeResponse?.ErrMsg); + return SKResponseResult.Get?>(SKResponseCode.Fail, "ERP 未返回可识别的工单详情,请查看服务日志", null); + } + + var materials = kingdeeOrder.Materials? + .Where(item => !string.IsNullOrWhiteSpace(item.DeviceCode) || !string.IsNullOrWhiteSpace(item.Number)) + .GroupBy(item => !string.IsNullOrWhiteSpace(item.DeviceCode) ? item.DeviceCode! : item.Number!) + .Select(group => new LiveWorkOrderMaterial( + group.Key, + group.First().Number, + group.First().Name, + group.First().Mode, + group.Sum(item => item.Qty), + group.Sum(item => item.InQty))) + .ToList() ?? new List(); + + if (materials.Count == 0) + { + _logger.LogWarning("工时查询到金蝶工单详情,但明细没有可填报商品行。工单:{WorkOrderCode},ERP单号:{ErpBillNo},明细数:{MaterialCount}", + workOrderCode, kingdeeOrder.BillNo, kingdeeOrder.Materials?.Count ?? 0); + return SKResponseResult.Get?>(SKResponseCode.Fail, "金蝶工单下没有可填报的机型", null); + } + + var actualWorkOrderCode = string.IsNullOrWhiteSpace(kingdeeOrder.BillNo) ? workOrderCode! : kingdeeOrder.BillNo; + var rows = new List(); + foreach (var material in materials) + { + string devCode = material.DevCode; + string? productNumber = material.ProductNumber; + string? productName = material.ProductName; + string? productMode = material.ProductMode; + int manuNum = material.ManuNum; + int inboundNum = material.InboundNum; + + var existing = await _mysql.Queryable() + .Where(it => it.WorkOrderCode == actualWorkOrderCode && it.DevCode == devCode) + .FirstAsync(); + if (existing == null) + { + await _mysql.Insertable(new WorkhourOrderProduct + { + WorkOrderCode = actualWorkOrderCode, + DevCode = devCode, + ProductNumber = productNumber, + ProductName = productName, + ProductMode = productMode, + ManuNum = manuNum, + InboundNum = inboundNum, + LastFetchedAt = DateTime.Now, + }).ExecuteCommandAsync(); + } + else + { + await _mysql.Updateable() + .SetColumns(it => new WorkhourOrderProduct + { + ProductNumber = productNumber, + ProductName = productName, + ProductMode = productMode, + ManuNum = manuNum, + InboundNum = inboundNum, + LastFetchedAt = DateTime.Now, + }) + .Where(it => it.WorkOrderCode == actualWorkOrderCode && it.DevCode == devCode) + .ExecuteCommandAsync(); + } + + rows.Add(new WorkhourProductModel + { + WorkOrderCode = actualWorkOrderCode, + DevCode = devCode, + ProdNo = productNumber, + ProductName = productName, + ProductMode = productMode, + ManuNum = manuNum, + InboundNum = inboundNum, + InboundDiff = manuNum - inboundNum, + }); + } + return SKResponseResult.Get(SKResponseCode.OK, SKResponseJsonMsg.GET_SUCCESS, rows); + } + + /// + /// 工序填报进度(仅正常工时;按工单+型号+大类+板件/组别+工序跨月份累计) + /// + /// 工单号 + /// 机型代码 + /// 大类 + /// 组别 + /// 工序 + /// 本次拟填数量,用于超量软提示;不传则不提示 + /// 工时类型;非正常工时不返回计划进度 + /// + [HttpGet] + public async Task> ProcessProgress( + [FromQuery] string? workOrderCode, + [FromQuery] string? devCode, + [FromQuery] string? category, + [FromQuery] string? groupName, + [FromQuery] string? processName, + [FromQuery] int qty = 0, + [FromQuery] string? dictType = "正常工时") + { + if (dictType != "正常工时" && dictType != "非正常工时") + { + return SKResponseResult.Get(SKResponseCode.Fail, "工时类型无效", null); + } + // 非正常工时没有生产计划进度,不返回 manu_num 进度口径 + if (dictType == "非正常工时") + { + if (!await HasAbnormalGroupScope(groupName) || string.IsNullOrEmpty(processName)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "当前账号没有该组别的非正常工时权限", null); + } + return SKResponseResult.Get(SKResponseCode.OK, SKResponseJsonMsg.GET_SUCCESS, null); + } + var allowedCategories = await GetCurrentWorkhourCategories(); + if (allowedCategories.Count == 0 || string.IsNullOrEmpty(category) || !allowedCategories.Contains(category) + || string.IsNullOrWhiteSpace(groupName) + || string.IsNullOrEmpty(processName)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "当前账号没有该流程的填报权限", null); + } + var result = await BuildProgress(workOrderCode, devCode, category, groupName, processName, qty); + if (result == null) + { + return SKResponseResult.Get(SKResponseCode.Fail, "无效的工单号或机型代码", null); + } + return SKResponseResult.Get(SKResponseCode.OK, SKResponseJsonMsg.GET_SUCCESS, result); + } + + /// + /// 工序下拉(按大类和组别取字典) + /// + /// 大类 + /// 组别 + /// 字典类型 + /// + [HttpGet] + public async Task?>> ProcessList( + [FromQuery] string? category, + [FromQuery] string? dictType, + [FromQuery] string? groupName) + { + if (dictType == "非正常工时") + { + var scopes = await GetCurrentWorkhourScopes(); + if (!scopes.Any(WorkhourScopeDefinitions.IsAbnormalScope)) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "当前账号未分配非正常工时权限", null); + } + category = "全部组别"; + groupName = "全部组别"; + } + else + { + var allowedCategories = await GetCurrentWorkhourCategories(); + if (allowedCategories.Count == 0) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "当前账号未分配正常工时权限", null); + } + if (string.IsNullOrEmpty(category) || !allowedCategories.Contains(category)) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "当前账号没有该流程的填报权限", null); + } + } + + var list = await _mysql.Queryable() + .Where(it => it.IsValid && it.DictType == dictType && it.Category == category) + .WhereIF(!string.IsNullOrEmpty(groupName), it => it.GroupName == groupName) + .OrderBy(it => it.GroupName) + .OrderBy(it => it.Sort) + .OrderBy(it => it.ProcessName) + .ToListAsync(); + return SKResponseResult.Get(SKResponseCode.OK, SKResponseJsonMsg.GET_SUCCESS, list); + } + + #endregion + + #region 工时记录 + + /// + /// 工时记录分页列表 + /// + /// 分页索引 从1开始 + /// 分页大小 + /// 工单号 + /// 生产月份 + /// 机型代码 + /// + [HttpGet] + public async Task?>> FillPageList( + [FromQuery] int index, + [FromQuery] int size, + [FromQuery] string? workOrderCode, + [FromQuery] string? mfgMonth, + [FromQuery] string? devCode) + { + var assignedScopes = await GetCurrentWorkhourScopes(); + var allowedCategories = WorkhourScopeDefinitions.ExpandFillCategories(assignedScopes); + var allowedAbnormalGroups = WorkhourScopeDefinitions.GetAuthorizedAbnormalGroups(assignedScopes); + if (allowedCategories.Count == 0 && allowedAbnormalGroups.Count == 0) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "当前账号未分配工时填报权限", null); + } + RefAsync total = 0; + var list = await _mysql.Queryable() + .Where(it => (it.DictType == "正常工时" && allowedCategories.Contains(it.Category)) + || (it.DictType == "非正常工时" && allowedAbnormalGroups.Contains(it.GroupName))) + .WhereIF(!string.IsNullOrEmpty(workOrderCode), it => it.WorkOrderCode.Contains(workOrderCode)) + .WhereIF(!string.IsNullOrEmpty(mfgMonth), it => it.MfgMonth == mfgMonth) + .WhereIF(!string.IsNullOrEmpty(devCode), it => it.DevCode == devCode) + .Includes(it => it.DevType) + .Includes(it => it.User) + .OrderBy(it => it.CreateTime, OrderByType.Desc) + .ToPageListAsync(index, size, total); + + var workOrderCodes = list.Select(it => it.WorkOrderCode).Where(it => !string.IsNullOrWhiteSpace(it)).Distinct().ToList(); + var devCodes = list.Select(it => it.DevCode).Where(it => !string.IsNullOrWhiteSpace(it)).Distinct().ToList(); + if (workOrderCodes.Count > 0 && devCodes.Count > 0) + { + var products = await _mysql.Queryable() + .Where(it => workOrderCodes.Contains(it.WorkOrderCode) && devCodes.Contains(it.DevCode)) + .ToListAsync(); + var productLookup = products.ToDictionary( + it => BuildWorkOrderProductKey(it.WorkOrderCode, it.DevCode), + StringComparer.OrdinalIgnoreCase); + foreach (var record in list) + { + productLookup.TryGetValue(BuildWorkOrderProductKey(record.WorkOrderCode, record.DevCode), out var product); + var productName = product?.ProductName; + if (string.IsNullOrWhiteSpace(record.ProductName)) + { + record.ProductName = !string.IsNullOrWhiteSpace(productName) + ? productName + : record.DevType?.DevTypeName; + } + record.ProductMode = product?.ProductMode; + } + } + else + { + foreach (var record in list) + { + if (string.IsNullOrWhiteSpace(record.ProductName)) + { + record.ProductName = record.DevType?.DevTypeName; + } + } + } + return SKResponseResult.Get(SKResponseCode.OK, SKResponseJsonMsg.GET_SUCCESS, new SKPageModel + { + Index = index, + Size = size, + Total = total.Value, + Data = list, + }); + } + + /// + /// 保存工时记录;重复填报和超计划量只提示,不拦截。 + /// + /// 创建模型 + /// 返回最新进度,Warnings 为提示信息 + [HttpPost] + public async Task> FillCreate( + [FromBody] WorkhourRecordCreateModel model) + { + _logger.LogInformation("工时填报:{model}", JsonConvert.SerializeObject(model)); + if (HttpContext.Items["user"] is not UserBasicInfo user) + { + return SKResponseResult.Get(SKResponseCode.Fail, "用户信息错误", null); + } + var dictType = string.IsNullOrEmpty(model.DictType) ? "正常工时" : model.DictType; + if (dictType != "正常工时" && dictType != "非正常工时") + { + return SKResponseResult.Get(SKResponseCode.Fail, "工时类型无效", null); + } + var assignedScopes = await GetCurrentWorkhourScopes(); + var allowedCategories = WorkhourScopeDefinitions.ExpandFillCategories(assignedScopes); + var allowedAbnormalGroups = WorkhourScopeDefinitions.GetAuthorizedAbnormalGroups(assignedScopes); + if ((dictType == "正常工时" && allowedCategories.Count == 0) + || (dictType == "非正常工时" && allowedAbnormalGroups.Count == 0)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "当前账号未分配该类型的工时填报权限", null); + } + + var isDirectNormalCategory = dictType == "正常工时" + && WorkhourScopeDefinitions.IsDirectNormalCategory(model.Category); + var category = dictType == "非正常工时" + ? WorkhourScopeDefinitions.GetAbnormalCategoryForGroup(model.GroupName) + : model.Category; + var groupName = model.GroupName; + var processName = model.ProcessName; + // 正常工时必须关联工单;非正常工时可不填工单,关联时必须选择产品。 + var hasWorkOrder = !string.IsNullOrWhiteSpace(model.WorkOrderCode); + var workOrderCode = hasWorkOrder ? model.WorkOrderCode!.Trim() : null; + var devCode = hasWorkOrder && !string.IsNullOrWhiteSpace(model.DevCode) ? model.DevCode!.Trim() : null; + if ((dictType == "正常工时" && (!hasWorkOrder || string.IsNullOrWhiteSpace(devCode))) + || (dictType == "非正常工时" && hasWorkOrder && string.IsNullOrWhiteSpace(devCode)) + || string.IsNullOrWhiteSpace(model.MfgMonth) || string.IsNullOrEmpty(category) + || (!isDirectNormalCategory && string.IsNullOrEmpty(model.ProcessName)) + || string.IsNullOrEmpty(model.BusinessSegment)) + { + return SKResponseResult.Get(SKResponseCode.Fail, + dictType == "正常工时" + ? "正常工时必须选择工单和产品;月份/板块/组别/工序不能为空" + : "关联工单时必须选择产品;月份/板块/组别/工序不能为空", null); + } + if (!BusinessSegments.Contains(model.BusinessSegment)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "公司板块无效", null); + } + if (model.Qty <= 0) + { + return SKResponseResult.Get(SKResponseCode.Fail, "填报数量必须大于0", null); + } + if (model.Minutes <= 0) + { + return SKResponseResult.Get(SKResponseCode.Fail, "工时必须大于0", null); + } + + if (dictType == "正常工时" && !allowedCategories.Contains(category!)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "当前账号没有该流程的填报权限", null); + } + if (isDirectNormalCategory) + { + // 这三类没有可选小工序,按原模板固定在“整机”组,工序字段用大类名映射。 + groupName = "整机"; + processName = category; + } + else if (string.IsNullOrWhiteSpace(groupName)) + { + return SKResponseResult.Get(SKResponseCode.Fail, + dictType == "正常工时" && category == WorkhourScopeDefinitions.Debug ? "请选择调试板件" : "请选择组别", null); + } + if (dictType == "非正常工时") + { + if (!allowedAbnormalGroups.Contains(groupName, StringComparer.Ordinal) + || !WorkhourScopeDefinitions.IsValidAbnormalGroup(category, groupName)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "当前账号没有该组别的非正常工时填报权限", null); + } + } + var dictionaryCategory = dictType == "非正常工时" ? "全部组别" : category; + var dictionaryGroup = dictType == "非正常工时" ? "全部组别" : groupName; + var validProcessCount = await _mysql.Queryable() + .Where(it => it.IsValid && it.DictType == dictType && it.ProcessName == processName + && it.Category == dictionaryCategory && it.GroupName == dictionaryGroup) + .CountAsync(); + if (!isDirectNormalCategory && validProcessCount == 0) + { + return SKResponseResult.Get(SKResponseCode.Fail, "所选工序不属于当前类型和组别", null); + } + // 非正常工时必须说明原因(正常工时无此约束) + if (dictType == "非正常工时" && string.IsNullOrWhiteSpace(model.Remark)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "非正常工时必须填写备注原因", null); + } + + WorkhourOrderProduct? orderProduct = null; + WorkOrderInfo? legacyOrder = null; + if (hasWorkOrder) + { + orderProduct = await _mysql.Queryable() + .Where(it => it.WorkOrderCode == workOrderCode && it.DevCode == devCode) + .FirstAsync(); + legacyOrder = orderProduct == null + ? await _mysql.Queryable() + .Where(it => it.WorkOrderCode == workOrderCode && it.DevCode == devCode) + .FirstAsync() + : null; + if (orderProduct == null && legacyOrder == null) + { + return SKResponseResult.Get(SKResponseCode.Fail, "请先输入工单号查询 ERP,并选择该工单下的产品", null); + } + } + var productName = !string.IsNullOrWhiteSpace(model.ProductName) + ? model.ProductName.Trim() + : orderProduct?.ProductName; + + // 只有正常生产工时才按计划数量计算进度和超量软提示 + WorkhourProgressModel? before = null; + if (dictType == "正常工时") + { + before = await BuildProgress(workOrderCode, devCode, + category, groupName, processName, model.Qty); + } + + var userId = user.UserId; + + WorkhourRecord insert = new() + { + WorkOrderCode = workOrderCode, + DevCode = devCode, + ProductName = productName, + MfgMonth = model.MfgMonth, + BusinessSegment = model.BusinessSegment, + Category = category, + GroupName = groupName, + ProcessName = processName, + DictType = dictType, + Qty = model.Qty, + Minutes = model.Minutes, + UserId = userId, + WorkDate = model.WorkDate, + Remark = model.Remark, + CreateTime = DateTime.Now, + }; + var ok = await _mysql.Insertable(insert).ExecuteCommandAsync() > 0; + if (!ok) + { + return SKResponseResult.Get(SKResponseCode.Fail, "填报失败", null); + } + + // 正常工时落库后重算进度;非正常工时不使用计划量进度 + WorkhourProgressModel? after = null; + if (dictType == "正常工时") + { + after = await BuildProgress(workOrderCode, devCode, + category, groupName, processName, 0); + if (after != null && before != null) + { + after.Warnings = before.Warnings; + } + } + return SKResponseResult.Get(SKResponseCode.OK, "填报成功", after); + } + + /// + /// 工时记录更新 + /// + /// 更新模型 + /// + [HttpPost] + public async Task> FillUpdate( + [FromBody] WorkhourRecordUpdateModel model) + { + _logger.LogInformation("更新工时记录:{model}", JsonConvert.SerializeObject(model)); + if (HttpContext.Items["user"] is not UserBasicInfo user) + { + return SKResponseResult.Get(SKResponseCode.Fail, "用户信息错误", false); + } + var assignedScopes = await GetCurrentWorkhourScopes(); + var allowedCategories = WorkhourScopeDefinitions.ExpandFillCategories(assignedScopes); + var allowedAbnormalGroups = WorkhourScopeDefinitions.GetAuthorizedAbnormalGroups(assignedScopes); + if (allowedCategories.Count == 0 && allowedAbnormalGroups.Count == 0) + { + return SKResponseResult.Get(SKResponseCode.Fail, "当前账号未分配工时填报权限", false); + } + if (model.Qty <= 0 || model.Minutes <= 0) + { + return SKResponseResult.Get(SKResponseCode.Fail, "填报数量和工时都必须大于0", false); + } + var existing = await _mysql.Queryable() + .Where(it => it.RecordId == model.RecordId) + .FirstAsync(); + if (existing == null) + { + return SKResponseResult.Get(SKResponseCode.Fail, "工时记录不存在", false); + } + var canEdit = existing.DictType == "非正常工时" + ? allowedAbnormalGroups.Contains(existing.GroupName ?? string.Empty, StringComparer.Ordinal) + : allowedCategories.Contains(existing.Category ?? string.Empty); + if (!canEdit) + { + return SKResponseResult.Get(SKResponseCode.Fail, "当前账号没有该流程的填报权限", false); + } + if (existing.DictType == "非正常工时" && string.IsNullOrWhiteSpace(model.Remark)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "非正常工时必须填写备注原因", false); + } + var productName = existing.DictType == "非正常工时" && string.IsNullOrWhiteSpace(existing.WorkOrderCode) + ? (string.IsNullOrWhiteSpace(model.ProductName) ? null : model.ProductName.Trim()) + : existing.ProductName; + var result = await _mysql.Updateable() + .SetColumns(it => new WorkhourRecord + { + ProductName = productName, + Qty = model.Qty, + Minutes = model.Minutes, + WorkDate = model.WorkDate, + Remark = model.Remark, + }) + .UpdateColumns(it => new { it.ProductName, it.Qty, it.Minutes, it.WorkDate, it.Remark }) + .Where(it => it.RecordId == model.RecordId) + .ExecuteCommandAsync() > 0; + if (result) + { + return SKResponseResult.Get(SKResponseCode.OK, "更新成功", true); + } + return SKResponseResult.Get(SKResponseCode.Fail, "更新失败", false); + } + + /// + /// 根据代码定义的工时字段和工序结构导出统计工作簿。 + /// + [HttpGet] + public async Task ExportTemplate( + [FromServices] IWebHostEnvironment environment, + [FromQuery] int year, + [FromQuery] int[]? months, + [FromQuery] string[]? businessSegments, + [FromQuery] string? dictType) + { + if (dictType is not ("正常工时" or "非正常工时")) + { + return BadRequest("工时类型无效"); + } + var assignedScopes = await GetCurrentWorkhourScopes(); + var allowedCategories = WorkhourScopeDefinitions.ExpandFillCategories(assignedScopes); + var allowedAbnormalGroups = WorkhourScopeDefinitions.GetAuthorizedAbnormalGroups(assignedScopes); + if ((dictType == "正常工时" && allowedCategories.Count == 0) + || (dictType == "非正常工时" && allowedAbnormalGroups.Count == 0)) + { + return StatusCode(StatusCodes.Status403Forbidden, "当前账号未分配该类型的工时填报权限"); + } + var monthLimit = WorkhourTemplateExportService.AvailableMonthCount(year); + var selectedMonths = months?.Distinct().OrderBy(month => month).ToArray() ?? Array.Empty(); + if (monthLimit == 0 || selectedMonths.Length == 0 || selectedMonths.Any(month => month < 1 || month > monthLimit)) + { + return BadRequest($"年份无效或月份选择不完整;请从 1 至 12 月中至少选择一个月份"); + } + var selectedSegments = businessSegments? + .Where(segment => !string.IsNullOrWhiteSpace(segment)) + .Distinct(StringComparer.Ordinal) + .ToArray() ?? Array.Empty(); + if (selectedSegments.Length == 0 || selectedSegments.Any(segment => !BusinessSegments.Contains(segment))) + { + return BadRequest("请至少选择一个有效板块:智慧用电、智能家居、安防报警"); + } + + var rows = await _mysql.Queryable() + .Where(it => it.DictType == dictType) + .WhereIF(dictType == "正常工时", it => allowedCategories.Contains(it.Category)) + .WhereIF(dictType == "非正常工时", it => allowedAbnormalGroups.Contains(it.GroupName)) + .Where(it => it.MfgMonth.StartsWith(year.ToString())) + .Where(it => it.BusinessSegment != null && selectedSegments.Contains(it.BusinessSegment)) + .ToListAsync(); + var devCodes = rows.Select(row => row.DevCode).Where(code => !string.IsNullOrWhiteSpace(code)).Distinct().ToList(); + var workOrderCodes = rows.Select(row => row.WorkOrderCode).Where(code => !string.IsNullOrWhiteSpace(code)).Distinct().ToList(); + var productSnapshots = devCodes.Count == 0 || workOrderCodes.Count == 0 + ? new List() + : await _mysql.Queryable() + .Where(it => workOrderCodes.Contains(it.WorkOrderCode) && devCodes.Contains(it.DevCode)) + .ToListAsync(); + var snapshotNames = productSnapshots.ToDictionary( + it => BuildWorkOrderProductKey(it.WorkOrderCode, it.DevCode), + it => it.ProductName, + StringComparer.OrdinalIgnoreCase); + var productRows = devCodes.Count == 0 + ? new List() + : await _mysql.Queryable().Where(it => devCodes.Contains(it.DevCode)).ToListAsync(); + var productNames = productRows.ToDictionary(row => row.DevCode ?? string.Empty, row => row.DevTypeName ?? string.Empty, StringComparer.OrdinalIgnoreCase); + var exportRecords = rows.Select(row => + { + var productName = !string.IsNullOrWhiteSpace(row.ProductName) + ? row.ProductName + : snapshotNames.GetValueOrDefault(BuildWorkOrderProductKey(row.WorkOrderCode, row.DevCode)); + if (string.IsNullOrWhiteSpace(productName)) + { + productName = productNames.GetValueOrDefault(row.DevCode ?? string.Empty, row.DevCode ?? string.Empty); + } + return new WorkhourTemplateExportService.WorkhourTemplateRecord( + row.BusinessSegment, + row.DictType, + row.Category, + row.GroupName, + row.ProcessName, + productName, + row.MfgMonth, + row.Remark, + row.Qty, + row.Minutes); + }).ToList(); + + try + { + var exporter = new WorkhourTemplateExportService(); + var bytes = dictType == "正常工时" + ? exporter.ExportNormal(selectedMonths, selectedSegments, exportRecords) + : exporter.ExportAbnormal(selectedMonths, selectedSegments, exportRecords); + var typeLabel = dictType == "正常工时" ? "工时统计" : "非正常工时统计"; + return File(bytes, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + BuildExportFileName(year, selectedMonths, selectedSegments, typeLabel)); + } + catch (Exception ex) + { + _logger.LogError(ex, "工时报表生成失败,年份:{Year} 类型:{Type}", year, dictType); + return StatusCode(StatusCodes.Status500InternalServerError, "工时统计表生成失败,请查看服务日志"); + } + } + + /// + /// 根据请求中的演示记录导出工作簿,不写入业务数据库。 + /// + [HttpPost] + public IActionResult ExportTemplatePreview( + [FromServices] IWebHostEnvironment environment, + [FromBody] WorkhourTemplatePreviewRequest model) + { + if (!environment.IsDevelopment()) + { + return NotFound(); + } + if (HttpContext.Items["user"] is not UserBasicInfo) + { + return Unauthorized(); + } + if (model.DictType is not ("正常工时" or "非正常工时")) + { + return BadRequest("工时类型无效"); + } + + var monthLimit = WorkhourTemplateExportService.AvailableMonthCount(model.Year); + var selectedMonths = model.Months?.Distinct().OrderBy(month => month).ToArray() ?? Array.Empty(); + if (monthLimit == 0 || selectedMonths.Length == 0 || selectedMonths.Any(month => month < 1 || month > monthLimit)) + { + return BadRequest("年份无效或月份选择不完整;请从 1 至 12 月中至少选择一个月份"); + } + + var selectedSegments = model.BusinessSegments? + .Where(segment => !string.IsNullOrWhiteSpace(segment)) + .Distinct(StringComparer.Ordinal) + .ToArray() ?? Array.Empty(); + if (selectedSegments.Length == 0 || selectedSegments.Any(segment => !BusinessSegments.Contains(segment))) + { + return BadRequest("请至少选择一个有效板块:智慧用电、智能家居、安防报警"); + } + + var selectedMonthSet = selectedMonths.ToHashSet(); + var records = (model.Records ?? new List()) + .Where(record => record.DictType == model.DictType + && !string.IsNullOrWhiteSpace(record.BusinessSegment) + && selectedSegments.Contains(record.BusinessSegment, StringComparer.Ordinal)) + .Where(record => + { + var parts = record.MfgMonth?.Split('-'); + return parts?.Length == 2 + && int.TryParse(parts[0], out var year) + && year == model.Year + && int.TryParse(parts[1], out var month) + && selectedMonthSet.Contains(month); + }) + .ToList(); + + try + { + var exporter = new WorkhourTemplateExportService(); + var bytes = model.DictType == "正常工时" + ? exporter.ExportNormal(selectedMonths, selectedSegments, records) + : exporter.ExportAbnormal(selectedMonths, selectedSegments, records); + var typeLabel = model.DictType == "正常工时" ? "工时统计" : "非正常工时统计"; + return File(bytes, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + BuildExportFileName(model.Year, selectedMonths, selectedSegments, $"演示样例_{typeLabel}")); + } + catch (Exception exception) + { + _logger.LogError(exception, "工时演示表生成失败"); + return StatusCode(StatusCodes.Status500InternalServerError, "工时演示表生成失败,请查看服务日志"); + } + } + + #endregion + + private static string BuildExportFileName(int year, IReadOnlyCollection months, IReadOnlyCollection segments, string typeLabel) + { + var orderedMonths = months.Distinct().OrderBy(month => month).ToArray(); + var periodLabel = orderedMonths.Length == 1 + ? $"{year}年{orderedMonths[0]}月" + : IsContinuousMonths(orderedMonths) + ? $"{year}年{orderedMonths[0]}月到{year}年{orderedMonths[^1]}月" + : string.Join("、", orderedMonths.Select(month => $"{year}年{month}月")); + var segmentLabel = segments.Count == 1 ? segments.Single() + "板块" : "多板块"; + return $"{segmentLabel}_{periodLabel}_{typeLabel}.xlsx"; + } + + private static bool IsContinuousMonths(IReadOnlyList months) + { + for (var index = 1; index < months.Count; index++) + { + if (months[index] != months[index - 1] + 1) return false; + } + return months.Count > 1; + } + + #region 工时统计 + + /// + /// 按工单统计 + /// + /// 工单号,可空 + /// 年份,可空 + /// 大类,可空 + /// 工时类型,可空 + /// + [HttpGet] + public async Task?>> StatOrder( + [FromQuery] string? workOrderCode, + [FromQuery] string? year, + [FromQuery] string? category, + [FromQuery] string? dictType) + { + var assignedScopes = await GetCurrentWorkhourScopes(); + var allowedCategories = WorkhourScopeDefinitions.ExpandFillCategories(assignedScopes); + var allowedAbnormalGroups = WorkhourScopeDefinitions.GetAuthorizedAbnormalGroups(assignedScopes); + if (allowedCategories.Count == 0 && allowedAbnormalGroups.Count == 0) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "当前账号未分配工时填报权限", null); + } + if (!string.IsNullOrEmpty(category) && !allowedCategories.Contains(category)) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "当前账号没有该流程的查看权限", null); + } + var legacyProducts = await _mysql.Queryable() + .WhereIF(!string.IsNullOrEmpty(workOrderCode), it => it.WorkOrderCode == workOrderCode) + .Select(it => new WorkhourProductModel + { + WorkOrderCode = it.WorkOrderCode, + DevCode = it.DevCode, + ManuNum = it.ManuNum, + InboundNum = SqlFunc.Subqueryable() + .Where(s => s.WorkOrderCode == it.WorkOrderCode + && s.DevCode == it.DevCode + && (s.DevState == "2" || s.DevState == "3")).Count() + }) + .ToListAsync(); + var workOrderProducts = await _mysql.Queryable() + .WhereIF(!string.IsNullOrEmpty(workOrderCode), it => it.WorkOrderCode == workOrderCode) + .Select(it => new WorkhourProductModel + { + WorkOrderCode = it.WorkOrderCode, + DevCode = it.DevCode, + ManuNum = it.ManuNum, + InboundNum = it.InboundNum, + }) + .ToListAsync(); + var productLookup = legacyProducts + .GroupBy(it => BuildWorkOrderProductKey(it.WorkOrderCode, it.DevCode), StringComparer.OrdinalIgnoreCase) + .ToDictionary(group => group.Key, group => group.First(), StringComparer.OrdinalIgnoreCase); + foreach (var product in workOrderProducts) + { + productLookup[BuildWorkOrderProductKey(product.WorkOrderCode, product.DevCode)] = product; + } + var rows = productLookup.Values.ToList(); + + var hours = await _mysql.Queryable() + .Where(it => (it.DictType == "正常工时" && allowedCategories.Contains(it.Category)) + || (it.DictType == "非正常工时" && allowedAbnormalGroups.Contains(it.GroupName))) + .WhereIF(!string.IsNullOrEmpty(workOrderCode), it => it.WorkOrderCode == workOrderCode) + .WhereIF(!string.IsNullOrEmpty(year), it => it.MfgMonth.StartsWith(year)) + .WhereIF(!string.IsNullOrEmpty(category), it => it.Category == category) + .WhereIF(!string.IsNullOrEmpty(dictType), it => it.DictType == dictType) + .GroupBy(it => it.WorkOrderCode) + .Select(it => new + { + WorkOrderCode = it.WorkOrderCode, + Minutes = SqlFunc.AggregateSum(it.Minutes) + }) + .ToListAsync(); + + var matchedWorkOrders = hours.Select(it => it.WorkOrderCode).ToHashSet(); + rows = rows.Where(it => matchedWorkOrders.Contains(it.WorkOrderCode)).ToList(); + + var list = rows + .GroupBy(it => it.WorkOrderCode) + .Select(g => + { + var minute = hours.FirstOrDefault(h => h.WorkOrderCode == g.Key)?.Minutes ?? 0; + return new WorkhourStatOrderModel + { + WorkOrderCode = g.Key, + DevCount = g.Count(), + ManuNum = g.Sum(x => x.ManuNum), + InboundNum = g.Sum(x => x.InboundNum), + InboundDiff = g.Sum(x => x.ManuNum) - g.Sum(x => x.InboundNum), + Minutes = minute, + Hours = Math.Round(minute / 60m, 2), + }; + }) + .OrderByDescending(it => it.ManuNum) + .ToList(); + + return SKResponseResult.Get(SKResponseCode.OK, SKResponseJsonMsg.GET_SUCCESS, list); + } + + /// + /// 按工序统计 + /// + /// 年份,可空 + /// 大类,可空 + /// 工时类型,可空 + /// + [HttpGet] + public async Task?>> StatProcess( + [FromQuery] string? year, + [FromQuery] string? category, + [FromQuery] string? dictType) + { + var assignedScopes = await GetCurrentWorkhourScopes(); + var allowedCategories = WorkhourScopeDefinitions.ExpandFillCategories(assignedScopes); + var allowedAbnormalGroups = WorkhourScopeDefinitions.GetAuthorizedAbnormalGroups(assignedScopes); + if (allowedCategories.Count == 0 && allowedAbnormalGroups.Count == 0) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "当前账号未分配工时填报权限", null); + } + if (!string.IsNullOrEmpty(category) && !allowedCategories.Contains(category)) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "当前账号没有该流程的查看权限", null); + } + var rows = await _mysql.Queryable() + .Where(it => (it.DictType == "正常工时" && allowedCategories.Contains(it.Category)) + || (it.DictType == "非正常工时" && allowedAbnormalGroups.Contains(it.GroupName))) + .WhereIF(!string.IsNullOrEmpty(year), it => it.MfgMonth.StartsWith(year)) + .WhereIF(!string.IsNullOrEmpty(category), it => it.Category == category) + .WhereIF(!string.IsNullOrEmpty(dictType), it => it.DictType == dictType) + .GroupBy(it => new { it.DictType, it.Category, it.GroupName, it.ProcessName }) + .Select(it => new + { + it.DictType, + it.Category, + it.GroupName, + it.ProcessName, + Qty = SqlFunc.AggregateSum(it.Qty), + Minutes = SqlFunc.AggregateSum(it.Minutes) + }) + .ToListAsync(); + + var list = rows.Select(it => new WorkhourStatProcessModel + { + DictType = it.DictType, + Category = it.Category, + GroupName = it.GroupName, + ProcessName = it.ProcessName, + Qty = it.Qty, + Minutes = it.Minutes, + Hours = Math.Round(it.Minutes / 60m, 2), + }).ToList(); + + return SKResponseResult.Get(SKResponseCode.OK, SKResponseJsonMsg.GET_SUCCESS, list); + } + + /// + /// 按月份统计 + /// + /// 年份;可空则查询全部 + /// 大类,可空 + /// 工时类型,可空 + /// + [HttpGet] + public async Task?>> StatMonth( + [FromQuery] string? year, + [FromQuery] string? category, + [FromQuery] string? dictType) + { + var assignedScopes = await GetCurrentWorkhourScopes(); + var allowedCategories = WorkhourScopeDefinitions.ExpandFillCategories(assignedScopes); + var allowedAbnormalGroups = WorkhourScopeDefinitions.GetAuthorizedAbnormalGroups(assignedScopes); + if (allowedCategories.Count == 0 && allowedAbnormalGroups.Count == 0) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "当前账号未分配工时填报权限", null); + } + if (!string.IsNullOrEmpty(category) && !allowedCategories.Contains(category)) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "当前账号没有该流程的查看权限", null); + } + var rows = await _mysql.Queryable() + .Where(it => (it.DictType == "正常工时" && allowedCategories.Contains(it.Category)) + || (it.DictType == "非正常工时" && allowedAbnormalGroups.Contains(it.GroupName))) + .WhereIF(!string.IsNullOrEmpty(year), it => it.MfgMonth.StartsWith(year)) + .WhereIF(!string.IsNullOrEmpty(category), it => it.Category == category) + .WhereIF(!string.IsNullOrEmpty(dictType), it => it.DictType == dictType) + .GroupBy(it => new { it.DictType, it.MfgMonth }) + .Select(it => new + { + it.DictType, + it.MfgMonth, + Qty = SqlFunc.AggregateSum(it.Qty), + Minutes = SqlFunc.AggregateSum(it.Minutes) + }) + .OrderBy(it => it.MfgMonth) + .ToListAsync(); + + var list = rows.Select(it => new WorkhourStatMonthModel + { + DictType = it.DictType, + MfgMonth = it.MfgMonth, + Qty = it.Qty, + Minutes = it.Minutes, + Hours = Math.Round(it.Minutes / 60m, 2), + }).ToList(); + + return SKResponseResult.Get(SKResponseCode.OK, SKResponseJsonMsg.GET_SUCCESS, list); + } + + #endregion + + #region 工序字典 dict_process表接口(沿用既有字典约定:无删除) + + /// + /// 获取工序字典列表 + /// + /// + [HttpGet] + public async Task?>> DictProcessList() + { + if (!CanManageProcessDictionary()) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "无权限", null); + } + var list = await _mysql.Queryable() + .OrderBy(it => it.DictType) + .OrderBy(it => it.Category) + .OrderBy(it => it.GroupName) + .OrderBy(it => it.Sort) + .ToListAsync(); + return SKResponseResult.Get(SKResponseCode.OK, SKResponseJsonMsg.GET_SUCCESS, list); + } + + /// + /// 获取工序字典分页列表 + /// + /// 分页索引 从1开始 + /// 分页大小 + /// 搜索条件 + /// + [HttpGet] + public async Task?>> DictProcessPageList( + [FromQuery] int index, + [FromQuery] int size, + [FromQuery] string? conditions) + { + if (!CanManageProcessDictionary()) + { + return SKResponseResult.Get?>(SKResponseCode.Fail, "无权限", null); + } + RefAsync total = 0; + var list = await _mysql.Queryable() + .WhereIF(!string.IsNullOrEmpty(conditions), it => it.ProcessName.Contains(conditions)) + .ToPageListAsync(index, size, total); + return SKResponseResult.Get(SKResponseCode.OK, SKResponseJsonMsg.GET_SUCCESS, new SKPageModel + { + Index = index, + Size = size, + Total = total.Value, + Data = list, + }); + } + + /// + /// 工序字典创建 + /// + /// 创建模型 + /// + [HttpPost] + public async Task> DictProcessCreate( + [FromBody] DictProcessCreateModel model) + { + if (!CanManageProcessDictionary()) + { + return SKResponseResult.Get(SKResponseCode.Fail, "无权限", false); + } + _logger.LogInformation("创建工序:{model}", JsonConvert.SerializeObject(model)); + if (string.IsNullOrWhiteSpace(model.ProcessName)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "工序名称不能为空", false); + } + var dictType = string.IsNullOrEmpty(model.DictType) ? "正常工时" : model.DictType; + if (dictType != "正常工时" && dictType != "非正常工时") + { + return SKResponseResult.Get(SKResponseCode.Fail, "工时类型无效", false); + } + var category = dictType == "非正常工时" ? "全部组别" : model.Category; + var groupName = dictType == "非正常工时" ? "全部组别" : model.GroupName; + if (dictType == "正常工时" && !WorkhourScopeDefinitions.IsProcessDictionaryCategory(category)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "正常工时工序字典大类只能是基板或调试", false); + } + if (string.IsNullOrWhiteSpace(category) + || string.IsNullOrWhiteSpace(groupName)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "大类和组别(调试板件)不能为空", false); + } + var exists = await _mysql.Queryable() + .Where(it => it.DictType == dictType + && it.Category == category + && it.GroupName == groupName + && it.ProcessName == model.ProcessName) + .AnyAsync(); + if (exists) + { + return SKResponseResult.Get(SKResponseCode.Fail, model.ProcessName + "已存在", false); + } + DictProcess insert = new() + { + DictType = dictType, + Category = category, + GroupName = groupName, + ProcessName = model.ProcessName, + Sort = model.Sort, + IsValid = true, + }; + var result = await _mysql.Insertable(insert).ExecuteCommandAsync() > 0; + if (result) + { + return SKResponseResult.Get(SKResponseCode.OK, "创建成功", true); + } + return SKResponseResult.Get(SKResponseCode.Fail, "创建失败", false); + } + + /// + /// 工序字典更新 + /// + /// 更新模型 + /// + [HttpPost] + public async Task> DictProcessUpdate( + [FromBody] DictProcess model) + { + if (!CanManageProcessDictionary()) + { + return SKResponseResult.Get(SKResponseCode.Fail, "无权限", false); + } + if (string.IsNullOrWhiteSpace(model.ProcessName)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "工序名称不能为空", false); + } + if (model.DictType == "非正常工时") + { + model.Category = "全部组别"; + model.GroupName = "全部组别"; + } + else if (model.DictType != "正常工时" || !WorkhourScopeDefinitions.IsProcessDictionaryCategory(model.Category)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "工时类型或大类无效", false); + } + if (string.IsNullOrWhiteSpace(model.Category) + || string.IsNullOrWhiteSpace(model.GroupName)) + { + return SKResponseResult.Get(SKResponseCode.Fail, "大类和组别(调试板件)不能为空", false); + } + var duplicate = await _mysql.Queryable() + .Where(it => it.ProcessId != model.ProcessId + && it.DictType == model.DictType + && it.Category == model.Category + && it.GroupName == model.GroupName + && it.ProcessName == model.ProcessName) + .AnyAsync(); + if (duplicate) + { + return SKResponseResult.Get(SKResponseCode.Fail, model.ProcessName + "已存在", false); + } + _logger.LogInformation("更新工序:{model}", JsonConvert.SerializeObject(model)); + var result = await _mysql.Updateable(model).ExecuteCommandAsync() > 0; + if (result) + { + return SKResponseResult.Get(SKResponseCode.OK, "更新成功", true); + } + return SKResponseResult.Get(SKResponseCode.Fail, "更新失败", false); + } + + #endregion + + #region 内部方法 + + private async Task> GetCurrentWorkhourScopes() + { + if (HttpContext.Items["user"] is not UserBasicInfo user) + { + return new List(); + } + var scopes = await _mysql.Queryable() + .Where(it => it.UserId == user.UserId) + .Select(it => it.Category) + .ToListAsync(); + return scopes.Distinct(StringComparer.Ordinal).ToList(); + } + + private async Task> GetCurrentWorkhourCategories() + { + return WorkhourScopeDefinitions.ExpandFillCategories(await GetCurrentWorkhourScopes()); + } + + private async Task HasAbnormalGroupScope(string? groupName) + { + var scope = WorkhourScopeDefinitions.GetAbnormalScopeForGroup(groupName); + if (scope == null) + { + return false; + } + var assignedScopes = await GetCurrentWorkhourScopes(); + return assignedScopes.Contains(scope, StringComparer.Ordinal); + } + + private bool CanManageProcessDictionary() + { + return HttpContext.Items["user"] is UserBasicInfo user && user.RoleId < 3; + } + + private static string BuildWorkOrderProductKey(string? workOrderCode, string? devCode) + { + return $"{workOrderCode ?? string.Empty}\u001f{devCode ?? string.Empty}"; + } + + /// + /// 计算工序填报进度并生成软提示 + /// + private async Task BuildProgress( + string? workOrderCode, string? devCode, + string? category, string? groupName, string? processName, int newQty) + { + if (string.IsNullOrEmpty(workOrderCode) || string.IsNullOrEmpty(devCode)) + { + return null; + } + var productSnapshot = await _mysql.Queryable() + .Where(it => it.WorkOrderCode == workOrderCode && it.DevCode == devCode) + .FirstAsync(); + var legacyOrder = productSnapshot == null + ? await _mysql.Queryable() + .Where(it => it.WorkOrderCode == workOrderCode && it.DevCode == devCode) + .FirstAsync() + : null; + if (productSnapshot == null && legacyOrder == null) + { + return null; + } + var manuNum = productSnapshot?.ManuNum ?? legacyOrder!.ManuNum; + + var agg = await _mysql.Queryable() + .Where(it => it.WorkOrderCode == workOrderCode + && it.DevCode == devCode + && it.Category == category + && it.ProcessName == processName + && it.DictType == "正常工时") + .Where(it => it.GroupName == groupName) + .GroupBy(it => new { it.WorkOrderCode, it.DevCode }) + .Select(it => new + { + Qty = SqlFunc.AggregateSum(it.Qty), + Minutes = SqlFunc.AggregateSum(it.Minutes), + Rows = SqlFunc.AggregateCount(it.RecordId) + }) + .FirstAsync(); + + var filled = agg?.Qty ?? 0; + var minutes = agg?.Minutes ?? 0; + var rowCount = agg?.Rows ?? 0; + + var model = new WorkhourProgressModel + { + ManuNum = manuNum, + FilledNum = filled, + RemainNum = manuNum - filled, + Minutes = minutes, + }; + + // 有历史记录时提示重复填报,不阻止提交。 + if (rowCount > 0) + { + model.Warnings.Add($"「{category} / {groupName} / {processName}」已有 {rowCount} 条历史填报记录,累计 {filled} 台。"); + } + // 超过计划量时提醒;返工和补投仍可提交。 + if (newQty > 0 && filled + newQty > manuNum) + { + model.Warnings.Add($"本次 {newQty} 台,累计将达到 {filled + newQty} 台,超过计划量 {manuNum} 台。"); + } + // 已完成计划量时提醒。 + if (filled >= manuNum && manuNum > 0) + { + model.Warnings.Add($"「{category} / {groupName} / {processName}」已填报 {filled} 台,已达到计划量。"); + } + return model; + } + + private sealed record LiveWorkOrderMaterial( + string DevCode, + string? ProductNumber, + string? ProductName, + string? ProductMode, + int ManuNum, + int InboundNum); + + #endregion + } + + public sealed class WorkhourTemplatePreviewRequest + { + public int Year { get; set; } + public int[]? Months { get; set; } + public string[]? BusinessSegments { get; set; } + public string? DictType { get; set; } + public List? Records { get; set; } + } +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Filter/ClientIpCheckActionFilter.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Filter/ClientIpCheckActionFilter.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Filter/ClientIpCheckActionFilter.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Filter/ClientIpCheckActionFilter.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Filter/GlobalAsyncExceptionFilter.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Filter/GlobalAsyncExceptionFilter.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Filter/GlobalAsyncExceptionFilter.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Filter/GlobalAsyncExceptionFilter.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Filter/OpenApiTokenParameterFilter.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Filter/OpenApiTokenParameterFilter.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Filter/OpenApiTokenParameterFilter.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Filter/OpenApiTokenParameterFilter.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Filter/TokenFilter.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Filter/TokenFilter.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Filter/TokenFilter.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Filter/TokenFilter.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Configs/BaseConfigHelper.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Configs/BaseConfigHelper.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Configs/BaseConfigHelper.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Configs/BaseConfigHelper.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Configs/BaseXmlConfig.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Configs/BaseXmlConfig.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Configs/BaseXmlConfig.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Configs/BaseXmlConfig.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Configs/Configer.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Configs/Configer.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Configs/Configer.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Configs/Configer.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/AppTokenHelper.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/AppTokenHelper.cs similarity index 76% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/AppTokenHelper.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/AppTokenHelper.cs index d772ec1..7186edc 100644 --- a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/AppTokenHelper.cs +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/AppTokenHelper.cs @@ -15,26 +15,28 @@ namespace SK_ERP_WebService.Jdy.Helper internal static void ParseTokenFromJson(IToken token, string json) { var at = JsonConvert.DeserializeAnonymousType(json, new { errcode = 0, description = "", data = new TokenData() }); - if (at?.data != null) + if (at?.data == null || string.IsNullOrWhiteSpace(at.data.AppToken) || at.data.Expires <= 0) { - token.SetAppToken(at.data.AppToken, DateTimeOffset.FromUnixTimeMilliseconds(at.data.Expires).DateTime, DateTime.Now); + throw new InvalidOperationException("金蝶未返回有效的 app-token 或过期时间。"); } + var expiresAt = DateTimeOffset.FromUnixTimeMilliseconds(at.data.Expires).LocalDateTime; + if (expiresAt <= DateTime.Now.AddMinutes(1)) + { + throw new InvalidOperationException("金蝶返回的 app-token 已过期或即将过期。"); + } + token.SetAppToken(at.data.AppToken, expiresAt, DateTime.Now); } internal static void ParseAuthorizeFromJson(IToken token, string json) { var at = JsonConvert.DeserializeAnonymousType(json, new { code = 0, msg = "", data = new List() }); - if (at?.data.Count > 0) + var item = at?.data?.FirstOrDefault(account => token?.ClientId?.Equals(account.ClientId, StringComparison.Ordinal) ?? false); + if (item == null || string.IsNullOrWhiteSpace(item.AppSecret) + || string.IsNullOrWhiteSpace(item.Domain) || string.IsNullOrWhiteSpace(item.AccountId)) { - foreach (var item in at.data) - { - - if (token?.ClientId?.Equals(item.ClientId) ?? false) - { - token.SetAppAuthorize(item.AppSecret, item.Domain, item.AccountId, DateTime.Now); - } - } + throw new InvalidOperationException("金蝶授权响应未包含当前应用的完整账套授权信息。"); } + token.SetAppAuthorize(item.AppSecret, item.Domain, item.AccountId, DateTime.Now); } public static bool PushAppAuthorize(IToken token, ref ErrorMessage? msg) @@ -55,7 +57,10 @@ namespace SK_ERP_WebService.Jdy.Helper try { ParseAuthorizeFromJson(token, result); - UpdateAppToken(token, ref msg, false); + if (!UpdateAppToken(token, ref msg, false)) + { + return false; + } msg = new ErrorMessage(0, "从服务器获取响应成功."); return true; } @@ -109,4 +114,4 @@ namespace SK_ERP_WebService.Jdy.Helper return false; } } -} \ No newline at end of file +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/CustomMultFieldHelper.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/CustomMultFieldHelper.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/CustomMultFieldHelper.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/CustomMultFieldHelper.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/CustomerHelper.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/CustomerHelper.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/CustomerHelper.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/CustomerHelper.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/InventoryHelper.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/InventoryHelper.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/InventoryHelper.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/InventoryHelper.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/MaterialHelper.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/MaterialHelper.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/MaterialHelper.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/MaterialHelper.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SalOrderHelper.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SalOrderHelper.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SalOrderHelper.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SalOrderHelper.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SubmProdinHelper.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SubmProdinHelper.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SubmProdinHelper.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SubmProdinHelper.cs diff --git a/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SubmWorkorderHelper.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SubmWorkorderHelper.cs new file mode 100644 index 0000000..29975b9 --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SubmWorkorderHelper.cs @@ -0,0 +1,375 @@ +using Newtonsoft.Json; +using SK_ERP_WebService.Jdy.Interfaces; +using SK_ERP_WebService.Jdy.Util; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Text.RegularExpressions; + +namespace SK_ERP_WebService.Jdy.Helper +{ + public class SubmWorkorderHelper + { + private const string UrlForGetDetial = "/jdy/v2/pm/subm_workorder_detail"; + private const string UrlForGetProductionTaskDetail = "/jdy/v2/pm/mo_taskbill_detail"; + private const string UrlForGetList = "/jdy/v2/pm/subm_workorder"; + private const string GetDetialHttpMethod = WebRequestMethods.Http.Get; + private const string GetListHttpMethod = WebRequestMethods.Http.Get; + + public static bool GetList(IToken token, int page, int pageSize, string? beginTime, string? endTime, ref ErrorMessage msg) + { + string paramValue = $"begin_date={beginTime}&end_date={endTime}&page={page}&page_size={pageSize}"; + string? url = token.GetUrl(UrlForGetList, paramValue); + string result = string.Empty; + string httpText = SignHelper.CreateHttpText(GetListHttpMethod, UrlForGetList, paramValue); + if (!RequestHelper.Request(url, httpText, ref result, GetListHttpMethod, true)) + { + msg = new ErrorMessage(ErrorMessage.ExceptionCode, result); + } + else if (ErrorMessage.IsErrorMessage(result)) + { + msg = ErrorMessage.Parse(result); + } + else + { + try + { + var obj = JsonConvert.DeserializeAnonymousType(result, new + { + errcode = 0, + description = "", + data = new + { + count = 0, + total_page = 0, + cur_page_size = 0, + page_size = 0, + page = 0, + rows = new List() + } + }); + + List list = []; + if (obj != null) + { + foreach (var item in obj.data.rows) + { + if (item != null) + { + ErrorMessage msg2 = new(ErrorMessage.ExceptionCode, ""); + if (GetDetail(token, item.BillNo, ref msg2)) + { + var subm = msg2.Data as SubmWorkorderRow; + subm?.Materials?.ForEach(it => it.SubMaterials = null); + list.Add(subm); + } + } + } + msg = new ErrorMessage(0, "从服务器获取响应成功.", new SubmWorkorderPage { List = list, Count = obj.data.count, PageIndex = obj.data.page, TotalPage = obj.data.total_page }); + return true; + } + + } + catch (Exception ex) + { + msg = new ErrorMessage(ex); + } + } + return false; + } + + public static bool GetDetail(IToken token, string? number, ref ErrorMessage msg) + { + return GetDetailByUrl(token, number, UrlForGetDetial, ref msg); + } + + /// + /// 工时填报可查询生产任务单和委外加工单。 + /// 委外详情缺少可填报产品时,按工单日期从列表定位单据 ID 后重查详情。 + /// + public static bool GetWorkhourOrderDetail(IToken token, string? number, ref ErrorMessage msg) + { + ErrorMessage productionMessage = new(ErrorMessage.ExceptionCode, "生产任务单查询未完成"); + if (GetDetailByUrl(token, number, UrlForGetProductionTaskDetail, ref productionMessage)) + { + if (HasSelectableMaterial(productionMessage.Data as SubmWorkorderRow)) + { + msg = productionMessage; + return true; + } + productionMessage = new ErrorMessage(ErrorMessage.ExceptionCode, + "生产任务单接口已返回,但明细中没有可识别的商品编号或机型代码"); + } + + ErrorMessage outsourceMessage = new(ErrorMessage.ExceptionCode, "委外加工单查询未完成"); + if (GetDetailByUrl(token, number, UrlForGetDetial, ref outsourceMessage)) + { + if (HasSelectableMaterial(outsourceMessage.Data as SubmWorkorderRow)) + { + msg = outsourceMessage; + return true; + } + outsourceMessage = new ErrorMessage(ErrorMessage.ExceptionCode, + "委外加工单接口已返回,但明细中没有可识别的商品编号或机型代码"); + } + + ErrorMessage idLookupMessage = new(ErrorMessage.ExceptionCode, "未尝试按工单日期回查ERP单据ID"); + if (TryGetSubmWorkorderId(token, number, out string? submWorkorderId, ref idLookupMessage)) + { + ErrorMessage detailByIdMessage = new(ErrorMessage.ExceptionCode, "委外加工单ID详情查询未完成"); + if (GetDetailByUrl(token, submWorkorderId, UrlForGetDetial, ref detailByIdMessage, "id")) + { + if (HasSelectableMaterial(detailByIdMessage.Data as SubmWorkorderRow)) + { + msg = detailByIdMessage; + return true; + } + + detailByIdMessage = new ErrorMessage(ErrorMessage.ExceptionCode, + "委外加工单ID详情已返回,但明细中没有可识别的商品编号或机型代码"); + } + + outsourceMessage = detailByIdMessage; + } + else + { + outsourceMessage = new ErrorMessage(ErrorMessage.ExceptionCode, + $"{outsourceMessage.ErrMsg};按日期列表回查ERP单据ID失败:{idLookupMessage.ErrMsg}"); + } + + msg = new ErrorMessage(ErrorMessage.ExceptionCode, + $"生产任务单查询:{productionMessage.ErrMsg};委外加工单查询:{outsourceMessage.ErrMsg}"); + return false; + } + + private static bool TryGetSubmWorkorderId( + IToken token, + string? number, + out string? workorderId, + ref ErrorMessage msg) + { + workorderId = null; + if (string.IsNullOrWhiteSpace(number)) + { + msg = new ErrorMessage(ErrorMessage.ExceptionCode, "工单号不能为空"); + return false; + } + + Match dateMatch = Regex.Match(number, @"^[^-]+-(?\d{8})-"); + if (!dateMatch.Success || !DateTime.TryParseExact( + dateMatch.Groups["date"].Value, + "yyyyMMdd", + CultureInfo.InvariantCulture, + DateTimeStyles.None, + out DateTime orderDate)) + { + msg = new ErrorMessage(ErrorMessage.ExceptionCode, "工单号不包含可用于ERP日期筛选的年月日"); + return false; + } + + string date = orderDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + const int pageSize = 100; + int totalPages = 1; + for (int page = 1; page <= totalPages; page++) + { + string paramValue = $"begin_date={date}&end_date={date}&page={page}&page_size={pageSize}"; + string? url = token.GetUrl(UrlForGetList, paramValue); + string result = string.Empty; + string httpText = SignHelper.CreateHttpText(GetListHttpMethod, UrlForGetList, paramValue); + if (!RequestHelper.Request(url, httpText, ref result, GetListHttpMethod, true)) + { + msg = new ErrorMessage(ErrorMessage.ExceptionCode, result); + return false; + } + if (ErrorMessage.IsErrorMessage(result)) + { + msg = ErrorMessage.Parse(result); + return false; + } + + try + { + var response = JsonConvert.DeserializeAnonymousType(result, new + { + errcode = 0, + description = "", + data = new + { + total_page = 1, + rows = new List() + } + }); + + if (response?.data?.rows == null) + { + msg = new ErrorMessage(ErrorMessage.ExceptionCode, "ERP工单列表未返回可识别的数据"); + return false; + } + + SubmWorkorderList? matchedOrder = response.data.rows.FirstOrDefault(item => + string.Equals(item.BillNo, number, StringComparison.OrdinalIgnoreCase)); + if (!string.IsNullOrWhiteSpace(matchedOrder?.Id)) + { + workorderId = matchedOrder.Id; + msg = new ErrorMessage(0, "已从ERP工单列表定位到单据ID"); + return true; + } + + totalPages = Math.Max(totalPages, response.data.total_page); + } + catch (Exception ex) + { + msg = new ErrorMessage(ex); + return false; + } + } + + msg = new ErrorMessage(ErrorMessage.ExceptionCode, $"ERP工单列表中未找到单号:{number}"); + return false; + } + + private static bool HasSelectableMaterial(SubmWorkorderRow? order) + { + return order?.Materials?.Any(item => + !string.IsNullOrWhiteSpace(item.DeviceCode) || !string.IsNullOrWhiteSpace(item.Number)) == true; + } + + private static bool GetDetailByUrl( + IToken token, + string? number, + string urlPath, + ref ErrorMessage msg, + string parameterName = "number") + { + if (string.IsNullOrWhiteSpace(number)) + { + msg = new ErrorMessage(ErrorMessage.ExceptionCode, "工单号不能为空"); + return false; + } + string numberE = Uri.EscapeDataString(number); + string query = $"{parameterName}={numberE}"; + string? url = token.GetUrl(urlPath, query); + string result = string.Empty; + string httpText = SignHelper.CreateHttpText(GetDetialHttpMethod, urlPath, $"{parameterName}={Uri.EscapeDataString(numberE)}"); + if (!RequestHelper.Request(url, httpText, ref result, GetDetialHttpMethod, true)) + { + msg = new ErrorMessage(ErrorMessage.ExceptionCode, result); + return false; + } + if (ErrorMessage.IsErrorMessage(result)) + { + msg = ErrorMessage.Parse(result); + return false; + } + try + { + var obj = JsonConvert.DeserializeAnonymousType(result, new + { + errcode = 0, + description = "", + data = new SubmWorkorderRow() + }); + if (obj?.data != null) + { + msg = new ErrorMessage(0, "从服务器获取响应成功.", obj.data); + return true; + } + msg = new ErrorMessage(ErrorMessage.ExceptionCode, "金蝶未返回工单详情"); + } + catch (Exception ex) + { + msg = new ErrorMessage(ex); + } + return false; + } + public static bool KitMatchingAnalysis(IToken token, string? number, string? devCode, ref ErrorMessage msg) + { + if (!String.IsNullOrEmpty(number)) + { + string numberE = Uri.EscapeDataString(number); + string? url = token.GetUrl(UrlForGetDetial, string.Format("number={0}", numberE)); + string result = string.Empty; + string httpText = SignHelper.CreateHttpText(GetDetialHttpMethod, UrlForGetDetial, string.Format("number={0}", Uri.EscapeDataString(numberE))); + if (!RequestHelper.Request(url, httpText, ref result, GetDetialHttpMethod, true)) + { + msg = new ErrorMessage(ErrorMessage.ExceptionCode, result); + } + else if (ErrorMessage.IsErrorMessage(result)) + { + msg = ErrorMessage.Parse(result); + } + else + { + try + { + var obj = JsonConvert.DeserializeAnonymousType(result, new + { + errcode = 0, + description = "", + data = new SubmWorkorderRow() + }); + if (obj != null) + { + var list = new List(); + obj.data.Materials?.ForEach(it1 => + { + if (!string.IsNullOrEmpty(devCode)) + { + if (it1.DeviceCode != devCode) + { + return; + } + } + it1.SubMaterials?.ForEach(item => + { + item.DeviceCode = it1.DeviceCode; + item.DeviceName = it1.Name; + float ivnQty = 0; + var stockName = new List(); + ErrorMessage msg2 = new(ErrorMessage.ExceptionCode, ""); + InventoryHelper.GetStockList(token, item.Id, ref msg2); + if (msg2?.Data is List sr) + { + sr?.ForEach(it2 => + { + ivnQty += it2.Imqty; + stockName.Add(it2.Name); + //if (it2.StockId== item.StockId) + //{ + // item.IvnQty = it2.Imqty; + + //} + }); + } + if (stockName.Count > 0) + { + item.IvnQty = ivnQty; + if (item.IvnQty > item.Qty) + { + item.Id = "齐套"; + } + else + { + item.Id = "待备货"; + } + item.StockName = string.Join(",", stockName); + list.Add(item); + } + }); + }); + msg = new ErrorMessage(0, "从服务器获取响应成功.", list); + return true; + } + } + catch (Exception ex) + { + msg = new ErrorMessage(ex); + } + } + } + return false; + } + } +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SupplierlHelper.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SupplierlHelper.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SupplierlHelper.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SupplierlHelper.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Interfaces/IToken.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Interfaces/IToken.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Interfaces/IToken.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Interfaces/IToken.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/AccountInfo.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/AccountInfo.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/AccountInfo.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/AccountInfo.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/Bomentity.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/Bomentity.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/Bomentity.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/Bomentity.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/CustomFieldRow.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/CustomFieldRow.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/CustomFieldRow.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/CustomFieldRow.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/CustomerRow.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/CustomerRow.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/CustomerRow.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/CustomerRow.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/ErrorMessage.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/ErrorMessage.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/ErrorMessage.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/ErrorMessage.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/Extensions.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/Extensions.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/Extensions.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/Extensions.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/MaterialRow.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/MaterialRow.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/MaterialRow.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/MaterialRow.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/RequestHelper.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/RequestHelper.cs similarity index 90% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/RequestHelper.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/RequestHelper.cs index b2cb76b..01fc6ea 100644 --- a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/RequestHelper.cs +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/RequestHelper.cs @@ -27,6 +27,16 @@ namespace SK_ERP_WebService.Jdy.Util { if (!string.IsNullOrEmpty(url)) { + if (withToken) + { + ErrorMessage? tokenMessage = null; + if (!TokenAccess.Instance.EnsureFreshAppToken(ref tokenMessage)) + { + responseData = Encoding.UTF8.GetBytes(tokenMessage?.ErrMsg ?? "金蝶 app-token 刷新失败。"); + return false; + } + } + HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url); httpRequest.Method = httpMethod; httpRequest.ContentType = "application/json"; @@ -98,4 +108,4 @@ namespace SK_ERP_WebService.Jdy.Util return Request(url, apiText, ref responseContent, httpMethod, true, bytes); } } -} \ No newline at end of file +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SalOrderRow.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SalOrderRow.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SalOrderRow.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SalOrderRow.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SignHelper.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SignHelper.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SignHelper.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SignHelper.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/StockRow.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/StockRow.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/StockRow.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/StockRow.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderList.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderList.cs similarity index 77% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderList.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderList.cs index d92fc44..9f31b7c 100644 --- a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderList.cs +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderList.cs @@ -4,10 +4,13 @@ namespace SK_ERP_WebService.Jdy.Util { public class SubmWorkorderList { + [JsonProperty(PropertyName = "id")] + public string? Id { get; set; } + [JsonProperty(PropertyName = "bill_no")] public string? BillNo { get; set; } [JsonProperty(PropertyName = "bill_date")] public string? BillDate { get; set; } } -} \ No newline at end of file +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderPage.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderPage.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderPage.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderPage.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderRow.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderRow.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderRow.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SubmWorkorderRow.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SupplierRow.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SupplierRow.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SupplierRow.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/SupplierRow.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/TokenAccess.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/TokenAccess.cs similarity index 75% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/TokenAccess.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/TokenAccess.cs index 23d6556..3792fb1 100644 --- a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/TokenAccess.cs +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/TokenAccess.cs @@ -9,6 +9,7 @@ namespace SK_ERP_WebService.Jdy.Util internal class TokenAccess : IToken { public static readonly TokenAccess Instance = new(); + private static readonly object AppTokenLock = new(); public string? Uid => Configer.Instance.Uid; @@ -56,7 +57,28 @@ namespace SK_ERP_WebService.Jdy.Util public bool IsTimeout() { - return DateTime.Now > ExpiresTime; + return string.IsNullOrWhiteSpace(_appToken) || DateTime.Now.AddMinutes(1) >= ExpiresTime; + } + + internal bool EnsureFreshAppToken(ref ErrorMessage? msg) + { + lock (AppTokenLock) + { + if (!IsTimeout()) + { + msg = new ErrorMessage(0, "当前 app-token 仍有效。"); + return true; + } + return AppTokenHelper.UpdateAppToken(this, ref msg); + } + } + + internal bool TryRefreshAppToken(ref ErrorMessage? msg) + { + lock (AppTokenLock) + { + return AppTokenHelper.UpdateAppToken(this, ref msg); + } } public void SetAppToken(string? token, DateTime expiresTime, DateTime refreshTime) @@ -75,7 +97,7 @@ namespace SK_ERP_WebService.Jdy.Util public void UpdateAppToken() { ErrorMessage? msg = null; - AppTokenHelper.UpdateAppToken(this, ref msg); + TryRefreshAppToken(ref msg); } public void SetAppAuthorize(string? appSecret, string? idc, string? accountId, DateTime refreshTime) @@ -88,4 +110,4 @@ namespace SK_ERP_WebService.Jdy.Util }); } } -} \ No newline at end of file +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/TokenData.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/TokenData.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/TokenData.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Jdy/Util/TokenData.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/DCSIBA.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/DCSIBA.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/DCSIBA.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/DCSIBA.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/DCSIBB.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/DCSIBB.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/DCSIBB.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/DCSIBB.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/ERPChipName.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/ERPChipName.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/ERPChipName.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/ERPChipName.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/ERPDeviceHardware.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/ERPDeviceHardware.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/ERPDeviceHardware.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/ERPDeviceHardware.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKKEA.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKKEA.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKKEA.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKKEA.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKKEB.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKKEB.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKKEB.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKKEB.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKLCA.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKLCA.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKLCA.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKLCA.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKLCB.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKLCB.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKLCB.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/JSKLCB.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/SGMRAA.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/SGMRAA.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/SGMRAA.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/SGMRAA.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/TPADBA.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/TPADBA.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/TPADBA.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/TPADBA.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/TPADEA.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/TPADEA.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/TPADEA.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/TPADEA.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/TPADFA.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/TPADFA.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/TPADFA.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/DataBase/TPADFA.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/Mes/MesVersion.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/Mes/MesVersion.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/Mes/MesVersion.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/Mes/MesVersion.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/BoxRecord.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/BoxRecord.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/BoxRecord.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/BoxRecord.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ClientBasicinfo.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ClientBasicinfo.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ClientBasicinfo.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ClientBasicinfo.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/CustomerBasicinfo.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/CustomerBasicinfo.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/CustomerBasicinfo.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/CustomerBasicinfo.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DeviceBasicinfo.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DeviceBasicinfo.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DeviceBasicinfo.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DeviceBasicinfo.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictBoxType.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictBoxType.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictBoxType.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictBoxType.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictMenu.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictMenu.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictMenu.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictMenu.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictModel.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictModel.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictModel.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictModel.cs diff --git a/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictProcess.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictProcess.cs new file mode 100644 index 0000000..6b6ae2f --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictProcess.cs @@ -0,0 +1,86 @@ +using SqlSugar; + +namespace SK_ERP_WebService.Model +{ + /// + /// 工序字典 + /// + [SugarTable("dict_process")] + public class DictProcess + { + /// + /// 主键 + /// + [SugarColumn(ColumnName = "process_id", IsPrimaryKey = true, IsIdentity = true)] + public int ProcessId { get; set; } + + /// + /// 字典类型:正常工时 / 非正常工时 + /// + [SugarColumn(ColumnName = "dict_type")] + public string? DictType { get; set; } + + /// + /// 工时组别或共享字典分类(非正常工时为“全部组别”) + /// + [SugarColumn(ColumnName = "category")] + public string? Category { get; set; } + + /// + /// 板件或非正常工时的共享字典组别 + /// + [SugarColumn(ColumnName = "group_name")] + public string? GroupName { get; set; } + + /// + /// 工序名称 + /// + [SugarColumn(ColumnName = "process_name")] + public string? ProcessName { get; set; } + + + /// + /// 排序 + /// + [SugarColumn(ColumnName = "sort")] + public int Sort { get; set; } + + /// + /// 是否启用 + /// + [SugarColumn(ColumnName = "is_valid")] + public bool IsValid { get; set; } = true; + } + + /// + /// 工序字典创建模型 + /// + public class DictProcessCreateModel + { + /// + /// 字典类型 + /// + public string? DictType { get; set; } + + /// + /// 工时组别或共享字典分类 + /// + public string? Category { get; set; } + + /// + /// 板件或非正常工时的共享字典组别 + /// + public string? GroupName { get; set; } + + /// + /// 工序名称 + /// + public string? ProcessName { get; set; } + + + /// + /// 排序 + /// + public int Sort { get; set; } + } +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictRole.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictRole.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictRole.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictRole.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictTransportType.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictTransportType.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictTransportType.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/DictTransportType.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/InstockRecord.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/InstockRecord.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/InstockRecord.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/InstockRecord.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/LogisticsRecord.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/LogisticsRecord.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/LogisticsRecord.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/LogisticsRecord.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ManuRepairRecord.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ManuRepairRecord.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ManuRepairRecord.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ManuRepairRecord.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/OutstockRecord.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/OutstockRecord.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/OutstockRecord.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/OutstockRecord.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductBasicinfo.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductBasicinfo.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductBasicinfo.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductBasicinfo.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductClassBasicinfo.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductClassBasicinfo.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductClassBasicinfo.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductClassBasicinfo.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductPackageDetail.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductPackageDetail.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductPackageDetail.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductPackageDetail.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductSoftCopyrightPrice.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductSoftCopyrightPrice.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductSoftCopyrightPrice.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductSoftCopyrightPrice.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductSubClassBasicinfo.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductSubClassBasicinfo.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductSubClassBasicinfo.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ProductSubClassBasicinfo.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/QRCodeRecord.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/QRCodeRecord.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/QRCodeRecord.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/QRCodeRecord.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RelaRoleMenu.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RelaRoleMenu.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RelaRoleMenu.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RelaRoleMenu.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RemodifyRecord.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RemodifyRecord.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RemodifyRecord.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RemodifyRecord.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RepairRecord.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RepairRecord.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RepairRecord.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RepairRecord.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RetstockRecord.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RetstockRecord.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RetstockRecord.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/RetstockRecord.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ReworkRecord.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ReworkRecord.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ReworkRecord.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/ReworkRecord.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/UserBasicinfo.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/UserBasicinfo.cs similarity index 94% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/UserBasicinfo.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/UserBasicinfo.cs index 2229869..12af50a 100644 --- a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/UserBasicinfo.cs +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/UserBasicinfo.cs @@ -70,6 +70,12 @@ namespace SK_ERP_WebService.Model [Navigate(NavigateType.OneToOne, nameof(RoleId))] public DictRole? Role { get; set; } + /// + /// 当前用户的工时填报权限范围(不映射数据库列) + /// + [SugarColumn(IsIgnore = true)] + public List WorkhourCategories { get; set; } = new(); + } /// diff --git a/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/UserWorkhourScope.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/UserWorkhourScope.cs new file mode 100644 index 0000000..31baa1e --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/UserWorkhourScope.cs @@ -0,0 +1,26 @@ +using SqlSugar; + +namespace SK_ERP_WebService.Model +{ + /// + /// 用户的工时填报权限范围。正常工时按流程大类授权,非正常工时按组别授权;权限按人员保存。 + /// + [SugarTable("rela_user_workhour_scope")] + public class UserWorkhourScope + { + [SugarColumn(ColumnName = "user_id", IsPrimaryKey = true)] + public int UserId { get; set; } + + [SugarColumn(ColumnName = "category", IsPrimaryKey = true)] + public string Category { get; set; } = string.Empty; + } + + /// + /// 更新某个人员的工时填报范围。 + /// + public class UserWorkhourScopeUpdateModel + { + public int UserId { get; set; } + public List Categories { get; set; } = new(); + } +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/WorkOrderInfo.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/WorkOrderInfo.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/MySql/WorkOrderInfo.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/WorkOrderInfo.cs diff --git a/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/WorkhourOrderProduct.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/WorkhourOrderProduct.cs new file mode 100644 index 0000000..685a6cc --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/WorkhourOrderProduct.cs @@ -0,0 +1,36 @@ +using SqlSugar; + +namespace SK_ERP_WebService.Model +{ + /// + /// 工时模块最近一次从金蝶实时查询到的工单产品快照。 + /// 与原有 work_order_info、dict_box_type 分开存储。 + /// + [SugarTable("workhour_order_product")] + public class WorkhourOrderProduct + { + [SugarColumn(ColumnName = "work_order_code", IsPrimaryKey = true)] + public string? WorkOrderCode { get; set; } + + [SugarColumn(ColumnName = "dev_code", IsPrimaryKey = true)] + public string? DevCode { get; set; } + + [SugarColumn(ColumnName = "product_number")] + public string? ProductNumber { get; set; } + + [SugarColumn(ColumnName = "product_name")] + public string? ProductName { get; set; } + + [SugarColumn(ColumnName = "product_mode")] + public string? ProductMode { get; set; } + + [SugarColumn(ColumnName = "manu_num")] + public int ManuNum { get; set; } + + [SugarColumn(ColumnName = "inbound_num")] + public int InboundNum { get; set; } + + [SugarColumn(ColumnName = "last_fetched_at")] + public DateTime LastFetchedAt { get; set; } + } +} diff --git a/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/WorkhourRecord.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/WorkhourRecord.cs new file mode 100644 index 0000000..7c94b74 --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/MySql/WorkhourRecord.cs @@ -0,0 +1,234 @@ +using Newtonsoft.Json; +using SqlSugar; + +namespace SK_ERP_WebService.Model +{ + /// + /// 工时填报记录 + /// 产品名称和规格型号在查询返回时从工时模块的 ERP 工单快照补齐。 + /// + [SugarTable("workhour_record")] + public class WorkhourRecord + { + /// + /// 主键 + /// + [SugarColumn(ColumnName = "record_id", IsPrimaryKey = true, IsIdentity = true)] + public long RecordId { get; set; } + + /// + /// 工单号 + /// + [SugarColumn(ColumnName = "work_order_code")] + public string? WorkOrderCode { get; set; } + + /// + /// 机型代码 + /// + [SugarColumn(ColumnName = "dev_code")] + public string? DevCode { get; set; } + + /// + /// 产品名称快照;无工单号的非正常工时由填报人填写,有工单时优先使用ERP产品名称。 + /// + [SugarColumn(ColumnName = "product_name")] + public string? ProductName { get; set; } + + /// + /// ERP 规格型号快照,由工时记录列表查询时关联工单产品快照填充。 + /// + [SugarColumn(IsIgnore = true)] + public string? ProductMode { get; set; } + + /// + /// 生产月份 yyyy-MM + /// + [SugarColumn(ColumnName = "mfg_month")] + public string? MfgMonth { get; set; } + + /// + /// 公司板块:智慧用电 / 智能家居 / 安防报警 + /// + [SugarColumn(ColumnName = "business_segment")] + public string? BusinessSegment { get; set; } + + /// + /// 工时组别:基板、调试、整机调试、整机总装、包装等 + /// + [SugarColumn(ColumnName = "category")] + public string? Category { get; set; } + + /// + /// 板件或非正常工时归属组别 + /// + [SugarColumn(ColumnName = "group_name")] + public string? GroupName { get; set; } + + /// + /// 工序 + /// + [SugarColumn(ColumnName = "process_name")] + public string? ProcessName { get; set; } + + /// + /// 字典类型:正常工时 / 非正常工时 + /// + [SugarColumn(ColumnName = "dict_type")] + public string? DictType { get; set; } + + /// + /// 本次数量(台) + /// + [SugarColumn(ColumnName = "qty")] + public int Qty { get; set; } + + /// + /// 本次工时(分钟) + /// + [SugarColumn(ColumnName = "minutes")] + public int Minutes { get; set; } + + /// + /// 填报人 + /// + [SugarColumn(ColumnName = "user_id")] + public int UserId { get; set; } + + /// + /// 作业日期 + /// + [SugarColumn(ColumnName = "work_date")] + public DateTime? WorkDate { get; set; } + + /// + /// 备注 + /// + [SugarColumn(ColumnName = "remark")] + public string? Remark { get; set; } + + /// + /// 创建时间 + /// + [SugarColumn(ColumnName = "create_time")] + public DateTime CreateTime { get; set; } = DateTime.Now; + + /// + /// 箱子类型(取产品名) + /// + [Navigate(NavigateType.OneToOne, nameof(DictBoxType.DevCode), nameof(DevCode))] + public DictBoxType? DevType { get; set; }//注意禁止手动赋值 + + /// + /// 填报人信息 + /// + [Navigate(NavigateType.OneToOne, nameof(UserBasicInfo.UserId), nameof(UserId))] + public UserBasicInfo? User { get; set; }//注意禁止手动赋值 + } + + /// + /// 工时填报创建模型 + /// + public class WorkhourRecordCreateModel + { + /// + /// 工单号 + /// + public string? WorkOrderCode { get; set; } + + /// + /// 机型代码 + /// + public string? DevCode { get; set; } + + /// + /// 产品名称;无工单号的非正常工时可手工填写。 + /// + public string? ProductName { get; set; } + + /// + /// 生产月份 yyyy-MM + /// + public string? MfgMonth { get; set; } + + /// + /// 公司板块:智慧用电 / 智能家居 / 安防报警 + /// + public string? BusinessSegment { get; set; } + + /// + /// 工时组别 + /// + public string? Category { get; set; } + + /// + /// 板件或非正常工时归属组别 + /// + public string? GroupName { get; set; } + + /// + /// 工序 + /// + public string? ProcessName { get; set; } + + /// + /// 字典类型 + /// + public string? DictType { get; set; } + + /// + /// 本次数量 + /// + public int Qty { get; set; } + + /// + /// 本次工时(分钟) + /// + public int Minutes { get; set; } + + /// + /// 作业日期 + /// + public DateTime? WorkDate { get; set; } + + /// + /// 备注 + /// + public string? Remark { get; set; } + } + + /// + /// 工时填报更新模型 + /// + public class WorkhourRecordUpdateModel + { + /// + /// 主键 + /// + public long RecordId { get; set; } + + /// + /// 无工单号的非正常工时产品名称。 + /// + public string? ProductName { get; set; } + + /// + /// 本次数量 + /// + public int Qty { get; set; } + + /// + /// 本次工时(分钟) + /// + public int Minutes { get; set; } + + /// + /// 作业日期 + /// + public DateTime? WorkDate { get; set; } + + /// + /// 备注 + /// + public string? Remark { get; set; } + } +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/QRCodeDb/TRCodeInfo.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/QRCodeDb/TRCodeInfo.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/QRCodeDb/TRCodeInfo.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/QRCodeDb/TRCodeInfo.cs diff --git a/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/QRRecordCreateModel.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/QRRecordCreateModel.cs new file mode 100644 index 0000000..6bc1e0a --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/QRRecordCreateModel.cs @@ -0,0 +1,14 @@ +namespace SK_ERP_WebService.Model; + +public class QRRecordCreateModel +{ + public string? UniqueCode { get; set; } + + public string? PanelType { get; set; } + + public string? Operator { get; set; } + + public string? ICCID { get; set; } + + public string? IMEI { get; set; } +} \ No newline at end of file diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/RepairCount/UserRepairCountModel.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/RepairCount/UserRepairCountModel.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/RepairCount/UserRepairCountModel.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/RepairCount/UserRepairCountModel.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/Response/ChartDataModel.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/Response/ChartDataModel.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/Response/ChartDataModel.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/Response/ChartDataModel.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/Response/SGMRAAInfo.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/Response/SGMRAAInfo.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/Response/SGMRAAInfo.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/Response/SGMRAAInfo.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/Response/SKResponseJsonModel.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/Response/SKResponseJsonModel.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/Response/SKResponseJsonModel.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/Response/SKResponseJsonModel.cs diff --git a/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/Response/WorkhourInfo.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/Response/WorkhourInfo.cs new file mode 100644 index 0000000..d8d2151 --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/Response/WorkhourInfo.cs @@ -0,0 +1,195 @@ +using SqlSugar; + +namespace SK_ERP_WebService.Model +{ + /// + /// 工单产品行(填报弹窗用) + /// 工单详情从金蝶实时读取,查询结果同时更新工时模块自己的工单快照。 + /// + public class WorkhourProductModel + { + /// + /// 工单号 + /// + public string? WorkOrderCode { get; set; } + + /// + /// 机型代码 + /// + public string? DevCode { get; set; } + + /// + /// 产品品号 + /// + public string? ProdNo { get; set; } + + /// + /// ERP 工单物料名称 + /// + public string? ProductName { get; set; } + + /// + /// 规格型号(从金蝶工单物料明细实时读取) + /// + public string? ProductMode { get; set; } + + /// + /// ERP 工单物料计划数量 + /// + public int ManuNum { get; set; } + + /// + /// ERP 工单物料已入库数量 + /// + public int InboundNum { get; set; } + + /// + /// 入库差额 = 计划 - 已入库(仅工单进度参考,不作为填报上限) + /// + public int InboundDiff { get; set; } + } + + /// + /// 工序填报进度 + /// + public class WorkhourProgressModel + { + /// + /// 应填报量 = 该(工单,型号)的计划数量 + /// + public int ManuNum { get; set; } + + /// + /// 已填报量 = SUM(workhour_record.qty) + /// + public int FilledNum { get; set; } + + /// + /// 本工序待填报量 = ManuNum - FilledNum + /// + public int RemainNum { get; set; } + + /// + /// 已填报工时(分钟) + /// + public int Minutes { get; set; } + + /// + /// 提示信息(软提示,不拦截) + /// + public List Warnings { get; set; } = []; + } + + /// + /// 工时统计-按工单 + /// + public class WorkhourStatOrderModel + { + /// + /// 工单号 + /// + public string? WorkOrderCode { get; set; } + + /// + /// 型号数 + /// + public int DevCount { get; set; } + + /// + /// 计划量 + /// + public int ManuNum { get; set; } + + /// + /// 已入库 + /// + public int InboundNum { get; set; } + + /// + /// 入库差额 + /// + public int InboundDiff { get; set; } + + /// + /// 累计工时(分钟) + /// + public int Minutes { get; set; } + + /// + /// 累计工时(小时) + /// + public decimal Hours { get; set; } + } + + /// + /// 工时统计-按工序 + /// + public class WorkhourStatProcessModel + { + /// + /// 工时类型 + /// + public string? DictType { get; set; } + + /// + /// 大类 + /// + public string? Category { get; set; } + + /// + /// 组别 + /// + public string? GroupName { get; set; } + + /// + /// 工序 + /// + public string? ProcessName { get; set; } + + /// + /// 已填报台次 + /// + public int Qty { get; set; } + + /// + /// 工时(分钟) + /// + public int Minutes { get; set; } + + /// + /// 工时(小时) + /// + public decimal Hours { get; set; } + } + + /// + /// 工时统计-按月份 + /// + public class WorkhourStatMonthModel + { + /// + /// 工时类型 + /// + public string? DictType { get; set; } + + /// + /// 月份 yyyy-MM + /// + public string? MfgMonth { get; set; } + + /// + /// 已填报台次 + /// + public int Qty { get; set; } + + /// + /// 工时(分钟) + /// + public int Minutes { get; set; } + + /// + /// 工时(小时) + /// + public decimal Hours { get; set; } + } +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/ShikePay/ShikePayCardType.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/ShikePay/ShikePayCardType.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/ShikePay/ShikePayCardType.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/ShikePay/ShikePayCardType.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/ShikePay/ShikePayIot.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/ShikePay/ShikePayIot.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/ShikePay/ShikePayIot.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/ShikePay/ShikePayIot.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Model/TelecomCloud/TelecomCloudWechatUser.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/TelecomCloud/TelecomCloudWechatUser.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Model/TelecomCloud/TelecomCloudWechatUser.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/TelecomCloud/TelecomCloudWechatUser.cs diff --git a/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/WorkhourScopeDefinitions.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/WorkhourScopeDefinitions.cs new file mode 100644 index 0000000..9eabfff --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Model/WorkhourScopeDefinitions.cs @@ -0,0 +1,120 @@ +namespace SK_ERP_WebService.Model +{ + /// + /// 正常工时按流程大类授权,非正常工时按模板组别独立授权。 + /// + public static class WorkhourScopeDefinitions + { + public const string Board = "基板"; + public const string Debug = "调试"; + public const string Machine = "整机"; + public const string MachineDebug = "整机调试"; + public const string MachineAssembly = "整机总装"; + public const string Packaging = "包装"; + public const string AbnormalPrefix = "非正常工时-"; + public const string AbnormalBoard = "非正常工时-基板"; + public const string AbnormalDebug = "非正常工时-调试"; + public const string AbnormalAssembly = "非正常工时-总装"; + public const string AbnormalPackaging = "非正常工时-包装"; + + public static readonly string[] AbnormalScopes = + [ + AbnormalBoard, + AbnormalDebug, + AbnormalAssembly, + AbnormalPackaging, + ]; + + public static readonly string[] AllScopes = + [ + MachineDebug, + MachineAssembly, + Board, + Debug, + Machine, + Packaging, + .. AbnormalScopes, + ]; + + /// + /// “整机”保留为人员权限标签;填报按模板拆成整机调试、整机总装、包装三类。 + /// 保留父标签本身以兼容历史记录查询,同时扩展到三种可填报分类。 + /// + public static List ExpandFillCategories(IEnumerable scopes) + { + var categories = scopes + .Where(scope => !IsAbnormalScope(scope)) + .Distinct() + .ToList(); + if (categories.Contains(Machine)) + { + foreach (var category in new[] { MachineDebug, MachineAssembly, Packaging }) + { + if (!categories.Contains(category)) categories.Add(category); + } + } + return categories; + } + + public static bool IsDirectNormalCategory(string? category) + { + return category is MachineDebug or MachineAssembly or Packaging; + } + + public static bool IsProcessDictionaryCategory(string? category) + { + return category is Board or Debug; + } + + public static bool IsValidAbnormalGroup(string? category, string? groupName) + { + return (category, groupName) switch + { + (Board, "基板") => true, + (Debug, "调试") => true, + (Machine, "调试" or "总装" or "包装") => true, + (MachineDebug, "调试") => true, + (MachineAssembly, "总装") => true, + (Packaging, "包装") => true, + _ => false, + }; + } + + public static bool IsAbnormalScope(string? scope) + { + return scope != null && scope.StartsWith(AbnormalPrefix, StringComparison.Ordinal); + } + + public static string? GetAbnormalScopeForGroup(string? groupName) + { + return groupName switch + { + "基板" => AbnormalBoard, + "调试" => AbnormalDebug, + "总装" => AbnormalAssembly, + "包装" => AbnormalPackaging, + _ => null, + }; + } + + public static string? GetAbnormalCategoryForGroup(string? groupName) + { + return groupName switch + { + "基板" => Board, + "调试" => Debug, + "总装" => MachineAssembly, + "包装" => Packaging, + _ => null, + }; + } + + public static List GetAuthorizedAbnormalGroups(IEnumerable scopes) + { + var scopeSet = scopes.ToHashSet(StringComparer.Ordinal); + return new[] { "基板", "调试", "总装", "包装" } + .Where(group => scopeSet.Contains(GetAbnormalScopeForGroup(group)!)) + .ToList(); + } + } +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Program.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Program.cs similarity index 99% rename from SK_ERP_WebService/SK_ERP_WebService/Program.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Program.cs index e1ef33b..b44760a 100644 --- a/SK_ERP_WebService/SK_ERP_WebService/Program.cs +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Program.cs @@ -118,7 +118,7 @@ try q.AddTrigger(opts => opts .ForJob("JdyTokenJob") .WithIdentity("JdyTokenJob-Trigger") - .WithCronSchedule("0 0 1 ? * *") + .WithCronSchedule("0 0 0/6 ? * *") ); }); builder.Services.AddQuartzServer(options => diff --git a/SK_ERP_WebService/SK_ERP_WebService/Properties/launchSettings.json b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Properties/launchSettings.json similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Properties/launchSettings.json rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Properties/launchSettings.json diff --git a/SK_ERP_WebService/SK_ERP_WebService/SK_ERP_WebService.csproj b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/SK_ERP_WebService.csproj similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/SK_ERP_WebService.csproj rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/SK_ERP_WebService.csproj diff --git a/SK_ERP_WebService/SK_ERP_WebService/Service/DbContext.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/DbContext.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Service/DbContext.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/DbContext.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Service/JdyService.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/JdyService.cs similarity index 84% rename from SK_ERP_WebService/SK_ERP_WebService/Service/JdyService.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/JdyService.cs index 4402e77..b876aa7 100644 --- a/SK_ERP_WebService/SK_ERP_WebService/Service/JdyService.cs +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/JdyService.cs @@ -18,11 +18,27 @@ namespace SK_ERP_WebService.Service public JdyService(ILogger logger) { _logger = logger; - TokenAccess.Instance.UpdateAppToken(); + UpdateAppToken(); } - public void UpdateAppToken() + public bool UpdateAppToken() { - TokenAccess.Instance.UpdateAppToken(); + ErrorMessage? msg = null; + var updated = TokenAccess.Instance.TryRefreshAppToken(ref msg); + if (updated) + { + _logger.LogInformation("金蝶云 app-token 已刷新。"); + } + else + { + _logger.LogWarning("金蝶云 app-token 刷新失败,错误码:{ErrorCode},错误:{ErrorMessage}", + msg?.ErrCode, msg?.ErrMsg); + } + return updated; + } + public bool GetWorkhourOrderDetail(string? number, ref ErrorMessage? msg) + { + msg = new(ErrorMessage.ExceptionCode, ""); + return SubmWorkorderHelper.GetWorkhourOrderDetail(TokenAccess.Instance, number, ref msg); } public bool GetSubmWorkorderDetail(string? number, ref ErrorMessage? msg) { diff --git a/SK_ERP_WebService/SK_ERP_WebService/Service/MesDbContext.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/MesDbContext.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Service/MesDbContext.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/MesDbContext.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Service/MySqlDbContext.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/MySqlDbContext.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Service/MySqlDbContext.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/MySqlDbContext.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Service/QRCodeContext.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/QRCodeContext.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Service/QRCodeContext.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/QRCodeContext.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Service/SKERPServiceExtensions.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/SKERPServiceExtensions.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Service/SKERPServiceExtensions.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/SKERPServiceExtensions.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Service/SKWechatApi.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/SKWechatApi.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Service/SKWechatApi.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/SKWechatApi.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Service/TelecomCloudDbContext.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/TelecomCloudDbContext.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Service/TelecomCloudDbContext.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/TelecomCloudDbContext.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Service/WechatService.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/WechatService.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Service/WechatService.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/WechatService.cs diff --git a/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/WorkhourTemplateExportService.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/WorkhourTemplateExportService.cs new file mode 100644 index 0000000..157793b --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Service/WorkhourTemplateExportService.cs @@ -0,0 +1,1524 @@ +using NPOI.SS.UserModel; +using NPOI.SS.Util; +using NPOI.XSSF.UserModel; +using System.Globalization; + +namespace SK_ERP_WebService.Service +{ + /// + /// 按工时分类、工序字段和填报记录生成统计工作簿,不读取外部 Excel 模板。 + /// + public sealed class WorkhourTemplateExportService + { + #region 导出入口与工作表结构 + + private static readonly string[] NormalBoardProcesses = ["贴片", "锡检", "插补", "加工"]; + private static readonly string[] NormalDebugProcesses = ["烧写程序", "打二维码", "调试", "刷三防漆"]; + private static readonly string[] NormalWholeMachineProcesses = ["整机调试", "整机总装", "包装"]; + private static readonly string[] NormalBoardOrder = ["主板", "单板", "小板", "按键板", "显示板", "模块小板", "灯板", "电源板", "计数模块小板", "转接板", "通讯板", "采集板", "面板"]; + private static readonly string[] AbnormalGroups = ["基板", "调试", "总装", "包装"]; + private static readonly string[] AbnormalProcesses = ["程序升级", "硬件升级", "其他"]; + + public WorkhourTemplateExportService() + { + } + + /// + /// 生成正常工时工作簿,并按所选月份和板块填入记录。 + /// + public byte[] ExportNormal(IReadOnlyCollection selectedMonths, IReadOnlyCollection selectedSegments, IReadOnlyCollection records) + { + selectedSegments = selectedSegments.Distinct(StringComparer.Ordinal).ToArray(); + var allYearRecords = records + .Where(record => record.DictType == "正常工时") + .ToList(); + var selectedMonthSet = selectedMonths.ToHashSet(); + var selectedRecords = allYearRecords + .Where(record => TryReadMonth(record.MfgMonth, out var month) && selectedMonthSet.Contains(month)) + .ToList(); + + var workbook = new XSSFWorkbook(); + var summarySheet = CreateNormalSummarySheet(workbook); + var monthSheet = CreateNormalMonthSheet(workbook); + var detailSheets = new[] { "基板", "调试", "总装", "包装" } + .Select(name => (Name: name, Sheet: CreateNormalDetailSheet(workbook, name))) + .ToList(); + + // 行结构来自工时分类和工序字段;年份只决定数据范围,不决定工作簿模板。 + FillNormalSummary(summarySheet, selectedRecords, allYearRecords); + FillNormalMonthSheet(monthSheet, selectedRecords, allYearRecords, selectedMonths); + foreach (var (name, sheet) in detailSheets) + { + FillNormalDetailSheet(sheet, selectedRecords, selectedMonths, name); + } + MergeNormalKeyCells(summarySheet, 1, FindNormalTotalRow(summarySheet)); + MergeNormalKeyCells(monthSheet, 2, FindMonthTotalRow(monthSheet)); + + if (selectedSegments.Count > 1) + { + var summaryBlocks = AppendSegmentBlocks(summarySheet, 1, FindNormalTotalRow(summarySheet), selectedSegments.Count); + var monthBlocks = AppendSegmentBlocks(monthSheet, 2, FindMonthTotalRow(monthSheet), selectedSegments.Count); + var detailBlocks = detailSheets.ToDictionary( + item => item.Name, + item => AppendSegmentBlocks(item.Sheet, 1, item.Sheet.LastRowNum, selectedSegments.Count)); + + for (var index = 0; index < selectedSegments.Count; index++) + { + var segment = selectedSegments.ElementAt(index); + var segmentRecords = selectedRecords.Where(record => record.BusinessSegment == segment).ToList(); + FillNormalSummaryRange(summarySheet, segmentRecords, summaryBlocks[index]); + FillNormalMonthSheetRange(monthSheet, segmentRecords, selectedMonths, monthBlocks[index]); + foreach (var (name, sheet) in detailSheets) + { + FillNormalDetailSheetRange(sheet, segmentRecords, selectedMonths, name, detailBlocks[name][index]); + } + } + + ApplyNormalTotalStyles(workbook, summarySheet, monthSheet); + AddSegmentColumn(workbook, summarySheet, summaryBlocks, headerRows: 1, selectedSegments); + AddSegmentColumn(workbook, monthSheet, monthBlocks, headerRows: 2, selectedSegments); + foreach (var (name, sheet) in detailSheets) + { + AddSegmentColumn(workbook, sheet, detailBlocks[name], headerRows: 1, selectedSegments); + } + } + else + { + ApplyNormalTotalStyles(workbook, summarySheet, monthSheet); + } + + return WriteWorkbook(workbook); + } + + /// + /// 生成非正常工时工作簿,并按所选月份和板块填入记录。 + /// + public byte[] ExportAbnormal(IReadOnlyCollection selectedMonths, IReadOnlyCollection selectedSegments, IReadOnlyCollection records) + { + selectedSegments = selectedSegments.Distinct(StringComparer.Ordinal).ToArray(); + var allYearRecords = records + .Where(record => record.DictType == "非正常工时") + .ToList(); + var workbook = new XSSFWorkbook(); + var summarySheet = CreateAbnormalSummarySheet(workbook); + var detailSheets = new[] { "基板", "调试", "总装", "包装" } + .Select(name => (Name: name, Sheet: CreateAbnormalDetailSheet(workbook, name))) + .ToList(); + + FillAbnormalSummary(summarySheet, allYearRecords, selectedMonths); + foreach (var groupName in new[] { "基板", "调试", "总装", "包装" }) + { + FillAbnormalDetailSheet(workbook.GetSheet(groupName), allYearRecords, selectedMonths, groupName); + } + + if (selectedSegments.Count > 1) + { + var summaryBlocks = AppendSegmentBlocks(summarySheet, 1, summarySheet.LastRowNum, selectedSegments.Count); + var detailBlocks = detailSheets.ToDictionary( + item => item.Name, + item => AppendSegmentBlocks(item.Sheet, 2, item.Sheet.LastRowNum, selectedSegments.Count)); + + for (var index = 0; index < selectedSegments.Count; index++) + { + var segment = selectedSegments.ElementAt(index); + var segmentRecords = allYearRecords.Where(record => record.BusinessSegment == segment).ToList(); + FillAbnormalSummaryRange(summarySheet, segmentRecords, selectedMonths, summaryBlocks[index], segment); + foreach (var (name, sheet) in detailSheets) + { + FillAbnormalDetailSheetRange(sheet, segmentRecords, selectedMonths, name, detailBlocks[name][index]); + } + } + + ApplyAbnormalTotalStyles(workbook, summarySheet, detailSheets); + AddSegmentColumn(workbook, summarySheet, summaryBlocks, headerRows: 1, selectedSegments); + foreach (var (name, sheet) in detailSheets) + { + AddSegmentColumn(workbook, sheet, detailBlocks[name], headerRows: 2, selectedSegments); + } + } + else + { + ApplyAbnormalTotalStyles(workbook, summarySheet, detailSheets); + } + + return WriteWorkbook(workbook); + } + + public static int AvailableMonthCount(int year) + { + return year is >= 1900 and <= 9999 ? 12 : 0; + } + + private static ISheet CreateNormalSummarySheet(IWorkbook workbook) + { + var sheet = workbook.CreateSheet("总表"); + var styles = CreateWorkbookStyles(workbook); + var headers = new[] { "产品", "板件", "大类", "工序", "数量", "工时(分钟)", "工时(小时)" }; + var header = sheet.CreateRow(0); + CreateStyledRow(header, headers.Length, styles.Body); + for (var column = 0; column < headers.Length; column++) + { + SetText(header, column, headers[column]); + header.GetCell(column).CellStyle = styles.Header; + } + + var total = sheet.CreateRow(1); + CreateStyledRow(total, headers.Length, styles.Body); + SetText(total, 0, "全厂合计"); + sheet.SetColumnWidth(0, 34 * 256); + sheet.SetColumnWidth(1, 16 * 256); + sheet.SetColumnWidth(2, 12 * 256); + sheet.SetColumnWidth(3, 16 * 256); + sheet.SetColumnWidth(4, 12 * 256); + sheet.SetColumnWidth(5, 16 * 256); + sheet.SetColumnWidth(6, 14 * 256); + sheet.CreateFreezePane(4, 1); + sheet.DisplayGridlines = false; + return sheet; + } + + private static ISheet CreateNormalMonthSheet(IWorkbook workbook) + { + var sheet = workbook.CreateSheet("总月份"); + var styles = CreateWorkbookStyles(workbook); + const int firstMonthColumn = 5; + const int monthColumnStride = 3; + const int monthCount = 12; + var totalStart = firstMonthColumn + monthCount * monthColumnStride; + var lastColumn = totalStart + 2; + var top = sheet.CreateRow(0); + var subHeader = sheet.CreateRow(1); + CreateStyledRow(top, lastColumn + 1, styles.Body); + CreateStyledRow(subHeader, lastColumn + 1, styles.Body); + + var baseHeaders = new[] { "产品", "板件", "大类", "工序" }; + for (var column = 0; column < baseHeaders.Length; column++) + { + SetText(top, column, baseHeaders[column]); + top.GetCell(column).CellStyle = styles.Header; + subHeader.GetCell(column).CellStyle = styles.Header; + sheet.AddMergedRegion(new CellRangeAddress(0, 1, column, column)); + } + top.GetCell(4).CellStyle = styles.Header; + subHeader.GetCell(4).CellStyle = styles.Header; + + for (var month = 1; month <= monthCount; month++) + { + var start = firstMonthColumn + (month - 1) * monthColumnStride; + SetText(top, start, $"{month}月"); + top.GetCell(start).CellStyle = styles.Header; + top.GetCell(start + 1).CellStyle = styles.Header; + top.GetCell(start + 2).CellStyle = styles.Header; + sheet.AddMergedRegion(new CellRangeAddress(0, 0, start, start + 1)); + SetText(subHeader, start, "数量"); + SetText(subHeader, start + 1, "工时(分)"); + subHeader.GetCell(start).CellStyle = styles.Header; + subHeader.GetCell(start + 1).CellStyle = styles.Header; + subHeader.GetCell(start + 2).CellStyle = styles.Header; + } + + SetText(top, totalStart, "合计"); + for (var column = totalStart; column <= lastColumn; column++) + { + top.GetCell(column).CellStyle = styles.Header; + subHeader.GetCell(column).CellStyle = styles.Header; + } + sheet.AddMergedRegion(new CellRangeAddress(0, 0, totalStart, lastColumn)); + SetText(subHeader, totalStart, "数量"); + SetText(subHeader, totalStart + 1, "工时(分)"); + SetText(subHeader, totalStart + 2, "工时(时)"); + + var total = sheet.CreateRow(2); + CreateStyledRow(total, lastColumn + 1, styles.Body); + SetText(total, 0, "合计"); + sheet.SetColumnWidth(0, 34 * 256); + sheet.SetColumnWidth(1, 16 * 256); + sheet.SetColumnWidth(2, 12 * 256); + sheet.SetColumnWidth(3, 16 * 256); + sheet.SetColumnWidth(4, 3 * 256); + for (var month = 1; month <= monthCount; month++) + { + var start = firstMonthColumn + (month - 1) * monthColumnStride; + sheet.SetColumnWidth(start, 11 * 256); + sheet.SetColumnWidth(start + 1, 13 * 256); + sheet.SetColumnWidth(start + 2, 3 * 256); + } + sheet.SetColumnWidth(totalStart, 11 * 256); + sheet.SetColumnWidth(totalStart + 1, 13 * 256); + sheet.SetColumnWidth(totalStart + 2, 12 * 256); + sheet.CreateFreezePane(4, 2); + sheet.DisplayGridlines = false; + return sheet; + } + + private static ISheet CreateNormalDetailSheet(IWorkbook workbook, string sheetName) + { + var sheet = workbook.CreateSheet(sheetName); + var styles = CreateWorkbookStyles(workbook); + var headers = new[] { "月份", "产品", "板件", "工序", "数量", "工时(分钟)" }; + var header = sheet.CreateRow(0); + CreateStyledRow(header, headers.Length, styles.Body); + for (var column = 0; column < headers.Length; column++) + { + SetText(header, column, headers[column]); + header.GetCell(column).CellStyle = styles.Header; + } + var firstDataRow = sheet.CreateRow(1); + CreateStyledRow(firstDataRow, headers.Length, styles.Body); + sheet.SetColumnWidth(0, 10 * 256); + sheet.SetColumnWidth(1, 38 * 256); + sheet.SetColumnWidth(2, 16 * 256); + sheet.SetColumnWidth(3, 18 * 256); + sheet.SetColumnWidth(4, 12 * 256); + sheet.SetColumnWidth(5, 16 * 256); + sheet.CreateFreezePane(2, 1); + sheet.DisplayGridlines = false; + return sheet; + } + + private static ISheet CreateAbnormalSummarySheet(IWorkbook workbook) + { + var sheet = workbook.CreateSheet("汇总表"); + var styles = CreateWorkbookStyles(workbook); + var header = sheet.CreateRow(0); + const int firstMonthColumn = 2; + const int monthCount = 12; + var totalStart = firstMonthColumn + monthCount; + var columnCount = totalStart + 3; + CreateStyledRow(header, columnCount, styles.Body); + SetText(header, 0, "组别"); + SetText(header, 1, "工序"); + header.GetCell(0).CellStyle = styles.Header; + header.GetCell(1).CellStyle = styles.Header; + for (var month = 1; month <= monthCount; month++) + { + SetText(header, firstMonthColumn + month - 1, $"{month}月"); + header.GetCell(firstMonthColumn + month - 1).CellStyle = styles.Header; + } + SetText(header, totalStart, "合计(分钟)"); + SetText(header, totalStart + 1, "合计(小时)"); + SetText(header, totalStart + 2, "数量合计"); + for (var column = totalStart; column < columnCount; column++) header.GetCell(column).CellStyle = styles.Header; + + var rowIndex = 1; + foreach (var group in AbnormalGroups) + { + var groupStart = rowIndex; + foreach (var process in AbnormalProcesses) + { + var row = sheet.CreateRow(rowIndex++); + CreateStyledRow(row, columnCount, styles.Body); + if (process == AbnormalProcesses[0]) SetText(row, 0, group); + SetText(row, 1, process); + } + sheet.AddMergedRegion(new CellRangeAddress(groupStart, rowIndex - 1, 0, 0)); + } + + var total = sheet.CreateRow(rowIndex); + CreateStyledRow(total, columnCount, styles.Body); + SetText(total, 0, "所选板块合计"); + SetText(total, 1, "全部工序"); + sheet.SetColumnWidth(0, 14 * 256); + sheet.SetColumnWidth(1, 18 * 256); + for (var column = firstMonthColumn; column < totalStart; column++) sheet.SetColumnWidth(column, 12 * 256); + sheet.SetColumnWidth(totalStart, 16 * 256); + sheet.SetColumnWidth(totalStart + 1, 14 * 256); + sheet.SetColumnWidth(totalStart + 2, 14 * 256); + sheet.CreateFreezePane(2, 1); + sheet.DisplayGridlines = false; + return sheet; + } + + private static ISheet CreateAbnormalDetailSheet(IWorkbook workbook, string groupName) + { + var sheet = workbook.CreateSheet(groupName); + var styles = CreateWorkbookStyles(workbook); + const int firstMonthColumn = 4; + const int monthCount = 12; + const int monthColumnStride = 3; + var totalStart = firstMonthColumn + monthCount * monthColumnStride; + var lastColumn = totalStart + 2; + var header = sheet.CreateRow(0); + var subHeader = sheet.CreateRow(1); + CreateStyledRow(header, lastColumn + 1, styles.Body); + CreateStyledRow(subHeader, lastColumn + 1, styles.Body); + var leftHeaders = new[] { "工序", "型号", "备注" }; + for (var column = 0; column < leftHeaders.Length; column++) + { + SetText(header, column, leftHeaders[column]); + header.GetCell(column).CellStyle = styles.Header; + subHeader.GetCell(column).CellStyle = styles.Header; + sheet.AddMergedRegion(new CellRangeAddress(0, 1, column, column)); + } + header.GetCell(3).CellStyle = styles.Header; + subHeader.GetCell(3).CellStyle = styles.Header; + + for (var month = 1; month <= monthCount; month++) + { + var start = firstMonthColumn + (month - 1) * monthColumnStride; + SetText(header, start, $"{month}月"); + header.GetCell(start).CellStyle = styles.Header; + header.GetCell(start + 1).CellStyle = styles.Header; + header.GetCell(start + 2).CellStyle = styles.Header; + sheet.AddMergedRegion(new CellRangeAddress(0, 0, start, start + 1)); + SetText(subHeader, start, "数量"); + SetText(subHeader, start + 1, "工时(分)"); + subHeader.GetCell(start).CellStyle = styles.Header; + subHeader.GetCell(start + 1).CellStyle = styles.Header; + subHeader.GetCell(start + 2).CellStyle = styles.Header; + } + SetText(header, totalStart, "合计"); + for (var column = totalStart; column <= lastColumn; column++) + { + header.GetCell(column).CellStyle = styles.Header; + subHeader.GetCell(column).CellStyle = styles.Header; + } + sheet.AddMergedRegion(new CellRangeAddress(0, 0, totalStart, lastColumn)); + SetText(subHeader, totalStart, "数量"); + SetText(subHeader, totalStart + 1, "工时(分)"); + SetText(subHeader, totalStart + 2, "工时(时)"); + + var total = sheet.CreateRow(2); + CreateStyledRow(total, lastColumn + 1, styles.Body); + SetText(total, 0, "合计"); + sheet.SetColumnWidth(0, 18 * 256); + sheet.SetColumnWidth(1, 34 * 256); + sheet.SetColumnWidth(2, 38 * 256); + sheet.SetColumnWidth(3, 3 * 256); + for (var month = 1; month <= monthCount; month++) + { + var start = firstMonthColumn + (month - 1) * monthColumnStride; + sheet.SetColumnWidth(start, 11 * 256); + sheet.SetColumnWidth(start + 1, 13 * 256); + sheet.SetColumnWidth(start + 2, 3 * 256); + } + sheet.SetColumnWidth(totalStart, 11 * 256); + sheet.SetColumnWidth(totalStart + 1, 13 * 256); + sheet.SetColumnWidth(totalStart + 2, 12 * 256); + sheet.CreateFreezePane(3, 2); + sheet.DisplayGridlines = false; + return sheet; + } + + #endregion + + #region 单元格样式与工作簿输出 + + private static WorkbookStyles CreateWorkbookStyles(IWorkbook workbook) + { + var headerFont = workbook.CreateFont(); + headerFont.FontName = "宋体"; + headerFont.FontHeightInPoints = 10; + headerFont.IsBold = true; + + var bodyFont = workbook.CreateFont(); + bodyFont.FontName = "宋体"; + bodyFont.FontHeightInPoints = 10; + + var header = workbook.CreateCellStyle(); + header.SetFont(headerFont); + header.FillForegroundColor = IndexedColors.Grey25Percent.Index; + header.FillPattern = FillPattern.SolidForeground; + header.Alignment = HorizontalAlignment.Center; + header.VerticalAlignment = VerticalAlignment.Center; + header.WrapText = true; + SetThinBorders(header); + + var body = workbook.CreateCellStyle(); + body.SetFont(bodyFont); + body.VerticalAlignment = VerticalAlignment.Center; + SetThinBorders(body); + + var total = workbook.CreateCellStyle(); + total.CloneStyleFrom(body); + var totalFont = workbook.CreateFont(); + totalFont.FontName = "宋体"; + totalFont.FontHeightInPoints = 10; + totalFont.IsBold = true; + total.SetFont(totalFont); + total.FillForegroundColor = IndexedColors.Grey25Percent.Index; + total.FillPattern = FillPattern.SolidForeground; + total.BorderTop = BorderStyle.Medium; + + return new WorkbookStyles(header, body, total); + } + + private static void SetThinBorders(ICellStyle style) + { + style.BorderTop = BorderStyle.Thin; + style.BorderBottom = BorderStyle.Thin; + style.BorderLeft = BorderStyle.Thin; + style.BorderRight = BorderStyle.Thin; + style.TopBorderColor = IndexedColors.Grey50Percent.Index; + style.BottomBorderColor = IndexedColors.Grey50Percent.Index; + style.LeftBorderColor = IndexedColors.Grey50Percent.Index; + style.RightBorderColor = IndexedColors.Grey50Percent.Index; + } + + private static void CreateStyledRow(IRow row, int columnCount, ICellStyle style) + { + for (var column = 0; column < columnCount; column++) row.CreateCell(column).CellStyle = style; + } + + private static void MergeNormalKeyCells(ISheet sheet, int firstDataRow, int totalRow) + { + if (totalRow <= firstDataRow) return; + MergeEqualRuns(sheet, firstDataRow, totalRow - 1, 0, row => ReadText(row.GetCell(0))); + MergeEqualRuns(sheet, firstDataRow, totalRow - 1, 1, row => $"{ReadText(row.GetCell(0))}\u001f{ReadText(row.GetCell(1))}"); + MergeEqualRuns(sheet, firstDataRow, totalRow - 1, 2, row => $"{ReadText(row.GetCell(0))}\u001f{ReadText(row.GetCell(1))}\u001f{ReadText(row.GetCell(2))}"); + } + + private static void MergeEqualRuns(ISheet sheet, int firstRow, int lastRow, int column, Func keySelector) + { + var runStart = firstRow; + var currentKey = sheet.GetRow(firstRow) is IRow first ? keySelector(first) : string.Empty; + for (var rowIndex = firstRow + 1; rowIndex <= lastRow; rowIndex++) + { + var row = sheet.GetRow(rowIndex); + var nextKey = row == null ? string.Empty : keySelector(row); + if (string.Equals(nextKey, currentKey, StringComparison.Ordinal)) continue; + MergeRun(sheet, runStart, rowIndex - 1, column); + runStart = rowIndex; + currentKey = nextKey; + } + MergeRun(sheet, runStart, lastRow, column); + } + + private static void MergeRun(ISheet sheet, int firstRow, int lastRow, int column) + { + if (lastRow <= firstRow) return; + for (var rowIndex = firstRow + 1; rowIndex <= lastRow; rowIndex++) ClearCell(sheet.GetRow(rowIndex)!, column); + sheet.AddMergedRegion(new CellRangeAddress(firstRow, lastRow, column, column)); + } + + private static void ApplyNormalTotalStyles(IWorkbook workbook, ISheet summarySheet, ISheet monthSheet) + { + ApplyMarkedTotalStyles(workbook, summarySheet, row => ReadText(row.GetCell(0)) == "全厂合计"); + ApplyMarkedTotalStyles(workbook, monthSheet, row => ReadText(row.GetCell(0)) == "合计"); + } + + private static void ApplyAbnormalTotalStyles(IWorkbook workbook, ISheet summarySheet, IReadOnlyCollection<(string Name, ISheet Sheet)> detailSheets) + { + ApplyMarkedTotalStyles(workbook, summarySheet, row => ReadText(row.GetCell(1)) == "全部工序"); + foreach (var (_, sheet) in detailSheets) + { + ApplyMarkedTotalStyles(workbook, sheet, row => ReadText(row.GetCell(0)) == "合计"); + } + } + + private static void ApplyMarkedTotalStyles(IWorkbook workbook, ISheet sheet, Func predicate) + { + var style = CreateWorkbookStyles(workbook).Total; + for (var rowIndex = 0; rowIndex <= sheet.LastRowNum; rowIndex++) + { + var row = sheet.GetRow(rowIndex); + if (row == null || !predicate(row)) continue; + for (var column = 0; column < row.LastCellNum; column++) + { + var cell = row.GetCell(column); + if (cell != null) cell.CellStyle = style; + } + } + } + + private sealed record WorkbookStyles(ICellStyle Header, ICellStyle Body, ICellStyle Total); + + private static byte[] WriteWorkbook(IWorkbook workbook) + { + using var output = new MemoryStream(); + workbook.Write(output); + return output.ToArray(); + } + + #endregion + + #region 数据汇总与工作表填充 + + private static Dictionary BuildNormalAggregates(IEnumerable records) + { + var result = new Dictionary(); + foreach (var record in records) + { + if (record.DictType != "正常工时" || !TryReadMonth(record.MfgMonth, out var month)) continue; + var key = ToNormalKey(record); + if (!result.TryGetValue(key, out var bucket)) result[key] = bucket = new MonthBucket(); + bucket.Add(month, record.Qty, record.Minutes); + } + return result; + } + + private static HashSet BuildNormalTemplateKeys(IEnumerable records) + { + var keys = new HashSet(); + foreach (var productRecords in records + .Where(record => record.DictType == "正常工时" && !string.IsNullOrWhiteSpace(record.ProductName)) + .GroupBy(record => record.ProductName!.Trim(), StringComparer.OrdinalIgnoreCase)) + { + var product = productRecords.Key; + var boards = productRecords + .Select(ToNormalKey) + .Where(key => key.Stage is "基板" or "调试") + .Select(key => key.Board) + .Where(board => !string.IsNullOrWhiteSpace(board) && board != "整机") + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(GetBoardOrder) + .ThenBy(board => board, StringComparer.OrdinalIgnoreCase); + + foreach (var board in boards) + { + foreach (var process in NormalBoardProcesses) keys.Add(new NormalKey(product, board, "基板", process)); + foreach (var process in NormalDebugProcesses) keys.Add(new NormalKey(product, board, "调试", process)); + } + + foreach (var process in NormalWholeMachineProcesses) keys.Add(new NormalKey(product, "整机", "整机", process)); + } + return keys; + } + + private static NormalKey ToNormalKey(WorkhourTemplateRecord record) + { + var process = record.ProcessName?.Trim() ?? string.Empty; + var category = record.Category?.Trim() ?? string.Empty; + var product = record.ProductName?.Trim() ?? string.Empty; + var machineProcess = NormalWholeMachineProcesses.Contains(process, StringComparer.Ordinal) + ? process + : NormalWholeMachineProcesses.Contains(category, StringComparer.Ordinal) ? category : string.Empty; + if (!string.IsNullOrWhiteSpace(machineProcess) || category == "整机") + { + return new NormalKey(product, "整机", "整机", machineProcess); + } + var stage = category switch + { + "基板" => "基板", + "调试" => "调试", + _ when NormalBoardProcesses.Contains(process, StringComparer.Ordinal) => "基板", + _ when NormalDebugProcesses.Contains(process, StringComparer.Ordinal) => "调试", + _ => category, + }; + return new NormalKey(product, GetNormalBoard(record), stage, process); + } + + private static IOrderedEnumerable OrderNormalKeys(IEnumerable keys) + { + return keys + .OrderBy(key => key.Product, StringComparer.OrdinalIgnoreCase) + .ThenBy(key => GetBoardOrder(key.Board)) + .ThenBy(key => key.Board, StringComparer.OrdinalIgnoreCase) + .ThenBy(key => key.Stage switch { "基板" => 0, "调试" => 1, "整机" => 2, _ => 3 }) + .ThenBy(key => GetProcessOrder(key.Stage, key.Process)) + .ThenBy(key => key.Process, StringComparer.OrdinalIgnoreCase); + } + + private static int GetBoardOrder(string board) + { + var index = Array.IndexOf(NormalBoardOrder, board); + return index >= 0 ? index : board == "整机" ? NormalBoardOrder.Length : NormalBoardOrder.Length + 1; + } + + private static int GetProcessOrder(string stage, string process) + { + var processes = stage switch + { + "基板" => NormalBoardProcesses, + "调试" => NormalDebugProcesses, + "整机" => NormalWholeMachineProcesses, + _ => Array.Empty(), + }; + var index = Array.IndexOf(processes, process); + return index >= 0 ? index : processes.Length; + } + + private static void FillNormalSummary( + ISheet sheet, + IReadOnlyCollection records, + IReadOnlyCollection structureRecords) + { + if (sheet == null) return; + var aggregates = BuildNormalAggregates(records); + var requiredKeys = BuildNormalTemplateKeys(structureRecords); + requiredKeys.UnionWith(aggregates.Keys); + var keys = GetNormalSummaryKeys(sheet); + foreach (var key in OrderNormalKeys(requiredKeys.Where(key => !keys.Contains(key)))) + { + var row = InsertBeforeTotal(sheet, FindNormalTotalRow(sheet), CopyStyleFromLastDataRow(sheet)); + WriteNormalKey(row, key); + keys.Add(key); + } + + FillNormalSummaryRange(sheet, records, new SegmentBlock(1, FindNormalTotalRow(sheet))); + } + + private static void FillNormalSummaryRange(ISheet sheet, IReadOnlyCollection records, SegmentBlock block) + { + var aggregates = BuildNormalAggregates(records); + var totalQty = aggregates.Values.Sum(bucket => bucket.TotalQty); + var totalMinutes = aggregates.Values.Sum(bucket => bucket.TotalMinutes); + for (var i = block.StartRow; i <= block.EndRow; i++) + { + var row = sheet.GetRow(i); + if (row == null) continue; + var first = ReadText(row.GetCell(0)); + if (first == "全厂合计") + { + ClearCells(row, 4, 6); + SetNumber(row, 4, totalQty); + SetNumber(row, 5, totalMinutes); + SetNumber(row, 6, Math.Round(totalMinutes / 60d, 2)); + continue; + } + ClearCells(row, 4, 6); + if (TryReadNormalKey(sheet, row, out var key) && aggregates.TryGetValue(key, out var bucket)) + { + SetOptionalNumber(row, 4, bucket.TotalQty); + SetOptionalNumber(row, 5, bucket.TotalMinutes); + SetOptionalNumber(row, 6, Math.Round(bucket.TotalMinutes / 60d, 2)); + } + } + } + + private static void FillNormalMonthSheet( + ISheet sheet, + IReadOnlyCollection records, + IReadOnlyCollection structureRecords, + IReadOnlyCollection selectedMonths) + { + if (sheet == null) return; + var aggregates = BuildNormalAggregates(records); + var requiredKeys = BuildNormalTemplateKeys(structureRecords); + requiredKeys.UnionWith(aggregates.Keys); + var keys = GetNormalMonthKeys(sheet); + foreach (var key in OrderNormalKeys(requiredKeys.Where(key => !keys.Contains(key)))) + { + var row = InsertBeforeMonthTotal(sheet, CopyStyleFromLastDataRow(sheet)); + WriteNormalKey(row, key); + keys.Add(key); + } + + FillNormalMonthSheetRange(sheet, records, selectedMonths, new SegmentBlock(2, FindMonthTotalRow(sheet))); + } + + private static void FillNormalMonthSheetRange(ISheet sheet, IReadOnlyCollection records, IReadOnlyCollection selectedMonths, SegmentBlock block) + { + var aggregates = BuildNormalAggregates(records); + var monthColumns = ReadMonthColumns(sheet, 0, 5); + var totalStart = monthColumns.Count == 0 ? 5 : monthColumns.Values.Max() + 3; + var totalRowIndex = -1; + for (var rowIndex = block.StartRow; rowIndex <= block.EndRow; rowIndex++) + { + if (ReadText(sheet.GetRow(rowIndex)?.GetCell(0)) == "合计") + { + totalRowIndex = rowIndex; + break; + } + } + + for (var rowIndex = block.StartRow; rowIndex <= block.EndRow; rowIndex++) + { + var row = sheet.GetRow(rowIndex); + if (row == null) continue; + var lastColumn = sheet.GetRow(0)?.LastCellNum ?? 0; + for (var i = 5; i < lastColumn; i++) ClearCell(row, i); + if (rowIndex == totalRowIndex) continue; + if (!TryReadNormalKey(sheet, row, out var key) || !aggregates.TryGetValue(key, out var bucket)) continue; + foreach (var month in selectedMonths) + { + if (!monthColumns.TryGetValue(month, out var start)) continue; + var value = bucket.Get(month); + if (value == null) continue; + SetOptionalNumber(row, start, value.Qty); + SetOptionalNumber(row, start + 1, value.Minutes); + } + SetOptionalNumber(row, totalStart, bucket.TotalQty); + SetOptionalNumber(row, totalStart + 1, bucket.TotalMinutes); + SetOptionalNumber(row, totalStart + 2, Math.Round(bucket.TotalMinutes / 60d, 2)); + } + + if (totalRowIndex >= 0 && sheet.GetRow(totalRowIndex) is IRow totalRow) + { + foreach (var month in selectedMonths) + { + if (!monthColumns.TryGetValue(month, out var start)) continue; + var monthQty = aggregates.Values.Sum(bucket => bucket.Get(month)?.Qty ?? 0); + var monthMinutes = aggregates.Values.Sum(bucket => bucket.Get(month)?.Minutes ?? 0); + SetNumber(totalRow, start, monthQty); + SetNumber(totalRow, start + 1, monthMinutes); + } + var qty = aggregates.Values.Sum(bucket => bucket.TotalQty); + var minutes = aggregates.Values.Sum(bucket => bucket.TotalMinutes); + SetNumber(totalRow, totalStart, qty); + SetNumber(totalRow, totalStart + 1, minutes); + SetNumber(totalRow, totalStart + 2, Math.Round(minutes / 60d, 2)); + } + } + + private static void FillNormalDetailSheet(ISheet sheet, IReadOnlyCollection records, IReadOnlyCollection selectedMonths, string sheetName) + { + if (sheet == null) return; + var data = BuildNormalDetailAggregates(records, sheetName); + var existing = new HashSet(); + for (var i = 1; i <= sheet.LastRowNum; i++) + { + var row = sheet.GetRow(i); + if (row == null || !int.TryParse(ReadText(row.GetCell(0)), out var month)) continue; + existing.Add(new NormalDetailKey(month, ReadText(row.GetCell(1)), ReadText(row.GetCell(2)), ReadText(row.GetCell(3)))); + } + var nextRowIndex = 1; + foreach (var item in data.Where(item => selectedMonths.Contains(item.Key.Month) && !existing.Contains(item.Key)) + .OrderBy(item => item.Key.Month).ThenBy(item => item.Key.Product).ThenBy(item => item.Key.Process)) + { + var row = sheet.GetRow(nextRowIndex); + if (row == null || Enumerable.Range(0, 4).Any(column => !string.IsNullOrWhiteSpace(ReadText(row.GetCell(column))))) + { + row = AppendRow(sheet, CopyStyleFromLastDataRow(sheet)); + nextRowIndex = row.RowNum; + } + SetNumber(row, 0, item.Key.Month); + SetText(row, 1, item.Key.Product); + SetText(row, 2, item.Key.Board); + SetText(row, 3, item.Key.Process); + existing.Add(item.Key); + nextRowIndex++; + } + + FillNormalDetailSheetRange(sheet, records, selectedMonths, sheetName, new SegmentBlock(1, sheet.LastRowNum)); + } + + private static void FillNormalDetailSheetRange(ISheet sheet, IReadOnlyCollection records, IReadOnlyCollection selectedMonths, string sheetName, SegmentBlock block) + { + var data = BuildNormalDetailAggregates(records, sheetName); + for (var i = block.StartRow; i <= block.EndRow; i++) + { + var row = sheet.GetRow(i); + if (row == null || !int.TryParse(ReadText(row.GetCell(0)), out var month)) continue; + var key = new NormalDetailKey(month, ReadText(row.GetCell(1)), ReadText(row.GetCell(2)), ReadText(row.GetCell(3))); + ClearCells(row, 4, 5); + if (selectedMonths.Contains(month) && data.TryGetValue(key, out var value)) + { + SetOptionalNumber(row, 4, value.Qty); + SetOptionalNumber(row, 5, value.Minutes); + } + } + } + + private static Dictionary BuildNormalDetailAggregates(IEnumerable records, string sheetName) + { + var data = new Dictionary(); + foreach (var record in records.Where(record => record.DictType == "正常工时" && GetNormalDetailSheet(record) == sheetName)) + { + if (!TryReadMonth(record.MfgMonth, out var month)) continue; + var normalKey = ToNormalKey(record); + var key = new NormalDetailKey(month, normalKey.Product, normalKey.Board, normalKey.Process); + if (!data.TryGetValue(key, out var value)) data[key] = value = new MonthValue(); + value.Add(record.Qty, record.Minutes); + } + return data; + } + + private static void FillAbnormalSummary(ISheet sheet, IReadOnlyCollection records, IReadOnlyCollection selectedMonths) + { + if (sheet == null) return; + var monthColumns = ReadMonthColumns(sheet, 0, 2); + var aggregates = BuildAbnormalGroupAggregates(records, selectedMonths); + var dataStart = 1; + var totalRowIndex = sheet.LastRowNum; + var group = string.Empty; + var existing = new HashSet<(string Group, string Process)>(); + for (var i = dataStart; i <= totalRowIndex; i++) + { + var row = sheet.GetRow(i); + if (row == null) continue; + var first = ReadText(row.GetCell(0)); + var process = ReadText(row.GetCell(1)); + if (first.EndsWith("合计", StringComparison.Ordinal) || process == "全部工序") + { + totalRowIndex = i; + ClearCells(row, 2, row.LastCellNum - 1); + continue; + } + if (!string.IsNullOrWhiteSpace(first)) group = first; + if (string.IsNullOrWhiteSpace(process)) continue; + existing.Add((group, process)); + ClearCells(row, 2, row.LastCellNum - 1); + if (!aggregates.TryGetValue((group, process), out var bucket)) continue; + WriteAbnormalSummaryRow(row, bucket, monthColumns, selectedMonths, 2); + } + + foreach (var entry in aggregates.Where(entry => (entry.Key.Group is "基板" or "调试" or "总装" or "包装") && !existing.Contains(entry.Key))) + { + var row = InsertBeforeRow(sheet, totalRowIndex, CopyStyleFromLastDataRow(sheet)); + SetText(row, 0, entry.Key.Group); + SetText(row, 1, entry.Key.Process); + WriteAbnormalSummaryRow(row, entry.Value, monthColumns, selectedMonths, 2); + existing.Add(entry.Key); + totalRowIndex++; + } + + FillAbnormalSummaryRange(sheet, records, selectedMonths, new SegmentBlock(dataStart, totalRowIndex), null); + } + + private static void FillAbnormalSummaryRange( + ISheet sheet, + IReadOnlyCollection records, + IReadOnlyCollection selectedMonths, + SegmentBlock block, + string? segmentLabel) + { + var monthColumns = ReadMonthColumns(sheet, 0, 2); + var aggregates = BuildAbnormalGroupAggregates(records, selectedMonths); + var group = string.Empty; + var totalRowIndex = -1; + for (var i = block.StartRow; i <= block.EndRow; i++) + { + var row = sheet.GetRow(i); + if (row == null) continue; + var first = ReadText(row.GetCell(0)); + var process = ReadText(row.GetCell(1)); + if (first.EndsWith("合计", StringComparison.Ordinal) || process == "全部工序") + { + totalRowIndex = i; + ClearCells(row, 2, row.LastCellNum - 1); + continue; + } + if (!string.IsNullOrWhiteSpace(first)) group = first; + if (string.IsNullOrWhiteSpace(process)) continue; + ClearCells(row, 2, row.LastCellNum - 1); + if (aggregates.TryGetValue((group, process), out var bucket)) + { + WriteAbnormalSummaryRow(row, bucket, monthColumns, selectedMonths, 2); + } + } + + if (totalRowIndex >= 0 && sheet.GetRow(totalRowIndex) is IRow totalRow) + { + var labels = records.Select(record => record.BusinessSegment) + .Where(value => !string.IsNullOrWhiteSpace(value)) + .Distinct(StringComparer.Ordinal) + .ToArray(); + var label = string.IsNullOrWhiteSpace(segmentLabel) + ? labels.Length == 1 ? labels[0] : "所选板块" + : segmentLabel; + SetText(totalRow, 0, string.IsNullOrWhiteSpace(label) ? "所选板块合计" : label + "合计"); + SetText(totalRow, 1, "全部工序"); + var totalBucket = MergeBuckets(aggregates.Values); + ClearCells(totalRow, 2, totalRow.LastCellNum - 1); + WriteAbnormalSummaryRow(totalRow, totalBucket, monthColumns, selectedMonths, 2); + } + } + + private static Dictionary<(string Group, string Process), MonthBucket> BuildAbnormalGroupAggregates(IEnumerable records, IReadOnlyCollection selectedMonths) + { + var result = new Dictionary<(string Group, string Process), MonthBucket>(); + foreach (var record in records.Where(record => record.DictType == "非正常工时")) + { + if (!TryReadMonth(record.MfgMonth, out var month) || !selectedMonths.Contains(month)) continue; + var group = record.GroupName ?? string.Empty; + if (group is not ("基板" or "调试" or "总装" or "包装")) continue; + var key = (group, record.ProcessName ?? string.Empty); + if (!result.TryGetValue(key, out var bucket)) result[key] = bucket = new MonthBucket(); + bucket.Add(month, record.Qty, record.Minutes); + } + return result; + } + + private static void WriteAbnormalSummaryRow(IRow row, MonthBucket bucket, IReadOnlyDictionary monthColumns, IReadOnlyCollection selectedMonths, int startColumn) + { + foreach (var month in selectedMonths) + { + if (monthColumns.TryGetValue(month, out var column) && bucket.Get(month) is MonthValue value) SetNumber(row, column, value.Minutes); + } + var totalColumn = monthColumns.Count == 0 ? startColumn : monthColumns.Values.Max() + 1; + SetNumber(row, totalColumn, bucket.TotalMinutes); + SetNumber(row, totalColumn + 1, Math.Round(bucket.TotalMinutes / 60d, 2)); + SetNumber(row, totalColumn + 2, bucket.TotalQty); + } + + private static void FillAbnormalDetailSheet(ISheet sheet, IReadOnlyCollection records, IReadOnlyCollection selectedMonths, string groupName) + { + if (sheet == null) return; + var aggregates = BuildAbnormalDetailAggregates(records, selectedMonths, groupName); + + var existing = new HashSet(); + var insertAt = sheet.LastRowNum + 1; + for (var i = 2; i <= sheet.LastRowNum; i++) + { + var row = sheet.GetRow(i); + if (row == null) continue; + var process = ReadText(row.GetCell(0)); + var product = ReadText(row.GetCell(1)); + if (process == "合计") + { + if (insertAt > i) insertAt = i; + continue; + } + if (product == "小计") + { + if (insertAt > i) insertAt = i; + continue; + } + if (string.IsNullOrWhiteSpace(process) && string.IsNullOrWhiteSpace(product)) continue; + var key = new AbnormalDetailKey(process, product, ReadText(row.GetCell(2))); + existing.Add(key); + } + + foreach (var item in aggregates.Where(item => !existing.Contains(item.Key)).OrderBy(item => item.Key.Process).ThenBy(item => item.Key.Product).ThenBy(item => item.Key.Remark)) + { + var sourceStyle = sheet.GetRow(Math.Max(2, insertAt - 1)) ?? sheet.GetRow(2); + var row = InsertBeforeRow(sheet, insertAt, sourceStyle); + SetText(row, 0, item.Key.Process); + SetText(row, 1, item.Key.Product); + SetText(row, 2, item.Key.Remark); + insertAt++; + } + + FillAbnormalDetailSheetRange(sheet, records, selectedMonths, groupName, new SegmentBlock(2, sheet.LastRowNum)); + } + + private static void FillAbnormalDetailSheetRange( + ISheet sheet, + IReadOnlyCollection records, + IReadOnlyCollection selectedMonths, + string groupName, + SegmentBlock block) + { + var monthColumns = ReadMonthColumns(sheet, 0, 4); + var totalStart = monthColumns.Count == 0 ? 4 : monthColumns.Values.Max() + 3; + var aggregates = BuildAbnormalDetailAggregates(records, selectedMonths, groupName); + for (var i = block.StartRow; i <= block.EndRow; i++) + { + var row = sheet.GetRow(i); + if (row == null) continue; + ClearCells(row, 4, row.LastCellNum - 1); + var label = ReadText(row.GetCell(1)); + if (label == "小计") + { + var processName = ReadText(row.GetCell(0)); + var subtotal = MergeBuckets(aggregates.Where(item => item.Key.Process == processName).Select(item => item.Value)); + ClearCells(row, 4, row.LastCellNum - 1); + WriteAbnormalDetailRow(row, subtotal, monthColumns, selectedMonths, totalStart); + } + else if (ReadText(row.GetCell(0)) == "合计") + { + var total = MergeBuckets(aggregates.Values); + ClearCells(row, 4, row.LastCellNum - 1); + WriteAbnormalDetailRow(row, total, monthColumns, selectedMonths, totalStart); + } + else + { + var key = new AbnormalDetailKey(ReadText(row.GetCell(0)), ReadText(row.GetCell(1)), ReadText(row.GetCell(2))); + if (aggregates.TryGetValue(key, out var bucket)) + { + WriteAbnormalDetailRow(row, bucket, monthColumns, selectedMonths, totalStart); + } + } + } + } + + private static Dictionary BuildAbnormalDetailAggregates( + IEnumerable records, + IReadOnlyCollection selectedMonths, + string groupName) + { + var aggregates = new Dictionary(); + foreach (var record in records.Where(record => record.DictType == "非正常工时" && record.GroupName == groupName)) + { + if (!TryReadMonth(record.MfgMonth, out var month) || !selectedMonths.Contains(month)) continue; + var key = new AbnormalDetailKey(record.ProcessName ?? string.Empty, record.ProductName ?? string.Empty, record.Remark ?? string.Empty); + if (!aggregates.TryGetValue(key, out var bucket)) aggregates[key] = bucket = new MonthBucket(); + bucket.Add(month, record.Qty, record.Minutes); + } + return aggregates; + } + + private static void WriteAbnormalDetailRow(IRow row, MonthBucket bucket, IReadOnlyDictionary monthColumns, IReadOnlyCollection selectedMonths, int totalStart) + { + foreach (var month in selectedMonths) + { + if (!monthColumns.TryGetValue(month, out var start)) continue; + var value = bucket.Get(month); + if (value == null) continue; + SetNumber(row, start, value.Qty); + SetNumber(row, start + 1, value.Minutes); + } + SetNumber(row, totalStart, bucket.TotalQty); + SetNumber(row, totalStart + 1, bucket.TotalMinutes); + SetNumber(row, totalStart + 2, Math.Round(bucket.TotalMinutes / 60d, 2)); + } + + #endregion + + #region 多板块行块与列布局 + + private static List AppendSegmentBlocks(ISheet sheet, int sourceStartRow, int sourceEndRow, int blockCount) + { + if (sourceEndRow < sourceStartRow) + { + throw new InvalidDataException($"工作表「{sheet.SheetName}」没有可供分块的模板数据行。"); + } + + var blocks = new List(blockCount) + { + new(sourceStartRow, sourceEndRow), + }; + for (var index = 1; index < blockCount; index++) + { + var destinationStartRow = sheet.LastRowNum + 1; + CopyRowBlock(sheet, sourceStartRow, sourceEndRow, destinationStartRow); + blocks.Add(new SegmentBlock(destinationStartRow, destinationStartRow + sourceEndRow - sourceStartRow)); + } + return blocks; + } + + private static void CopyRowBlock(ISheet sheet, int sourceStartRow, int sourceEndRow, int destinationStartRow) + { + var mergedRanges = Enumerable.Range(0, sheet.NumMergedRegions) + .Select(sheet.GetMergedRegion) + .Where(range => range.FirstRow >= sourceStartRow && range.LastRow <= sourceEndRow) + .ToList(); + + for (var sourceIndex = sourceStartRow; sourceIndex <= sourceEndRow; sourceIndex++) + { + var source = sheet.GetRow(sourceIndex); + var target = sheet.CreateRow(destinationStartRow + sourceIndex - sourceStartRow); + if (source == null) continue; + target.Height = source.Height; + target.ZeroHeight = source.ZeroHeight; + for (var column = 0; column < source.LastCellNum; column++) + { + var sourceCell = source.GetCell(column); + if (sourceCell == null) continue; + var targetCell = target.CreateCell(column, sourceCell.CellType); + CopyCell(sourceCell, targetCell); + } + } + + var rowOffset = destinationStartRow - sourceStartRow; + foreach (var range in mergedRanges) + { + sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress( + range.FirstRow + rowOffset, + range.LastRow + rowOffset, + range.FirstColumn, + range.LastColumn)); + } + } + + private static void AddSegmentColumn( + IWorkbook workbook, + ISheet sheet, + IReadOnlyList blocks, + int headerRows, + IReadOnlyCollection selectedSegments) + { + var maxColumn = sheet.GetRow(0)?.LastCellNum - 1 ?? 0; + for (var rowIndex = 0; rowIndex <= sheet.LastRowNum; rowIndex++) + { + maxColumn = Math.Max(maxColumn, (sheet.GetRow(rowIndex)?.LastCellNum ?? 0) - 1); + } + + var originalWidths = Enumerable.Range(0, Math.Max(1, maxColumn + 1)) + .Select(sheet.GetColumnWidth) + .ToArray(); + var mergedRanges = Enumerable.Range(0, sheet.NumMergedRegions) + .Select(sheet.GetMergedRegion) + .ToList(); + for (var index = sheet.NumMergedRegions - 1; index >= 0; index--) + { + sheet.RemoveMergedRegion(index); + } + + for (var rowIndex = 0; rowIndex <= sheet.LastRowNum; rowIndex++) + { + var row = sheet.GetRow(rowIndex); + if (row == null) continue; + for (var column = maxColumn; column >= 0; column--) + { + var source = row.GetCell(column); + var destination = row.GetCell(column + 1) ?? row.CreateCell(column + 1); + if (source == null) + { + ClearCell(destination, CellType.Blank); + } + else + { + CopyCell(source, destination); + } + } + var firstColumn = row.GetCell(0) ?? row.CreateCell(0); + ClearCell(firstColumn, CellType.Blank); + } + + for (var column = originalWidths.Length - 1; column >= 0; column--) + { + sheet.SetColumnWidth(column + 1, originalWidths[column]); + } + sheet.SetColumnWidth(0, 18 * 256); + + foreach (var range in mergedRanges) + { + sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress( + range.FirstRow, + range.LastRow, + range.FirstColumn + 1, + range.LastColumn + 1)); + } + + var header = sheet.GetRow(0) ?? sheet.CreateRow(0); + var headerCell = header.GetCell(0) ?? header.CreateCell(0); + SetText(header, 0, "板块"); + var headerSourceStyle = header.GetCell(1)?.CellStyle; + if (headerSourceStyle != null) + { + var style = workbook.CreateCellStyle(); + style.CloneStyleFrom(headerSourceStyle); + style.Alignment = HorizontalAlignment.Center; + style.VerticalAlignment = VerticalAlignment.Center; + headerCell.CellStyle = style; + } + if (headerRows > 1) + { + sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, headerRows - 1, 0, 0)); + } + + var labelStyle = workbook.CreateCellStyle(); + var styleSource = blocks.Select(block => sheet.GetRow(block.StartRow)?.GetCell(0)?.CellStyle).FirstOrDefault(style => style != null); + if (styleSource != null) labelStyle.CloneStyleFrom(styleSource); + labelStyle.Alignment = HorizontalAlignment.Center; + labelStyle.VerticalAlignment = VerticalAlignment.Center; + labelStyle.WrapText = true; + + var segments = selectedSegments.ToList(); + for (var index = 0; index < blocks.Count; index++) + { + var block = blocks[index]; + var firstRow = sheet.GetRow(block.StartRow) ?? sheet.CreateRow(block.StartRow); + var label = firstRow.GetCell(0) ?? firstRow.CreateCell(0); + label.CellStyle = labelStyle; + label.SetCellValue(segments[index] + "板块"); + if (block.EndRow > block.StartRow) + { + sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(block.StartRow, block.EndRow, 0, 0)); + } + } + } + + private static void CopyCell(ICell source, ICell destination) + { + destination.CellStyle = source.CellStyle; + switch (source.CellType) + { + case CellType.String: + destination.SetCellValue(source.StringCellValue); + break; + case CellType.Numeric: + destination.SetCellValue(source.NumericCellValue); + break; + case CellType.Boolean: + destination.SetCellValue(source.BooleanCellValue); + break; + case CellType.Formula: + destination.SetCellFormula(source.CellFormula); + break; + case CellType.Error: + destination.SetCellErrorValue(source.ErrorCellValue); + break; + default: + destination.SetCellType(CellType.Blank); + break; + } + if (source.Hyperlink != null) destination.Hyperlink = source.Hyperlink; + } + + #endregion + + #region 模板读取与单元格操作 + + private static Dictionary ReadMonthColumns(ISheet sheet, int headerRowIndex, int firstColumn) + { + var columns = new Dictionary(); + var row = sheet.GetRow(headerRowIndex); + if (row == null) return columns; + for (var column = firstColumn; column < row.LastCellNum; column++) + { + var text = ReadText(row.GetCell(column)); + if (!text.EndsWith("月", StringComparison.Ordinal)) continue; + if (int.TryParse(text.TrimEnd('月'), NumberStyles.Integer, CultureInfo.InvariantCulture, out var month)) + { + columns[month] = column; + } + } + return columns; + } + + private static HashSet GetNormalSummaryKeys(ISheet sheet) + { + var keys = new HashSet(); + for (var i = 1; i <= sheet.LastRowNum; i++) + { + var row = sheet.GetRow(i); + if (row != null && TryReadNormalKey(sheet, row, out var key)) keys.Add(key); + } + return keys; + } + + private static HashSet GetNormalMonthKeys(ISheet sheet) + { + var keys = new HashSet(); + for (var i = 2; i <= sheet.LastRowNum; i++) + { + var row = sheet.GetRow(i); + if (row == null || ReadText(row.GetCell(0)) == "合计") continue; + if (TryReadNormalKey(sheet, row, out var key)) keys.Add(key); + } + return keys; + } + + private static bool TryReadNormalKey(ISheet sheet, IRow row, out NormalKey key) + { + key = default; + var product = ReadMergedText(sheet, row.RowNum, 0); + var board = ReadMergedText(sheet, row.RowNum, 1); + var stage = ReadMergedText(sheet, row.RowNum, 2); + var process = ReadText(row.GetCell(3)); + if (string.IsNullOrWhiteSpace(product) || product is "全厂合计" or "合计" || string.IsNullOrWhiteSpace(board)) return false; + if (stage == "整机" && !string.IsNullOrWhiteSpace(process)) + { + key = new NormalKey(product, "整机", "整机", process); + return true; + } + if ((stage is "基板" or "调试") && !string.IsNullOrWhiteSpace(process)) + { + key = new NormalKey(product, board, stage, process); + return true; + } + if (NormalWholeMachineProcesses.Contains(stage, StringComparer.Ordinal) && string.IsNullOrWhiteSpace(process)) + { + key = new NormalKey(product, "整机", "整机", stage); + return true; + } + return false; + } + + private static string ReadMergedText(ISheet sheet, int rowIndex, int columnIndex) + { + var value = ReadText(sheet.GetRow(rowIndex)?.GetCell(columnIndex)); + if (!string.IsNullOrWhiteSpace(value)) return value; + for (var i = 0; i < sheet.NumMergedRegions; i++) + { + var range = sheet.GetMergedRegion(i); + if (range.IsInRange(rowIndex, columnIndex)) + { + return ReadText(sheet.GetRow(range.FirstRow)?.GetCell(range.FirstColumn)); + } + } + return value; + } + + private static void WriteNormalKey(IRow row, NormalKey key) + { + SetText(row, 0, key.Product); + SetText(row, 1, key.Board); + SetText(row, 2, key.Stage); + SetText(row, 3, key.Process); + } + + private static int FindNormalTotalRow(ISheet sheet) + { + for (var i = sheet.LastRowNum; i >= 1; i--) + { + if (ReadText(sheet.GetRow(i)?.GetCell(0)) == "全厂合计") return i; + } + return -1; + } + + private static int FindMonthTotalRow(ISheet sheet) + { + for (var i = sheet.LastRowNum; i >= 2; i--) + { + if (ReadText(sheet.GetRow(i)?.GetCell(0)) == "合计") return i; + } + return -1; + } + + private static IRow InsertBeforeTotal(ISheet sheet, int totalRowIndex, IRow? styleSource) + { + return InsertBeforeRow(sheet, totalRowIndex >= 0 ? totalRowIndex : sheet.LastRowNum + 1, styleSource); + } + + private static IRow InsertBeforeMonthTotal(ISheet sheet, IRow? styleSource) + { + var totalRowIndex = FindMonthTotalRow(sheet); + return InsertBeforeRow(sheet, totalRowIndex >= 0 ? totalRowIndex : sheet.LastRowNum + 1, styleSource); + } + + private static IRow InsertBeforeRow(ISheet sheet, int rowIndex, IRow? styleSource) + { + if (rowIndex <= sheet.LastRowNum) + { + sheet.ShiftRows(rowIndex, sheet.LastRowNum, 1, true, false); + } + var row = sheet.CreateRow(rowIndex); + CopyRowStyle(styleSource, row); + return row; + } + + private static IRow AppendRow(ISheet sheet, IRow? styleSource) + { + var row = sheet.CreateRow(sheet.LastRowNum + 1); + CopyRowStyle(styleSource, row); + return row; + } + + private static IRow? CopyStyleFromLastDataRow(ISheet sheet) + { + for (var i = sheet.LastRowNum; i >= 1; i--) + { + var row = sheet.GetRow(i); + if (row != null && !string.IsNullOrWhiteSpace(ReadText(row.GetCell(0)))) return row; + } + return sheet.GetRow(Math.Max(1, sheet.LastRowNum)); + } + + private static void CopyRowStyle(IRow? source, IRow target) + { + if (source == null) return; + target.Height = source.Height; + for (var column = 0; column < source.LastCellNum; column++) + { + var from = source.GetCell(column); + if (from == null) continue; + target.CreateCell(column).CellStyle = from.CellStyle; + } + } + + private static string GetNormalDetailSheet(WorkhourTemplateRecord record) + { + var key = ToNormalKey(record); + if (key.Stage == "基板") return "基板"; + return key.Process switch + { + "整机总装" => "总装", + "包装" => "包装", + _ => "调试", + }; + } + + private static string GetNormalBoard(WorkhourTemplateRecord record) + { + if (record.Category == "整机" + || NormalWholeMachineProcesses.Contains(record.Category ?? string.Empty, StringComparer.Ordinal) + || NormalWholeMachineProcesses.Contains(record.ProcessName ?? string.Empty, StringComparer.Ordinal)) return "整机"; + return record.GroupName?.Trim() ?? string.Empty; + } + + private static string ReadText(ICell? cell) + { + if (cell == null || cell.CellType == CellType.Blank) return string.Empty; + return new DataFormatter(CultureInfo.InvariantCulture).FormatCellValue(cell).Trim(); + } + + private static bool TryReadMonth(string? mfgMonth, out int month) + { + month = 0; + if (string.IsNullOrWhiteSpace(mfgMonth)) return false; + var parts = mfgMonth.Split('-'); + return parts.Length == 2 && int.TryParse(parts[1], out month) && month is >= 1 and <= 12; + } + + private static void SetText(IRow row, int column, string? value) + { + var cell = row.GetCell(column) ?? row.CreateCell(column); + cell.SetCellValue(value ?? string.Empty); + } + + private static void SetNumber(IRow row, int column, double value) + { + var cell = row.GetCell(column) ?? row.CreateCell(column); + cell.SetCellValue(value); + } + + private static void SetOptionalNumber(IRow row, int column, double value) + { + if (value == 0) return; + SetNumber(row, column, value); + } + + private static void ClearCells(IRow row, int start, int end) + { + for (var column = start; column <= end && column < row.LastCellNum; column++) ClearCell(row, column); + } + + private static void ClearCell(IRow row, int column) + { + var cell = row.GetCell(column) ?? row.CreateCell(column); + ClearCell(cell, CellType.Blank); + } + + private static void ClearCell(ICell cell, CellType cellType) + { + cell.SetCellType(cellType); + } + + #endregion + + #region 导出数据结构 + + private sealed record SegmentBlock(int StartRow, int EndRow); + private sealed record NormalKey(string Product, string Board, string Stage, string Process); + private sealed record NormalDetailKey(int Month, string Product, string Board, string Process); + private sealed record AbnormalDetailKey(string Process, string Product, string Remark); + + private sealed class MonthValue + { + public int Qty { get; private set; } + public int Minutes { get; private set; } + public void Add(int qty, int minutes) + { + Qty += qty; + Minutes += minutes; + } + } + + private sealed class MonthBucket + { + private readonly Dictionary _months = new(); + public int TotalQty { get; private set; } + public int TotalMinutes { get; private set; } + public void Add(int month, int qty, int minutes) + { + if (!_months.TryGetValue(month, out var value)) _months[month] = value = new MonthValue(); + value.Add(qty, minutes); + TotalQty += qty; + TotalMinutes += minutes; + } + public MonthValue? Get(int month) => _months.TryGetValue(month, out var value) ? value : null; + public void Merge(MonthBucket other) + { + foreach (var month in other._months) + { + Add(month.Key, month.Value.Qty, month.Value.Minutes); + } + } + } + + public sealed record WorkhourTemplateRecord( + string? BusinessSegment, + string? DictType, + string? Category, + string? GroupName, + string? ProcessName, + string? ProductName, + string? MfgMonth, + string? Remark, + int Qty, + int Minutes); + + private static MonthBucket MergeBuckets(IEnumerable buckets) + { + var merged = new MonthBucket(); + foreach (var bucket in buckets) merged.Merge(bucket); + return merged; + } + + #endregion + } +} diff --git a/SK_ERP_WebService/SK_ERP_WebService/Worker/DayJob.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Worker/DayJob.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Worker/DayJob.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Worker/DayJob.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/Worker/JdyTokenJob.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Worker/JdyTokenJob.cs similarity index 82% rename from SK_ERP_WebService/SK_ERP_WebService/Worker/JdyTokenJob.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Worker/JdyTokenJob.cs index 5081053..bc6d615 100644 --- a/SK_ERP_WebService/SK_ERP_WebService/Worker/JdyTokenJob.cs +++ b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Worker/JdyTokenJob.cs @@ -40,8 +40,11 @@ namespace SK_ERP_WebService.Worker /// public async Task Execute(IJobExecutionContext context) { - _logger.LogInformation("开始每日更新金蝶云Token!"); - _jdyService.UpdateAppToken(); + _logger.LogInformation("开始定时刷新金蝶云 app-token。"); + if (!_jdyService.UpdateAppToken()) + { + _logger.LogWarning("定时刷新金蝶云 app-token 失败。"); + } } } } diff --git a/SK_ERP_WebService/SK_ERP_WebService/Worker/ServiceInitJob.cs b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Worker/ServiceInitJob.cs similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/Worker/ServiceInitJob.cs rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/Worker/ServiceInitJob.cs diff --git a/SK_ERP_WebService/SK_ERP_WebService/appsettings.Development.json b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/appsettings.Development.json similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/appsettings.Development.json rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/appsettings.Development.json diff --git a/SK_ERP_WebService/SK_ERP_WebService/appsettings.json b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/appsettings.json similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/appsettings.json rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/appsettings.json diff --git a/SK_ERP_WebService/SK_ERP_WebService/register.bat b/Lifecycle/SK_ERP_WebService/SK_ERP_WebService/register.bat similarity index 100% rename from SK_ERP_WebService/SK_ERP_WebService/register.bat rename to Lifecycle/SK_ERP_WebService/SK_ERP_WebService/register.bat diff --git a/Lifecycle/SK_ERP_WebService/迁移清单.md b/Lifecycle/SK_ERP_WebService/迁移清单.md new file mode 100644 index 0000000..c5e81d0 --- /dev/null +++ b/Lifecycle/SK_ERP_WebService/迁移清单.md @@ -0,0 +1,121 @@ +# 工时模块迁移清单 + +## 2026-11-19:ERP工单查询验证与回查修正 + +对以下三个真实单号执行了只读 ERP 查询: + +| 工单号 | 反馈类型 | ERP 列表精确命中 | 按单号查详情 | 按列表 ID 查详情 | +|---|---|---|---|---| +| `WWJGD-20261019-00015` | 外加工 | 是 | 只返回单据头 | 成功,1 条物料明细 | +| `WWJGD-20261019-00014` | 半成品 | 是 | 只返回单据头 | 成功,1 条物料明细 | +| `WWJGD-20261102-00001` | 成品 | 是 | 只返回单据头 | 成功,1 条物料明细 | + +问题不是这些单号不存在:`/jdy/v2/pm/subm_workorder` 列表接口能按工单号匹配记录,但 `/jdy/v2/pm/subm_workorder_detail?number=...` 的成功响应没有物料明细;用列表记录的 `id` 调同一详情接口后,三单都返回了物料。`/jdy/v2/pm/mo_taskbill_detail` 对这三个单号返回 HTTP 400;生产任务单列表探测返回 HTTP 519,暂不能据此判断其他生产任务单的查询能力。 三张单据的物料行均包含 `material_number`,满足工时产品编号回退字段;接口未返回可用的 `device_code`。 + +源码中的工时查询已增加回查:按单号中的日期分页查询委外工单列表,精确匹配单号,再用返回的 ID 请求详情。原有生产任务单及按单号查询路径仍保留。非正常工时无工单号逻辑、工序及数量/分钟字段保持原有实现。 + +token 首次请求返回授权刷新状态;按服务已有的授权刷新流程获取到 token 后完成了上述只读查询。刷新响应只在临时测试进程中使用,没有改写本地 XML、数据库或服务器。 + +已在本机完成 Service 发布和 Web 生产构建:产物位于仓库根目录 `push/Service`、`push/Web`。构建有现存可空性、XML 文档和前端依赖提示,但无编译错误。未部署服务器,未连接或写入 MySQL。 + +## 2026-11-12:服务器拉取版 Service 增量更新 + +已用完整后端源码构建工时功能,并将发布产物直接更新到本地从服务器拉取的发布目录 `D:\work\SKIOT\code\Lifecycle\Service261112`。该目录本身是发布目录,不包含源码;服务器也不需要放 `.cs` 或 `.csproj`。 + +本次只替换以下三个发布文件: + +| 文件 | 操作 | 说明 | +|---|---|---| +| `SK_ERP_WebService.dll` | 替换 | 加入工时权限接口及工时服务端代码;同时保留当前源码中的二维码请求字段映射 | +| `SK_ERP_WebService.pdb` | 替换 | 与新 DLL 对应的调试符号 | +| `SK_ERP_WebService.xml` | 替换 | 更新 API XML 文档 | + +更新后的 DLL SHA256:`3AEA7212232AE9E795EB0833717E5F9FDD4929EC32B184149656F0FC1619A146`。拉取目录中原 DLL SHA256 为 `CD895E1A3A106110EC59EF3EEA43F88B8F68138FD2691CD85C627FC4CC4D07B7`,与此前服务器提供的哈希一致。 + +替换前的三个文件已备份到 `D:\work\SKIOT\code\Lifecycle\Service261112-before-workhour-20261112`。服务器部署时,停止 Service 进程后,只需将上述三个更新文件复制到服务器的 Service 发布目录并覆盖同名文件;保留服务器原有 `appsettings*.json`、`XML\Config.xml`、`SK_ERP_WebService.staticwebassets.endpoints.json`、依赖项、`runtimes` 和日志目录。回退时从上述备份目录恢复三个旧文件。 + +本地对新发布文件做了 SHA256 回读核对,确认与构建候选件一致;未连接生产数据库,也未在本次操作中执行 SQL 或做运行时端到端验证。若二维码请求的 `Operator` 仍未由调用方传入,数据库的 `Operator` 非空错误仍需由请求方补齐该字段。 + +源码仍在 `Lifecycle` 目录;仓库根目录的 `push` 是单独的发布目录,含 `Service` 与 `Web`。`zx` 和 `push` 已从 Git 变更列表中排除。 + +下表说明如何把本包文件合并到原有的前后端**源码工程**中;它不是服务器文件复制清单。`.csproj`、`.cs`、前端源码等用于构建,不需要单独复制到生产服务器。完成源码合并和构建后,服务器接收前端构建产物与后端发布产物。 + +生产 Service 目录通常看不到 `Controllers`、`Model` 等源码文件:这些代码已编译到程序程序集里。发布目录应能找到服务的 `.dll`(通常还会有 `.deps.json`、`.runtimeconfig.json`,有时带同名 `.exe`)、依赖文件及 `runtimes` 等目录。如果当前查看位置只有 `logfiles`、`runtimes`、`XML` 等目录且没有服务程序文件,应按服务器实际托管方式(Windows 服务/IIS、Linux systemd、Docker 或运维面板)查看进程启动项或容器挂载目录,确认真正的发布目录后再部署构建产物。 + +## 迁移前要保留的配置 + +- `push/Service` 不带 `appsettings*.json` 或 `XML/Config.xml`。部署时保留服务器现有配置,不要用源码目录或本机配置覆盖;当前 MySQL 连接配置还涉及 `Configer`,部署前须按服务器现状核对实际连接目标。 +- 前端源码位于 `Lifecycle/productLifecycleManagement`;本次发布产物位于 `push/Web`。开发配置不部署到生产。 +- 先备份服务器当前 Web 发布目录、Service 发布目录和 MySQL 数据库。当前没有执行任何生产 SQL,也没有改动服务器账号或数据库。 + +## 源码工程合并表 + +表内路径分别相对于源码目录 `Lifecycle/productLifecycleManagement`、`Lifecycle/SK_ERP_WebService`。表中的“替换/新增”指源码工程中的操作,不是把 `.cs` 或前端源码复制到服务器。 + +| 模块 | 文件路径 | 操作 | 用途 | +|---|---|---|---| +| Web | `package.json` | 替换 | 保留原应用命令;移除构建时自动同步 demo 的脚本 | +| Web | `components.d.ts` | 替换 | 加入工时页面组件声明 | +| Web | `src/apis/model/userModel.ts` | 替换 | 扩展用户工时权限字段 | +| Web | `src/apis/user.ts` | 替换 | 加入人员工时权限接口调用 | +| Web | `src/main.ts` | 替换 | 注册工时页面所需组件 | +| Web | `src/pages/login/index.vue` | 替换 | 配合现有登录流程读取用户权限 | +| Web | `src/pages/user/userManage.vue` | 替换 | 在人员管理中配置正常工时和非正常工时权限组 | +| Web | `src/permission.ts` | 替换 | 根据登录用户权限控制工时页面访问 | +| Web | `src/router/index.ts` | 替换 | 注册工时路由 | +| Web | `src/router/routes.ts` | 替换 | 注册工时菜单及路由项 | +| Web | `src/utils/http/index.ts` | 替换 | 配合工时 API 请求 | +| Web | `src/utils/http/request.ts` | 替换 | 统一处理工时请求的登录态和响应 | +| Web | `vite.config.ts` | 替换 | 保留原构建配置并构建工时前端 | +| Web | `src/apis/model/workhourModel.ts` | 新增 | 工时数据类型 | +| Web | `src/apis/workhour.ts` | 新增 | 工时填报、查询、字典和导出接口 | +| Web | `src/pages/workhour/index.vue` | 新增 | 工时填报页 | +| Web | `src/pages/workhour/processDict.vue` | 新增 | 工序字典维护页 | +| Web | `src/pages/workhour/stat.vue` | 新增 | 工时统计和导出页 | +| Service | `SK_ERP_WebService.csproj` | 替换 | 引入代码生成 Excel 所需的 NPOI 依赖 | +| Service | `Controllers/Web/UserController.cs` | 替换 | 提供人员工时权限读取和保存接口 | +| Service | `Model/MySql/UserBasicinfo.cs` | 替换 | 映射用户工时权限信息 | +| Service | `Controllers/Web/WorkhourController.cs` | 新增 | 工时权限、实时 ERP 工单读取、填报、查询和导出接口 | +| Service | `Jdy/Helper/AppTokenHelper.cs` | 修改 | 校验授权响应及 token 获取结果,刷新失败不再误报成功 | +| Service | `Jdy/Helper/SubmWorkorderHelper.cs` | 修改 | 工时查询同时支持生产任务单及委外加工单详情接口 | +| Service | `Jdy/Util/SubmWorkorderList.cs` | 修改 | 保存ERP列表记录ID,用于按ID回查工单详情 | +| Service | `Service/JdyService.cs` | 修改 | 输出 token 刷新结果并提供工时工单查询入口 | +| Service | `Worker/JdyTokenJob.cs`、`Program.cs` | 修改 | 每 6 小时刷新 app-token,并记录失败日志 | +| Service | `Model/MySql/DictProcess.cs` | 新增 | 工序字典表映射 | +| Service | `Model/MySql/UserWorkhourScope.cs` | 新增 | 人员工时授权表映射 | +| Service | `Model/MySql/WorkhourRecord.cs` | 新增 | 工时记录表映射 | +| Service | `Model/MySql/WorkhourOrderProduct.cs` | 新增 | 独立保存 ERP 工单产品快照,不写原工单和产品字典表 | +| Service | `Model/Response/WorkhourInfo.cs` | 新增 | 工时页面接口数据模型 | +| Service | `Model/WorkhourScopeDefinitions.cs` | 新增 | 正常工时大类与非正常工时组权限定义 | +| Service | `Service/WorkhourTemplateExportService.cs` | 新增 | 按字段和记录用 NPOI 生成工作簿,不读取年份 Excel 模板 | +| Database | `Database/workhour_schema.sql` | 新增 | 创建工时表并初始化工序字典 | +| Database | `Database/workhour_template_segment_migration.sql` | 新增 | 补齐板件工序、板块字段索引及旧工时分类修正 | +| Database | `Database/workhour_erp_snapshot_migration.sql` | 新增 | 仅给缺少 `workhour_order_product` 的既有工时库补表;新库已由 schema 脚本创建时不必重复执行 | +| Database | `Database/workhour_non_order_abnormal_migration.sql` | 新增 | 允许非正常工时不关联工单,并保存选填产品名称 | +| Web | `src/apis/model/workhourModel.ts` | 修改 | 工时记录和填报参数允许缺少工单号/产品代码,新增产品名称字段 | + +## 数据库脚本顺序 + +服务启动时不会自动建工时表或执行这些 SQL。首次增加工时模块时,先确认目标库为 `lifecircle` 并备份数据库,再手动执行 `Database/workhour_schema.sql`,随后执行 `Database/workhour_template_segment_migration.sql`。第二个脚本会补齐完整工序字典,并可能更新已有工时记录分类;如果目标库里已经有工时数据,先核对脚本中的 `UPDATE workhour_record` 语句和数据备份,再安排执行。 + +`workhour_schema.sql` 已创建 `workhour_order_product`。只有目标库已经部署过旧版工时表、但缺少该快照表时,才单独执行 `workhour_erp_snapshot_migration.sql`。 + +若数据库已经有工时表,且要启用无工单号的非正常工时,再执行 `workhour_non_order_abnormal_migration.sql`。新库使用更新后的 `workhour_schema.sql` 时已包含对应列定义;该迁移脚本可重复运行。 + +这些脚本只新增工时模块表和字典数据,不重置账号;工时服务实时请求 ERP,ERP 工单产品快照单独写入 `workhour_order_product`。本次没有连接生产 MySQL 或实际执行这些脚本。 + +## 业务约定 + +- 正常工时始终展示模板要求的工序:基板为贴片、锡检、插补、加工;调试为烧写程序、打二维码、调试、刷三防漆;整机为整机调试、整机总装、包装。即使某工序当月没有数据,导出仍保留对应行。 +- 非正常工时授权按组配置,填报时选择组别和工序;工序为程序升级、硬件升级、其他,记录保留数量、分钟数和备注,不选择板件。非正常工时可不关联工单,产品名称为选填。 +- 正常和非正常权限在人员管理中分别配置。填报和统计页面按账号权限显示。 +- Excel 由代码字段生成;不携带 2025/2026 年的业务工作簿。导出年份由页面选择。 + +## 构建与验证 + +前端在 `Lifecycle/productLifecycleManagement` 目录运行 `npm run build`,产物整理至仓库根目录 `push/Web`;后端在 `Lifecycle/SK_ERP_WebService` 目录使用 .NET 8 SDK 发布,产物位于 `push/Service`。发布时保留服务器现有配置,并把 `push/Service/Database` 中的 SQL 按迁移清单手动核对执行。 +注意:`push/Web/workhour-demo.html` 已排除;压缩插件生成的孤立文件 `push/Web/workhour-demo.html.gz` 仍在目录中,部署时不要复制该文件。 + +历史记录:2026-11-09 的 Service 构建有 346 个警告。2026-11-19 当前源码的 Service 发布与 Web 生产构建均已完成;构建仍有可空性、XML 文档和前端依赖提示,尚未逐条清理。 + +2026-11-19 已从当前源码重新构建 Service 与 Web,输出至仓库根目录 `push`。本地测试直接请求 ERP 验证了上述三个工单的列表与详情回查;尚未通过完整 Service/Web 页面执行端到端填报,也未进行服务器回归。 diff --git a/productLifecycleManagement/.env b/Lifecycle/productLifecycleManagement/.env similarity index 100% rename from productLifecycleManagement/.env rename to Lifecycle/productLifecycleManagement/.env diff --git a/productLifecycleManagement/.env.development b/Lifecycle/productLifecycleManagement/.env.development similarity index 100% rename from productLifecycleManagement/.env.development rename to Lifecycle/productLifecycleManagement/.env.development diff --git a/productLifecycleManagement/.env.production b/Lifecycle/productLifecycleManagement/.env.production similarity index 100% rename from productLifecycleManagement/.env.production rename to Lifecycle/productLifecycleManagement/.env.production diff --git a/productLifecycleManagement/.eslintignore b/Lifecycle/productLifecycleManagement/.eslintignore similarity index 100% rename from productLifecycleManagement/.eslintignore rename to Lifecycle/productLifecycleManagement/.eslintignore diff --git a/productLifecycleManagement/.eslintrc b/Lifecycle/productLifecycleManagement/.eslintrc similarity index 100% rename from productLifecycleManagement/.eslintrc rename to Lifecycle/productLifecycleManagement/.eslintrc diff --git a/productLifecycleManagement/.eslintrc-auto-import.json b/Lifecycle/productLifecycleManagement/.eslintrc-auto-import.json similarity index 100% rename from productLifecycleManagement/.eslintrc-auto-import.json rename to Lifecycle/productLifecycleManagement/.eslintrc-auto-import.json diff --git a/productLifecycleManagement/.gitignore b/Lifecycle/productLifecycleManagement/.gitignore similarity index 100% rename from productLifecycleManagement/.gitignore rename to Lifecycle/productLifecycleManagement/.gitignore diff --git a/productLifecycleManagement/.prettierignore b/Lifecycle/productLifecycleManagement/.prettierignore similarity index 100% rename from productLifecycleManagement/.prettierignore rename to Lifecycle/productLifecycleManagement/.prettierignore diff --git a/productLifecycleManagement/.prettierrc b/Lifecycle/productLifecycleManagement/.prettierrc similarity index 100% rename from productLifecycleManagement/.prettierrc rename to Lifecycle/productLifecycleManagement/.prettierrc diff --git a/productLifecycleManagement/README.md b/Lifecycle/productLifecycleManagement/README.md similarity index 100% rename from productLifecycleManagement/README.md rename to Lifecycle/productLifecycleManagement/README.md diff --git a/productLifecycleManagement/auto-imports.d.ts b/Lifecycle/productLifecycleManagement/auto-imports.d.ts similarity index 100% rename from productLifecycleManagement/auto-imports.d.ts rename to Lifecycle/productLifecycleManagement/auto-imports.d.ts diff --git a/productLifecycleManagement/commitlint.config.cjs b/Lifecycle/productLifecycleManagement/commitlint.config.cjs similarity index 100% rename from productLifecycleManagement/commitlint.config.cjs rename to Lifecycle/productLifecycleManagement/commitlint.config.cjs diff --git a/productLifecycleManagement/components.d.ts b/Lifecycle/productLifecycleManagement/components.d.ts similarity index 95% rename from productLifecycleManagement/components.d.ts rename to Lifecycle/productLifecycleManagement/components.d.ts index 558b875..cf6fb9e 100644 --- a/productLifecycleManagement/components.d.ts +++ b/Lifecycle/productLifecycleManagement/components.d.ts @@ -10,6 +10,7 @@ declare module 'vue' { CommonAside: typeof import('./src/components/CommonAside.vue')['default'] CommonHeader: typeof import('./src/components/CommonHeader.vue')['default'] DeviceDetail: typeof import('./src/components/DeviceDetail.vue')['default'] + ElAlert: typeof import('element-plus/es')['ElAlert'] ElButton: typeof import('element-plus/es')['ElButton'] ElCheckbox: typeof import('element-plus/es')['ElCheckbox'] ElCheckboxGroup: typeof import('element-plus/es')['ElCheckboxGroup'] @@ -25,6 +26,7 @@ declare module 'vue' { ElIcon: typeof import('element-plus/es')['ElIcon'] ElImage: typeof import('element-plus/es')['ElImage'] ElInput: typeof import('element-plus/es')['ElInput'] + ElInputNumber: typeof import('element-plus/es')['ElInputNumber'] ElMenu: typeof import('element-plus/es')['ElMenu'] ElMenuItem: typeof import('element-plus/es')['ElMenuItem'] ElOption: typeof import('element-plus/es')['ElOption'] diff --git a/productLifecycleManagement/index.html b/Lifecycle/productLifecycleManagement/index.html similarity index 100% rename from productLifecycleManagement/index.html rename to Lifecycle/productLifecycleManagement/index.html diff --git a/productLifecycleManagement/package-lock.json b/Lifecycle/productLifecycleManagement/package-lock.json similarity index 100% rename from productLifecycleManagement/package-lock.json rename to Lifecycle/productLifecycleManagement/package-lock.json diff --git a/productLifecycleManagement/package.json b/Lifecycle/productLifecycleManagement/package.json similarity index 100% rename from productLifecycleManagement/package.json rename to Lifecycle/productLifecycleManagement/package.json diff --git a/productLifecycleManagement/postcss.config.cjs b/Lifecycle/productLifecycleManagement/postcss.config.cjs similarity index 100% rename from productLifecycleManagement/postcss.config.cjs rename to Lifecycle/productLifecycleManagement/postcss.config.cjs diff --git a/productLifecycleManagement/public/vite.svg b/Lifecycle/productLifecycleManagement/public/vite.svg similarity index 100% rename from productLifecycleManagement/public/vite.svg rename to Lifecycle/productLifecycleManagement/public/vite.svg diff --git a/productLifecycleManagement/src/App.vue b/Lifecycle/productLifecycleManagement/src/App.vue similarity index 100% rename from productLifecycleManagement/src/App.vue rename to Lifecycle/productLifecycleManagement/src/App.vue diff --git a/productLifecycleManagement/src/apis/box.ts b/Lifecycle/productLifecycleManagement/src/apis/box.ts similarity index 100% rename from productLifecycleManagement/src/apis/box.ts rename to Lifecycle/productLifecycleManagement/src/apis/box.ts diff --git a/productLifecycleManagement/src/apis/client.ts b/Lifecycle/productLifecycleManagement/src/apis/client.ts similarity index 100% rename from productLifecycleManagement/src/apis/client.ts rename to Lifecycle/productLifecycleManagement/src/apis/client.ts diff --git a/productLifecycleManagement/src/apis/customer.ts b/Lifecycle/productLifecycleManagement/src/apis/customer.ts similarity index 100% rename from productLifecycleManagement/src/apis/customer.ts rename to Lifecycle/productLifecycleManagement/src/apis/customer.ts diff --git a/productLifecycleManagement/src/apis/device.ts b/Lifecycle/productLifecycleManagement/src/apis/device.ts similarity index 100% rename from productLifecycleManagement/src/apis/device.ts rename to Lifecycle/productLifecycleManagement/src/apis/device.ts diff --git a/productLifecycleManagement/src/apis/dict.ts b/Lifecycle/productLifecycleManagement/src/apis/dict.ts similarity index 100% rename from productLifecycleManagement/src/apis/dict.ts rename to Lifecycle/productLifecycleManagement/src/apis/dict.ts diff --git a/productLifecycleManagement/src/apis/instock.ts b/Lifecycle/productLifecycleManagement/src/apis/instock.ts similarity index 100% rename from productLifecycleManagement/src/apis/instock.ts rename to Lifecycle/productLifecycleManagement/src/apis/instock.ts diff --git a/productLifecycleManagement/src/apis/logistics.ts b/Lifecycle/productLifecycleManagement/src/apis/logistics.ts similarity index 100% rename from productLifecycleManagement/src/apis/logistics.ts rename to Lifecycle/productLifecycleManagement/src/apis/logistics.ts diff --git a/productLifecycleManagement/src/apis/manuRepair.ts b/Lifecycle/productLifecycleManagement/src/apis/manuRepair.ts similarity index 100% rename from productLifecycleManagement/src/apis/manuRepair.ts rename to Lifecycle/productLifecycleManagement/src/apis/manuRepair.ts diff --git a/productLifecycleManagement/src/apis/model/boxModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/boxModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/boxModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/boxModel.ts diff --git a/productLifecycleManagement/src/apis/model/clientModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/clientModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/clientModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/clientModel.ts diff --git a/productLifecycleManagement/src/apis/model/customerModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/customerModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/customerModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/customerModel.ts diff --git a/productLifecycleManagement/src/apis/model/deviceModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/deviceModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/deviceModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/deviceModel.ts diff --git a/productLifecycleManagement/src/apis/model/dictModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/dictModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/dictModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/dictModel.ts diff --git a/productLifecycleManagement/src/apis/model/instockModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/instockModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/instockModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/instockModel.ts diff --git a/productLifecycleManagement/src/apis/model/logisticsModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/logisticsModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/logisticsModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/logisticsModel.ts diff --git a/productLifecycleManagement/src/apis/model/manuRepairModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/manuRepairModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/manuRepairModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/manuRepairModel.ts diff --git a/productLifecycleManagement/src/apis/model/orderModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/orderModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/orderModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/orderModel.ts diff --git a/productLifecycleManagement/src/apis/model/outstockModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/outstockModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/outstockModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/outstockModel.ts diff --git a/productLifecycleManagement/src/apis/model/productModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/productModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/productModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/productModel.ts diff --git a/productLifecycleManagement/src/apis/model/remodifyModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/remodifyModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/remodifyModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/remodifyModel.ts diff --git a/productLifecycleManagement/src/apis/model/repairCountModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/repairCountModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/repairCountModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/repairCountModel.ts diff --git a/productLifecycleManagement/src/apis/model/repairModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/repairModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/repairModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/repairModel.ts diff --git a/productLifecycleManagement/src/apis/model/retstockModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/retstockModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/retstockModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/retstockModel.ts diff --git a/productLifecycleManagement/src/apis/model/reworkModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/reworkModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/reworkModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/reworkModel.ts diff --git a/productLifecycleManagement/src/apis/model/roleModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/roleModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/roleModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/roleModel.ts diff --git a/productLifecycleManagement/src/apis/model/userModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/userModel.ts similarity index 85% rename from productLifecycleManagement/src/apis/model/userModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/userModel.ts index b19ef0f..da5389e 100644 --- a/productLifecycleManagement/src/apis/model/userModel.ts +++ b/Lifecycle/productLifecycleManagement/src/apis/model/userModel.ts @@ -32,6 +32,7 @@ export interface UserInfo { phone: string; roleId: number; role: object; + workhourCategories?: string[]; } interface Menu { menuId: number; @@ -53,4 +54,10 @@ export interface List { phone: string; roleId: number; role: Role; + workhourCategories?: string[]; +} + +export interface WorkhourScopeUpdateParams { + userId: number; + categories: string[]; } diff --git a/productLifecycleManagement/src/apis/model/workOrderModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/workOrderModel.ts similarity index 100% rename from productLifecycleManagement/src/apis/model/workOrderModel.ts rename to Lifecycle/productLifecycleManagement/src/apis/model/workOrderModel.ts diff --git a/Lifecycle/productLifecycleManagement/src/apis/model/workhourModel.ts b/Lifecycle/productLifecycleManagement/src/apis/model/workhourModel.ts new file mode 100644 index 0000000..f73f54d --- /dev/null +++ b/Lifecycle/productLifecycleManagement/src/apis/model/workhourModel.ts @@ -0,0 +1,140 @@ +// 工时填报、统计和工序字典模型 + +/** 工单下的产品行(填报弹窗) */ +export interface WorkhourProductModel { + workOrderCode: string; + devCode: string; + prodNo: string; + productName: string; + /** ERP 物料规格型号 */ + productMode: string; + /** 计划数量 */ + manuNum: number; + /** 已入库(dev_state 为 2/3) */ + inboundNum: number; + /** 入库差额 = 计划 - 已入库(仅工单进度参考,不是填报上限) */ + inboundDiff: number; +} + +/** 工序填报进度 */ +export interface WorkhourProgressModel { + /** 应填报量 = 计划数量 */ + manuNum: number; + /** 已填报量 = SUM(qty) */ + filledNum: number; + /** 本工序待填报量 = manuNum - filledNum */ + remainNum: number; + /** 已填报工时(分钟) */ + minutes: number; + /** 软提示,不拦截提交 */ + warnings: string[]; +} + +/** 工时记录 */ +export interface WorkhourRecord { + recordId: number; + workOrderCode?: string; + devCode?: string; + productName?: string; + productMode?: string; + mfgMonth: string; + businessSegment?: string; + category: string; + groupName: string; + processName: string; + dictType: string; + qty: number; + minutes: number; + userId: number; + workDate: string; + remark: string; + createTime: string; + devType?: { devCode: string; devTypeName: string }; + user?: { userId: number; userName: string; account: string }; +} + +/** 填报创建参数 */ +export interface WorkhourFillParams { + workOrderCode?: string; + devCode?: string; + productName?: string; + mfgMonth: string; + businessSegment: string; + category: string; + groupName: string; + processName: string; + dictType: string; + qty: number; + minutes: number; + workDate: string; + remark: string; +} + +/** 记录更新参数 */ +export interface WorkhourUpdateParams { + recordId: number; + productName?: string; + qty: number; + minutes: number; + workDate: string; + remark: string; +} + +/** 工序字典 */ +export interface DictProcess { + processId: number; + dictType: string; + category: string; + groupName: string; + processName: string; + sort: number; + isValid: boolean; +} + +/** 工序字典创建参数 */ +export interface DictProcessCreateParams { + dictType: string; + category: string; + groupName: string; + processName: string; + sort: number; +} + +/** 统计-按工单 */ +export interface WorkhourStatOrderModel { + workOrderCode: string; + devCount: number; + manuNum: number; + inboundNum: number; + inboundDiff: number; + minutes: number; + hours: number; +} + +/** 统计-按工序 */ +export interface WorkhourStatProcessModel { + dictType: string; + category: string; + groupName: string; + processName: string; + qty: number; + minutes: number; + hours: number; +} + +/** 统计-按月份 */ +export interface WorkhourStatMonthModel { + dictType: string; + mfgMonth: string; + qty: number; + minutes: number; + hours: number; +} + +/** 通用分页 */ +export interface WorkhourPage { + index: number; + size: number; + total: number; + data: T[]; +} diff --git a/productLifecycleManagement/src/apis/order.ts b/Lifecycle/productLifecycleManagement/src/apis/order.ts similarity index 100% rename from productLifecycleManagement/src/apis/order.ts rename to Lifecycle/productLifecycleManagement/src/apis/order.ts diff --git a/productLifecycleManagement/src/apis/outstock.ts b/Lifecycle/productLifecycleManagement/src/apis/outstock.ts similarity index 100% rename from productLifecycleManagement/src/apis/outstock.ts rename to Lifecycle/productLifecycleManagement/src/apis/outstock.ts diff --git a/productLifecycleManagement/src/apis/product.ts b/Lifecycle/productLifecycleManagement/src/apis/product.ts similarity index 100% rename from productLifecycleManagement/src/apis/product.ts rename to Lifecycle/productLifecycleManagement/src/apis/product.ts diff --git a/productLifecycleManagement/src/apis/remodify.ts b/Lifecycle/productLifecycleManagement/src/apis/remodify.ts similarity index 100% rename from productLifecycleManagement/src/apis/remodify.ts rename to Lifecycle/productLifecycleManagement/src/apis/remodify.ts diff --git a/productLifecycleManagement/src/apis/repair.ts b/Lifecycle/productLifecycleManagement/src/apis/repair.ts similarity index 100% rename from productLifecycleManagement/src/apis/repair.ts rename to Lifecycle/productLifecycleManagement/src/apis/repair.ts diff --git a/productLifecycleManagement/src/apis/repairCount.ts b/Lifecycle/productLifecycleManagement/src/apis/repairCount.ts similarity index 100% rename from productLifecycleManagement/src/apis/repairCount.ts rename to Lifecycle/productLifecycleManagement/src/apis/repairCount.ts diff --git a/productLifecycleManagement/src/apis/retstock.ts b/Lifecycle/productLifecycleManagement/src/apis/retstock.ts similarity index 100% rename from productLifecycleManagement/src/apis/retstock.ts rename to Lifecycle/productLifecycleManagement/src/apis/retstock.ts diff --git a/productLifecycleManagement/src/apis/rework.ts b/Lifecycle/productLifecycleManagement/src/apis/rework.ts similarity index 100% rename from productLifecycleManagement/src/apis/rework.ts rename to Lifecycle/productLifecycleManagement/src/apis/rework.ts diff --git a/productLifecycleManagement/src/apis/role.ts b/Lifecycle/productLifecycleManagement/src/apis/role.ts similarity index 100% rename from productLifecycleManagement/src/apis/role.ts rename to Lifecycle/productLifecycleManagement/src/apis/role.ts diff --git a/productLifecycleManagement/src/apis/user.ts b/Lifecycle/productLifecycleManagement/src/apis/user.ts similarity index 71% rename from productLifecycleManagement/src/apis/user.ts rename to Lifecycle/productLifecycleManagement/src/apis/user.ts index c2b373e..10b103b 100644 --- a/productLifecycleManagement/src/apis/user.ts +++ b/Lifecycle/productLifecycleManagement/src/apis/user.ts @@ -8,6 +8,7 @@ import { DeleteParams, PasswordParams, ResetPasswordParams, + WorkhourScopeUpdateParams, } from './model/userModel'; export default { // 登录 @@ -26,6 +27,18 @@ export default { async getProductionList() { return await http.get>('/api/User/ProductionList'); }, + // 工时填报范围选项 + async workhourScopeOptions() { + return await http.get>('/api/User/WorkhourScopeOptions'); + }, + // 指定人员已分配的工时填报范围 + async workhourScopeList(params: { userId: number }) { + return await http.get>('/api/User/WorkhourScopeList', params); + }, + // 保存指定人员的工时填报范围 + async updateWorkhourScopes(params: WorkhourScopeUpdateParams) { + return await http.post>('/api/User/WorkhourScopeUpdate', params); + }, // 创建用户 async create(params: CreateParams) { return await http.post>('/api/User/Create', params); diff --git a/productLifecycleManagement/src/apis/workOrder.ts b/Lifecycle/productLifecycleManagement/src/apis/workOrder.ts similarity index 100% rename from productLifecycleManagement/src/apis/workOrder.ts rename to Lifecycle/productLifecycleManagement/src/apis/workOrder.ts diff --git a/Lifecycle/productLifecycleManagement/src/apis/workhour.ts b/Lifecycle/productLifecycleManagement/src/apis/workhour.ts new file mode 100644 index 0000000..4c3ec67 --- /dev/null +++ b/Lifecycle/productLifecycleManagement/src/apis/workhour.ts @@ -0,0 +1,88 @@ +import http, { Response } from '@/utils/http'; + +import { + WorkhourProductModel, + WorkhourProgressModel, + WorkhourRecord, + WorkhourFillParams, + WorkhourUpdateParams, + DictProcess, + DictProcessCreateParams, + WorkhourStatOrderModel, + WorkhourStatProcessModel, + WorkhourStatMonthModel, + WorkhourPage, +} from './model/workhourModel'; + +export default { + // 查询工单中的产品和规格型号 + async orderProductList(params: { workOrderCode: string }) { + return await http.get>('/api/Workhour/OrderProductList', params); + }, + // 查询工序填报进度 + async processProgress(params: { + workOrderCode: string; + devCode: string; + category: string; + groupName: string; + processName: string; + qty?: number; + dictType?: string; + }) { + return await http.get>('/api/Workhour/ProcessProgress', params); + }, + // 获取可选工序 + async processList(params: { category?: string; groupName?: string; dictType?: string }) { + return await http.get>('/api/Workhour/ProcessList', params); + }, + // 分页查询工时记录 + async fillPageList(params: { + index: number; + size: number; + workOrderCode?: string; + mfgMonth?: string; + devCode?: string; + }) { + return await http.get>>('/api/Workhour/FillPageList', params); + }, + // 新增工时记录 + async fillCreate(params: WorkhourFillParams) { + return await http.post>('/api/Workhour/FillCreate', params); + }, + // 工时记录更新 + async fillUpdate(params: WorkhourUpdateParams) { + return await http.post>('/api/Workhour/FillUpdate', params); + }, + // 按年份、月份和公司板块导出工时工作簿 + async exportTemplate(params: string) { + return await http.getBlobByArr('/api/Workhour/ExportTemplate', params); + }, + // 统计-按工单 + async statOrder(params: { workOrderCode?: string; year?: string; category?: string; dictType?: string }) { + return await http.get>('/api/Workhour/StatOrder', params); + }, + // 统计-按工序 + async statProcess(params: { year?: string; category?: string; dictType?: string }) { + return await http.get>('/api/Workhour/StatProcess', params); + }, + // 统计-按月份 + async statMonth(params: { year?: string; category?: string; dictType?: string }) { + return await http.get>('/api/Workhour/StatMonth', params); + }, + // 工序字典列表 + async dictProcessList() { + return await http.get>('/api/Workhour/DictProcessList'); + }, + // 工序字典分页 + async dictProcessPageList(params: { index: number; size: number; conditions?: string }) { + return await http.get>>('/api/Workhour/DictProcessPageList', params); + }, + // 工序字典创建 + async dictProcessCreate(params: DictProcessCreateParams) { + return await http.post>('/api/Workhour/DictProcessCreate', params); + }, + // 工序字典更新 + async dictProcessUpdate(params: DictProcess) { + return await http.post>('/api/Workhour/DictProcessUpdate', params); + }, +}; diff --git a/productLifecycleManagement/src/assets/audio/abnormal-video.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/abnormal-video.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/abnormal-video.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/abnormal-video.mp3 diff --git a/productLifecycleManagement/src/assets/audio/唯一码重复.wav b/Lifecycle/productLifecycleManagement/src/assets/audio/唯一码重复.wav similarity index 100% rename from productLifecycleManagement/src/assets/audio/唯一码重复.wav rename to Lifecycle/productLifecycleManagement/src/assets/audio/唯一码重复.wav diff --git a/productLifecycleManagement/src/assets/audio/所选机型代码不存在该唯一码.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/所选机型代码不存在该唯一码.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/所选机型代码不存在该唯一码.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/所选机型代码不存在该唯一码.mp3 diff --git a/productLifecycleManagement/src/assets/audio/扫描正确的唯一码.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/扫描正确的唯一码.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/扫描正确的唯一码.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/扫描正确的唯一码.mp3 diff --git a/productLifecycleManagement/src/assets/audio/扫描正确的条形码.wav b/Lifecycle/productLifecycleManagement/src/assets/audio/扫描正确的条形码.wav similarity index 100% rename from productLifecycleManagement/src/assets/audio/扫描正确的条形码.wav rename to Lifecycle/productLifecycleManagement/src/assets/audio/扫描正确的条形码.wav diff --git a/productLifecycleManagement/src/assets/audio/操作失败.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/操作失败.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/操作失败.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/操作失败.mp3 diff --git a/productLifecycleManagement/src/assets/audio/操作成功.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/操作成功.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/操作成功.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/操作成功.mp3 diff --git a/productLifecycleManagement/src/assets/audio/无效的箱子.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/无效的箱子.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/无效的箱子.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/无效的箱子.mp3 diff --git a/productLifecycleManagement/src/assets/audio/未找到可入库的设备.wav b/Lifecycle/productLifecycleManagement/src/assets/audio/未找到可入库的设备.wav similarity index 100% rename from productLifecycleManagement/src/assets/audio/未找到可入库的设备.wav rename to Lifecycle/productLifecycleManagement/src/assets/audio/未找到可入库的设备.wav diff --git a/productLifecycleManagement/src/assets/audio/箱子不存在.wav b/Lifecycle/productLifecycleManagement/src/assets/audio/箱子不存在.wav similarity index 100% rename from productLifecycleManagement/src/assets/audio/箱子不存在.wav rename to Lifecycle/productLifecycleManagement/src/assets/audio/箱子不存在.wav diff --git a/productLifecycleManagement/src/assets/audio/箱子容量为0.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/箱子容量为0.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/箱子容量为0.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/箱子容量为0.mp3 diff --git a/productLifecycleManagement/src/assets/audio/箱子已满.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/箱子已满.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/箱子已满.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/箱子已满.mp3 diff --git a/productLifecycleManagement/src/assets/audio/获取失败.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/获取失败.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/获取失败.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/获取失败.mp3 diff --git a/productLifecycleManagement/src/assets/audio/获取成功.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/获取成功.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/获取成功.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/获取成功.mp3 diff --git a/productLifecycleManagement/src/assets/audio/设备不存在.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/设备不存在.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/设备不存在.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/设备不存在.mp3 diff --git a/productLifecycleManagement/src/assets/audio/设备已入库.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/设备已入库.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/设备已入库.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/设备已入库.mp3 diff --git a/productLifecycleManagement/src/assets/audio/设备已存在当前箱子.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/设备已存在当前箱子.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/设备已存在当前箱子.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/设备已存在当前箱子.mp3 diff --git a/productLifecycleManagement/src/assets/audio/需要唯一码.mp3 b/Lifecycle/productLifecycleManagement/src/assets/audio/需要唯一码.mp3 similarity index 100% rename from productLifecycleManagement/src/assets/audio/需要唯一码.mp3 rename to Lifecycle/productLifecycleManagement/src/assets/audio/需要唯一码.mp3 diff --git a/productLifecycleManagement/src/assets/iconfont/demo.css b/Lifecycle/productLifecycleManagement/src/assets/iconfont/demo.css similarity index 100% rename from productLifecycleManagement/src/assets/iconfont/demo.css rename to Lifecycle/productLifecycleManagement/src/assets/iconfont/demo.css diff --git a/productLifecycleManagement/src/assets/iconfont/demo_index.html b/Lifecycle/productLifecycleManagement/src/assets/iconfont/demo_index.html similarity index 100% rename from productLifecycleManagement/src/assets/iconfont/demo_index.html rename to Lifecycle/productLifecycleManagement/src/assets/iconfont/demo_index.html diff --git a/productLifecycleManagement/src/assets/iconfont/iconfont.css b/Lifecycle/productLifecycleManagement/src/assets/iconfont/iconfont.css similarity index 100% rename from productLifecycleManagement/src/assets/iconfont/iconfont.css rename to Lifecycle/productLifecycleManagement/src/assets/iconfont/iconfont.css diff --git a/productLifecycleManagement/src/assets/iconfont/iconfont.js b/Lifecycle/productLifecycleManagement/src/assets/iconfont/iconfont.js similarity index 100% rename from productLifecycleManagement/src/assets/iconfont/iconfont.js rename to Lifecycle/productLifecycleManagement/src/assets/iconfont/iconfont.js diff --git a/productLifecycleManagement/src/assets/iconfont/iconfont.json b/Lifecycle/productLifecycleManagement/src/assets/iconfont/iconfont.json similarity index 100% rename from productLifecycleManagement/src/assets/iconfont/iconfont.json rename to Lifecycle/productLifecycleManagement/src/assets/iconfont/iconfont.json diff --git a/productLifecycleManagement/src/assets/iconfont/iconfont.ttf b/Lifecycle/productLifecycleManagement/src/assets/iconfont/iconfont.ttf similarity index 100% rename from productLifecycleManagement/src/assets/iconfont/iconfont.ttf rename to Lifecycle/productLifecycleManagement/src/assets/iconfont/iconfont.ttf diff --git a/productLifecycleManagement/src/assets/iconfont/iconfont.woff b/Lifecycle/productLifecycleManagement/src/assets/iconfont/iconfont.woff similarity index 100% rename from productLifecycleManagement/src/assets/iconfont/iconfont.woff rename to Lifecycle/productLifecycleManagement/src/assets/iconfont/iconfont.woff diff --git a/productLifecycleManagement/src/assets/iconfont/iconfont.woff2 b/Lifecycle/productLifecycleManagement/src/assets/iconfont/iconfont.woff2 similarity index 100% rename from productLifecycleManagement/src/assets/iconfont/iconfont.woff2 rename to Lifecycle/productLifecycleManagement/src/assets/iconfont/iconfont.woff2 diff --git a/productLifecycleManagement/src/assets/image/product.png b/Lifecycle/productLifecycleManagement/src/assets/image/product.png similarity index 100% rename from productLifecycleManagement/src/assets/image/product.png rename to Lifecycle/productLifecycleManagement/src/assets/image/product.png diff --git a/productLifecycleManagement/src/assets/image/qrcode.png b/Lifecycle/productLifecycleManagement/src/assets/image/qrcode.png similarity index 100% rename from productLifecycleManagement/src/assets/image/qrcode.png rename to Lifecycle/productLifecycleManagement/src/assets/image/qrcode.png diff --git a/productLifecycleManagement/src/assets/image/search-icon.png b/Lifecycle/productLifecycleManagement/src/assets/image/search-icon.png similarity index 100% rename from productLifecycleManagement/src/assets/image/search-icon.png rename to Lifecycle/productLifecycleManagement/src/assets/image/search-icon.png diff --git a/productLifecycleManagement/src/assets/image/入库.png b/Lifecycle/productLifecycleManagement/src/assets/image/入库.png similarity index 100% rename from productLifecycleManagement/src/assets/image/入库.png rename to Lifecycle/productLifecycleManagement/src/assets/image/入库.png diff --git a/productLifecycleManagement/src/assets/image/出库.png b/Lifecycle/productLifecycleManagement/src/assets/image/出库.png similarity index 100% rename from productLifecycleManagement/src/assets/image/出库.png rename to Lifecycle/productLifecycleManagement/src/assets/image/出库.png diff --git a/productLifecycleManagement/src/assets/image/异常GUID@1x.png b/Lifecycle/productLifecycleManagement/src/assets/image/异常GUID@1x.png similarity index 100% rename from productLifecycleManagement/src/assets/image/异常GUID@1x.png rename to Lifecycle/productLifecycleManagement/src/assets/image/异常GUID@1x.png diff --git a/productLifecycleManagement/src/assets/image/扫描.png b/Lifecycle/productLifecycleManagement/src/assets/image/扫描.png similarity index 100% rename from productLifecycleManagement/src/assets/image/扫描.png rename to Lifecycle/productLifecycleManagement/src/assets/image/扫描.png diff --git a/productLifecycleManagement/src/assets/image/暂无.png b/Lifecycle/productLifecycleManagement/src/assets/image/暂无.png similarity index 100% rename from productLifecycleManagement/src/assets/image/暂无.png rename to Lifecycle/productLifecycleManagement/src/assets/image/暂无.png diff --git a/productLifecycleManagement/src/assets/image/查询.png b/Lifecycle/productLifecycleManagement/src/assets/image/查询.png similarity index 100% rename from productLifecycleManagement/src/assets/image/查询.png rename to Lifecycle/productLifecycleManagement/src/assets/image/查询.png diff --git a/productLifecycleManagement/src/assets/image/标识.png b/Lifecycle/productLifecycleManagement/src/assets/image/标识.png similarity index 100% rename from productLifecycleManagement/src/assets/image/标识.png rename to Lifecycle/productLifecycleManagement/src/assets/image/标识.png diff --git a/productLifecycleManagement/src/assets/image/用户.png b/Lifecycle/productLifecycleManagement/src/assets/image/用户.png similarity index 100% rename from productLifecycleManagement/src/assets/image/用户.png rename to Lifecycle/productLifecycleManagement/src/assets/image/用户.png diff --git a/productLifecycleManagement/src/assets/image/组 32.png b/Lifecycle/productLifecycleManagement/src/assets/image/组 32.png similarity index 100% rename from productLifecycleManagement/src/assets/image/组 32.png rename to Lifecycle/productLifecycleManagement/src/assets/image/组 32.png diff --git a/productLifecycleManagement/src/assets/image/维修.png b/Lifecycle/productLifecycleManagement/src/assets/image/维修.png similarity index 100% rename from productLifecycleManagement/src/assets/image/维修.png rename to Lifecycle/productLifecycleManagement/src/assets/image/维修.png diff --git a/productLifecycleManagement/src/assets/image/详情.png b/Lifecycle/productLifecycleManagement/src/assets/image/详情.png similarity index 100% rename from productLifecycleManagement/src/assets/image/详情.png rename to Lifecycle/productLifecycleManagement/src/assets/image/详情.png diff --git a/productLifecycleManagement/src/assets/image/路径.png b/Lifecycle/productLifecycleManagement/src/assets/image/路径.png similarity index 100% rename from productLifecycleManagement/src/assets/image/路径.png rename to Lifecycle/productLifecycleManagement/src/assets/image/路径.png diff --git a/productLifecycleManagement/src/assets/image/返工.png b/Lifecycle/productLifecycleManagement/src/assets/image/返工.png similarity index 100% rename from productLifecycleManagement/src/assets/image/返工.png rename to Lifecycle/productLifecycleManagement/src/assets/image/返工.png diff --git a/productLifecycleManagement/src/assets/image/退货.png b/Lifecycle/productLifecycleManagement/src/assets/image/退货.png similarity index 100% rename from productLifecycleManagement/src/assets/image/退货.png rename to Lifecycle/productLifecycleManagement/src/assets/image/退货.png diff --git a/productLifecycleManagement/src/assets/styles/index.scss b/Lifecycle/productLifecycleManagement/src/assets/styles/index.scss similarity index 100% rename from productLifecycleManagement/src/assets/styles/index.scss rename to Lifecycle/productLifecycleManagement/src/assets/styles/index.scss diff --git a/productLifecycleManagement/src/assets/vue.svg b/Lifecycle/productLifecycleManagement/src/assets/vue.svg similarity index 100% rename from productLifecycleManagement/src/assets/vue.svg rename to Lifecycle/productLifecycleManagement/src/assets/vue.svg diff --git a/productLifecycleManagement/src/auto-import.d.ts b/Lifecycle/productLifecycleManagement/src/auto-import.d.ts similarity index 100% rename from productLifecycleManagement/src/auto-import.d.ts rename to Lifecycle/productLifecycleManagement/src/auto-import.d.ts diff --git a/productLifecycleManagement/src/components/CommonAside.vue b/Lifecycle/productLifecycleManagement/src/components/CommonAside.vue similarity index 100% rename from productLifecycleManagement/src/components/CommonAside.vue rename to Lifecycle/productLifecycleManagement/src/components/CommonAside.vue diff --git a/productLifecycleManagement/src/components/CommonHeader.vue b/Lifecycle/productLifecycleManagement/src/components/CommonHeader.vue similarity index 100% rename from productLifecycleManagement/src/components/CommonHeader.vue rename to Lifecycle/productLifecycleManagement/src/components/CommonHeader.vue diff --git a/productLifecycleManagement/src/components/DeviceDetail.vue b/Lifecycle/productLifecycleManagement/src/components/DeviceDetail.vue similarity index 100% rename from productLifecycleManagement/src/components/DeviceDetail.vue rename to Lifecycle/productLifecycleManagement/src/components/DeviceDetail.vue diff --git a/productLifecycleManagement/src/layout/index.vue b/Lifecycle/productLifecycleManagement/src/layout/index.vue similarity index 100% rename from productLifecycleManagement/src/layout/index.vue rename to Lifecycle/productLifecycleManagement/src/layout/index.vue diff --git a/productLifecycleManagement/src/main.ts b/Lifecycle/productLifecycleManagement/src/main.ts similarity index 75% rename from productLifecycleManagement/src/main.ts rename to Lifecycle/productLifecycleManagement/src/main.ts index 7b7e229..31059f6 100644 --- a/productLifecycleManagement/src/main.ts +++ b/Lifecycle/productLifecycleManagement/src/main.ts @@ -12,6 +12,13 @@ import 'normalize.css'; import { printPlugin } from 'vue-print-next'; const app = createApp(App); +// 工时独立 demo 复用当前系统会话,并调用主应用配置的 API 域名。 +const configuredApiUrl = new URL(import.meta.env.VITE_APP_API_BASE_URL || '/', window.location.origin); +sessionStorage.setItem( + 'lifecycleApiBaseUrl', + configuredApiUrl.origin, +); + for (const [key, component] of Object.entries(ElementPlusIconsVue)) { app.component(key, component); } diff --git a/productLifecycleManagement/src/pages/box/index.vue b/Lifecycle/productLifecycleManagement/src/pages/box/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/box/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/box/index.vue diff --git a/productLifecycleManagement/src/pages/box/types/index.ts b/Lifecycle/productLifecycleManagement/src/pages/box/types/index.ts similarity index 100% rename from productLifecycleManagement/src/pages/box/types/index.ts rename to Lifecycle/productLifecycleManagement/src/pages/box/types/index.ts diff --git a/productLifecycleManagement/src/pages/createOrderContract/index.vue b/Lifecycle/productLifecycleManagement/src/pages/createOrderContract/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/createOrderContract/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/createOrderContract/index.vue diff --git a/productLifecycleManagement/src/pages/createOrderContract/types/index.ts b/Lifecycle/productLifecycleManagement/src/pages/createOrderContract/types/index.ts similarity index 100% rename from productLifecycleManagement/src/pages/createOrderContract/types/index.ts rename to Lifecycle/productLifecycleManagement/src/pages/createOrderContract/types/index.ts diff --git a/productLifecycleManagement/src/pages/deviceStatistics/customDetail.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customDetail.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/customDetail.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customDetail.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/classifiedStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/classifiedStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/customEcharts/classifiedStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/classifiedStatistics.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/customerRanking.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/customerRanking.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/customEcharts/customerRanking.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/customerRanking.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/deviceModel.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/deviceModel.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/customEcharts/deviceModel.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/deviceModel.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/disposalMethod.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/disposalMethod.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/customEcharts/disposalMethod.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/disposalMethod.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/faultStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/faultStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/customEcharts/faultStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/faultStatistics.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/overinsuredStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/overinsuredStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/customEcharts/overinsuredStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/overinsuredStatistics.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/repairStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/repairStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/customEcharts/repairStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/repairStatistics.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/tagStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/tagStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/customEcharts/tagStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customEcharts/tagStatistics.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/customRepair.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customRepair.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/customRepair.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/customRepair.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/factoryDetail.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryDetail.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/factoryDetail.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryDetail.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/badPointStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/badPointStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/badPointStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/badPointStatistics.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/causeAnalysis.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/causeAnalysis.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/causeAnalysis.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/causeAnalysis.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/classifiedStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/classifiedStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/classifiedStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/classifiedStatistics.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/componentModel.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/componentModel.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/componentModel.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/componentModel.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/faultStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/faultStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/faultStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/faultStatistics.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/finishedProductCategory.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/finishedProductCategory.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/finishedProductCategory.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/finishedProductCategory.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/plugInPatch.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/plugInPatch.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/plugInPatch.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/plugInPatch.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/repairStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/repairStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/repairStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/repairStatistics.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/stationStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/stationStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/stationStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/stationStatistics.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/tagStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/tagStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/tagStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryEcharts/tagStatistics.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/factoryRepair.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryRepair.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/factoryRepair.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/factoryRepair.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/repairStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/repairStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/repairStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/repairStatistics.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/rewardPunishmentDetail.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/rewardPunishmentDetail.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/rewardPunishmentDetail.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/rewardPunishmentDetail.vue diff --git a/productLifecycleManagement/src/pages/deviceStatistics/rewardPunishmentStatistics.vue b/Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/rewardPunishmentStatistics.vue similarity index 100% rename from productLifecycleManagement/src/pages/deviceStatistics/rewardPunishmentStatistics.vue rename to Lifecycle/productLifecycleManagement/src/pages/deviceStatistics/rewardPunishmentStatistics.vue diff --git a/productLifecycleManagement/src/pages/devicequery/index.vue b/Lifecycle/productLifecycleManagement/src/pages/devicequery/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/devicequery/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/devicequery/index.vue diff --git a/productLifecycleManagement/src/pages/devicequery/types/index.ts b/Lifecycle/productLifecycleManagement/src/pages/devicequery/types/index.ts similarity index 100% rename from productLifecycleManagement/src/pages/devicequery/types/index.ts rename to Lifecycle/productLifecycleManagement/src/pages/devicequery/types/index.ts diff --git a/productLifecycleManagement/src/pages/equipmentModification/index.vue b/Lifecycle/productLifecycleManagement/src/pages/equipmentModification/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/equipmentModification/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/equipmentModification/index.vue diff --git a/productLifecycleManagement/src/pages/instock/index.vue b/Lifecycle/productLifecycleManagement/src/pages/instock/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/instock/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/instock/index.vue diff --git a/productLifecycleManagement/src/pages/instock/types/index.ts b/Lifecycle/productLifecycleManagement/src/pages/instock/types/index.ts similarity index 100% rename from productLifecycleManagement/src/pages/instock/types/index.ts rename to Lifecycle/productLifecycleManagement/src/pages/instock/types/index.ts diff --git a/productLifecycleManagement/src/pages/login/index.vue b/Lifecycle/productLifecycleManagement/src/pages/login/index.vue similarity index 58% rename from productLifecycleManagement/src/pages/login/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/login/index.vue index a337af7..549643d 100644 --- a/productLifecycleManagement/src/pages/login/index.vue +++ b/Lifecycle/productLifecycleManagement/src/pages/login/index.vue @@ -20,12 +20,15 @@ diff --git a/productLifecycleManagement/src/pages/login/types/index.ts b/Lifecycle/productLifecycleManagement/src/pages/login/types/index.ts similarity index 100% rename from productLifecycleManagement/src/pages/login/types/index.ts rename to Lifecycle/productLifecycleManagement/src/pages/login/types/index.ts diff --git a/productLifecycleManagement/src/pages/logisticsInfoCheck/index.vue b/Lifecycle/productLifecycleManagement/src/pages/logisticsInfoCheck/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/logisticsInfoCheck/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/logisticsInfoCheck/index.vue diff --git a/productLifecycleManagement/src/pages/outstock/index.vue b/Lifecycle/productLifecycleManagement/src/pages/outstock/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/outstock/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/outstock/index.vue diff --git a/productLifecycleManagement/src/pages/outstock/types/index.ts b/Lifecycle/productLifecycleManagement/src/pages/outstock/types/index.ts similarity index 100% rename from productLifecycleManagement/src/pages/outstock/types/index.ts rename to Lifecycle/productLifecycleManagement/src/pages/outstock/types/index.ts diff --git a/productLifecycleManagement/src/pages/product/editPackage.vue b/Lifecycle/productLifecycleManagement/src/pages/product/editPackage.vue similarity index 100% rename from productLifecycleManagement/src/pages/product/editPackage.vue rename to Lifecycle/productLifecycleManagement/src/pages/product/editPackage.vue diff --git a/productLifecycleManagement/src/pages/product/editProduct.vue b/Lifecycle/productLifecycleManagement/src/pages/product/editProduct.vue similarity index 100% rename from productLifecycleManagement/src/pages/product/editProduct.vue rename to Lifecycle/productLifecycleManagement/src/pages/product/editProduct.vue diff --git a/productLifecycleManagement/src/pages/product/index.vue b/Lifecycle/productLifecycleManagement/src/pages/product/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/product/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/product/index.vue diff --git a/productLifecycleManagement/src/pages/product/types/index.ts b/Lifecycle/productLifecycleManagement/src/pages/product/types/index.ts similarity index 100% rename from productLifecycleManagement/src/pages/product/types/index.ts rename to Lifecycle/productLifecycleManagement/src/pages/product/types/index.ts diff --git a/productLifecycleManagement/src/pages/repair/children/components/editDialog.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/components/editDialog.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/components/editDialog.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/components/editDialog.vue diff --git a/productLifecycleManagement/src/pages/repair/children/components/failureAnalysis.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/components/failureAnalysis.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/components/failureAnalysis.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/components/failureAnalysis.vue diff --git a/productLifecycleManagement/src/pages/repair/children/components/failureAppearance.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/components/failureAppearance.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/components/failureAppearance.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/components/failureAppearance.vue diff --git a/productLifecycleManagement/src/pages/repair/children/components/failureCategory.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/components/failureCategory.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/components/failureCategory.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/components/failureCategory.vue diff --git a/productLifecycleManagement/src/pages/repair/children/components/failureChip.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/components/failureChip.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/components/failureChip.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/components/failureChip.vue diff --git a/productLifecycleManagement/src/pages/repair/children/components/failureProcess.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/components/failureProcess.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/components/failureProcess.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/components/failureProcess.vue diff --git a/productLifecycleManagement/src/pages/repair/children/components/failureWorkstation.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/components/failureWorkstation.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/components/failureWorkstation.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/components/failureWorkstation.vue diff --git a/productLifecycleManagement/src/pages/repair/children/components/faultConfirmation.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/components/faultConfirmation.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/components/faultConfirmation.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/components/faultConfirmation.vue diff --git a/productLifecycleManagement/src/pages/repair/children/components/finproductCategory.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/components/finproductCategory.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/components/finproductCategory.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/components/finproductCategory.vue diff --git a/productLifecycleManagement/src/pages/repair/children/components/repairCategory.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/components/repairCategory.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/components/repairCategory.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/components/repairCategory.vue diff --git a/productLifecycleManagement/src/pages/repair/children/components/requestList.js b/Lifecycle/productLifecycleManagement/src/pages/repair/children/components/requestList.js similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/components/requestList.js rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/components/requestList.js diff --git a/productLifecycleManagement/src/pages/repair/children/editPrice.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/editPrice.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/editPrice.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/editPrice.vue diff --git a/productLifecycleManagement/src/pages/repair/children/getList.ts b/Lifecycle/productLifecycleManagement/src/pages/repair/children/getList.ts similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/getList.ts rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/getList.ts diff --git a/productLifecycleManagement/src/pages/repair/children/rapairPrice.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/rapairPrice.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/rapairPrice.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/rapairPrice.vue diff --git a/productLifecycleManagement/src/pages/repair/children/repairCustomRepair.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/repairCustomRepair.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/repairCustomRepair.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/repairCustomRepair.vue diff --git a/productLifecycleManagement/src/pages/repair/children/repairDictMamage.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/repairDictMamage.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/repairDictMamage.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/repairDictMamage.vue diff --git a/productLifecycleManagement/src/pages/repair/children/repairFactoryRepair.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/children/repairFactoryRepair.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/children/repairFactoryRepair.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/children/repairFactoryRepair.vue diff --git a/productLifecycleManagement/src/pages/repair/index.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/index.vue diff --git a/productLifecycleManagement/src/pages/repair/repairDialog.vue b/Lifecycle/productLifecycleManagement/src/pages/repair/repairDialog.vue similarity index 100% rename from productLifecycleManagement/src/pages/repair/repairDialog.vue rename to Lifecycle/productLifecycleManagement/src/pages/repair/repairDialog.vue diff --git a/productLifecycleManagement/src/pages/repair/types/index.ts b/Lifecycle/productLifecycleManagement/src/pages/repair/types/index.ts similarity index 100% rename from productLifecycleManagement/src/pages/repair/types/index.ts rename to Lifecycle/productLifecycleManagement/src/pages/repair/types/index.ts diff --git a/productLifecycleManagement/src/pages/retstock/index.vue b/Lifecycle/productLifecycleManagement/src/pages/retstock/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/retstock/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/retstock/index.vue diff --git a/productLifecycleManagement/src/pages/retstock/retstockDialog.vue b/Lifecycle/productLifecycleManagement/src/pages/retstock/retstockDialog.vue similarity index 100% rename from productLifecycleManagement/src/pages/retstock/retstockDialog.vue rename to Lifecycle/productLifecycleManagement/src/pages/retstock/retstockDialog.vue diff --git a/productLifecycleManagement/src/pages/retstock/types/index.ts b/Lifecycle/productLifecycleManagement/src/pages/retstock/types/index.ts similarity index 100% rename from productLifecycleManagement/src/pages/retstock/types/index.ts rename to Lifecycle/productLifecycleManagement/src/pages/retstock/types/index.ts diff --git a/productLifecycleManagement/src/pages/rework/index.vue b/Lifecycle/productLifecycleManagement/src/pages/rework/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/rework/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/rework/index.vue diff --git a/productLifecycleManagement/src/pages/softDictionaryMaintenance/index.vue b/Lifecycle/productLifecycleManagement/src/pages/softDictionaryMaintenance/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/softDictionaryMaintenance/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/softDictionaryMaintenance/index.vue diff --git a/productLifecycleManagement/src/pages/user/index.vue b/Lifecycle/productLifecycleManagement/src/pages/user/index.vue similarity index 100% rename from productLifecycleManagement/src/pages/user/index.vue rename to Lifecycle/productLifecycleManagement/src/pages/user/index.vue diff --git a/productLifecycleManagement/src/pages/user/roleManage.vue b/Lifecycle/productLifecycleManagement/src/pages/user/roleManage.vue similarity index 100% rename from productLifecycleManagement/src/pages/user/roleManage.vue rename to Lifecycle/productLifecycleManagement/src/pages/user/roleManage.vue diff --git a/productLifecycleManagement/src/pages/user/types/index.ts b/Lifecycle/productLifecycleManagement/src/pages/user/types/index.ts similarity index 100% rename from productLifecycleManagement/src/pages/user/types/index.ts rename to Lifecycle/productLifecycleManagement/src/pages/user/types/index.ts diff --git a/productLifecycleManagement/src/pages/user/userManage.vue b/Lifecycle/productLifecycleManagement/src/pages/user/userManage.vue similarity index 64% rename from productLifecycleManagement/src/pages/user/userManage.vue rename to Lifecycle/productLifecycleManagement/src/pages/user/userManage.vue index 9fc3394..8e623ab 100644 --- a/productLifecycleManagement/src/pages/user/userManage.vue +++ b/Lifecycle/productLifecycleManagement/src/pages/user/userManage.vue @@ -11,10 +11,19 @@ {{ scope.row.role?.roleName }} - + + + + + + diff --git a/Lifecycle/productLifecycleManagement/src/pages/workhour/processDict.vue b/Lifecycle/productLifecycleManagement/src/pages/workhour/processDict.vue new file mode 100644 index 0000000..fb81c1b --- /dev/null +++ b/Lifecycle/productLifecycleManagement/src/pages/workhour/processDict.vue @@ -0,0 +1,256 @@ + + + + + diff --git a/Lifecycle/productLifecycleManagement/src/pages/workhour/stat.vue b/Lifecycle/productLifecycleManagement/src/pages/workhour/stat.vue new file mode 100644 index 0000000..afc7131 --- /dev/null +++ b/Lifecycle/productLifecycleManagement/src/pages/workhour/stat.vue @@ -0,0 +1,436 @@ + + + + + diff --git a/Lifecycle/productLifecycleManagement/src/permission.ts b/Lifecycle/productLifecycleManagement/src/permission.ts new file mode 100644 index 0000000..5dde622 --- /dev/null +++ b/Lifecycle/productLifecycleManagement/src/permission.ts @@ -0,0 +1,38 @@ +import router from "./router"; + +const whiteList = ["/login"]; // no redirect whitelist +const workhourPaths = new Set(["/workhour", "/workhourStat", "/workhourProcess"]); +router.beforeEach(async (to, from, next) => { + console.log(from); + const storage: string | null = sessionStorage.getItem( + "lifecycleStorage" + ); + const storeUserInfo = storage ? JSON.parse(storage) : null; + const hasToken = storeUserInfo && storeUserInfo.token; + if (hasToken) { + const userInfo = storeUserInfo.userInfo; + const hasWorkhourScope = Boolean(userInfo?.workhourCategories?.length); + const canManageProcessDictionary = (userInfo?.roleId ?? Number.MAX_SAFE_INTEGER) < 3; + const workhourRouteDenied = workhourPaths.has(to.path) + && (to.path === "/workhourProcess" + ? !canManageProcessDictionary + : !hasWorkhourScope); + if (workhourRouteDenied) { + const roleMenus = storeUserInfo.userInfo?.role?.menus as + | Array<{ leadId: number; menuUrl: string }> + | undefined; + const fallbackMenu = roleMenus?.find((item) => { + return item.leadId === 0 && !item.menuUrl.includes("/reserve") && !item.menuUrl.startsWith("/workhour"); + }); + next(fallbackMenu?.menuUrl || "/login"); + return; + } + next(); + } else { + if (whiteList.indexOf(to.path) !== -1) { + next(); + } else { + next(`/login`); + } + } +}); diff --git a/productLifecycleManagement/src/router/index.ts b/Lifecycle/productLifecycleManagement/src/router/index.ts similarity index 90% rename from productLifecycleManagement/src/router/index.ts rename to Lifecycle/productLifecycleManagement/src/router/index.ts index c35876d..f9dd5c3 100644 --- a/productLifecycleManagement/src/router/index.ts +++ b/Lifecycle/productLifecycleManagement/src/router/index.ts @@ -6,7 +6,7 @@ const router = createRouter({ history: createWebHashHistory(), // history 模式则使用 createWebHistory() routes, }); -router.beforeEach((to, from, next) => { +router.beforeEach((to, _from, next) => { /* 路由发生变化修改页面title */ if (typeof to.meta.title === 'string') { document.title = to.meta.title; diff --git a/productLifecycleManagement/src/router/routes.ts b/Lifecycle/productLifecycleManagement/src/router/routes.ts similarity index 91% rename from productLifecycleManagement/src/router/routes.ts rename to Lifecycle/productLifecycleManagement/src/router/routes.ts index dd6cf75..b1d798d 100644 --- a/productLifecycleManagement/src/router/routes.ts +++ b/Lifecycle/productLifecycleManagement/src/router/routes.ts @@ -110,6 +110,30 @@ export const routes: Array = [ }, component: () => import('@/pages/user/index.vue'), }, + { + path: '/workhour', + name: 'workhour', + meta: { + title: '工时填报', + }, + component: () => import('@/pages/workhour/index.vue'), + }, + { + path: '/workhourStat', + name: 'workhourStat', + meta: { + title: '工时统计', + }, + component: () => import('@/pages/workhour/stat.vue'), + }, + { + path: '/workhourProcess', + name: 'workhourProcess', + meta: { + title: '工序字典', + }, + component: () => import('@/pages/workhour/processDict.vue'), + }, { path: '/workOrder', name: 'workOrder', diff --git a/productLifecycleManagement/src/store/index.ts b/Lifecycle/productLifecycleManagement/src/store/index.ts similarity index 100% rename from productLifecycleManagement/src/store/index.ts rename to Lifecycle/productLifecycleManagement/src/store/index.ts diff --git a/productLifecycleManagement/src/store/modules/user/index.ts b/Lifecycle/productLifecycleManagement/src/store/modules/user/index.ts similarity index 100% rename from productLifecycleManagement/src/store/modules/user/index.ts rename to Lifecycle/productLifecycleManagement/src/store/modules/user/index.ts diff --git a/productLifecycleManagement/src/style.css b/Lifecycle/productLifecycleManagement/src/style.css similarity index 100% rename from productLifecycleManagement/src/style.css rename to Lifecycle/productLifecycleManagement/src/style.css diff --git a/productLifecycleManagement/src/typings.d.ts b/Lifecycle/productLifecycleManagement/src/typings.d.ts similarity index 100% rename from productLifecycleManagement/src/typings.d.ts rename to Lifecycle/productLifecycleManagement/src/typings.d.ts diff --git a/productLifecycleManagement/src/utils/http/index.ts b/Lifecycle/productLifecycleManagement/src/utils/http/index.ts similarity index 96% rename from productLifecycleManagement/src/utils/http/index.ts rename to Lifecycle/productLifecycleManagement/src/utils/http/index.ts index b9f46df..99f1430 100644 --- a/productLifecycleManagement/src/utils/http/index.ts +++ b/Lifecycle/productLifecycleManagement/src/utils/http/index.ts @@ -2,7 +2,7 @@ import service, { AxiosRequestConfig } from './request'; export * from './types'; export const request = (config: AxiosRequestConfig): Promise => { - return new Promise((resolve) => { + return new Promise((resolve, reject) => { service .request(config) .then((res) => { @@ -11,6 +11,7 @@ export const request = (config: AxiosRequestConfig): Promise => { }) .catch((err) => { console.log('request fail:', err); + reject(err); }); }); }; diff --git a/productLifecycleManagement/src/utils/http/request.ts b/Lifecycle/productLifecycleManagement/src/utils/http/request.ts similarity index 83% rename from productLifecycleManagement/src/utils/http/request.ts rename to Lifecycle/productLifecycleManagement/src/utils/http/request.ts index e369a2f..ff072e0 100644 --- a/productLifecycleManagement/src/utils/http/request.ts +++ b/Lifecycle/productLifecycleManagement/src/utils/http/request.ts @@ -6,10 +6,13 @@ const { updateToken, updateUserInfo } = userStore; axios.defaults.timeout = 1000 * 30; +const configuredApiBaseUrl = import.meta.env.VITE_APP_API_BASE_URL || '/'; +const normalizedApiBaseUrl = configuredApiBaseUrl.replace(/\/+$/, '').replace(/\/api$/i, '') || '/'; + // 创建axios实例 const service = axios.create({ - // 根据不同env设置不同的baseURL - baseURL: import.meta.env.VITE_APP_API_BASE_URL, + // API paths already contain /api; normalize legacy env values such as /api to avoid /api/api/... . + baseURL: normalizedApiBaseUrl, }); // axios实例拦截请求 @@ -31,6 +34,9 @@ service.interceptors.response.use( (response: AxiosResponse) => { // response.data就是后端返回的数据,结构根据你们的约定来定义 const res = response.data; + if (response.config.responseType === 'blob' || res instanceof Blob) { + return res; + } if (res.code !== 0) { let messages = res.msg; if (res.code === 1 || res.code === -1) { diff --git a/productLifecycleManagement/src/utils/http/types.ts b/Lifecycle/productLifecycleManagement/src/utils/http/types.ts similarity index 100% rename from productLifecycleManagement/src/utils/http/types.ts rename to Lifecycle/productLifecycleManagement/src/utils/http/types.ts diff --git a/productLifecycleManagement/src/utils/index.js b/Lifecycle/productLifecycleManagement/src/utils/index.js similarity index 100% rename from productLifecycleManagement/src/utils/index.js rename to Lifecycle/productLifecycleManagement/src/utils/index.js diff --git a/productLifecycleManagement/src/utils/speak-tts.js b/Lifecycle/productLifecycleManagement/src/utils/speak-tts.js similarity index 100% rename from productLifecycleManagement/src/utils/speak-tts.js rename to Lifecycle/productLifecycleManagement/src/utils/speak-tts.js diff --git a/productLifecycleManagement/src/vite-env.d.ts b/Lifecycle/productLifecycleManagement/src/vite-env.d.ts similarity index 100% rename from productLifecycleManagement/src/vite-env.d.ts rename to Lifecycle/productLifecycleManagement/src/vite-env.d.ts diff --git a/productLifecycleManagement/tsconfig.json b/Lifecycle/productLifecycleManagement/tsconfig.json similarity index 100% rename from productLifecycleManagement/tsconfig.json rename to Lifecycle/productLifecycleManagement/tsconfig.json diff --git a/productLifecycleManagement/tsconfig.node.json b/Lifecycle/productLifecycleManagement/tsconfig.node.json similarity index 100% rename from productLifecycleManagement/tsconfig.node.json rename to Lifecycle/productLifecycleManagement/tsconfig.node.json diff --git a/productLifecycleManagement/vite.config.ts b/Lifecycle/productLifecycleManagement/vite.config.ts similarity index 86% rename from productLifecycleManagement/vite.config.ts rename to Lifecycle/productLifecycleManagement/vite.config.ts index 2765202..97f3358 100644 --- a/productLifecycleManagement/vite.config.ts +++ b/Lifecycle/productLifecycleManagement/vite.config.ts @@ -38,11 +38,21 @@ export default ({ mode }) => { open: true, https: false, proxy: { + // 后端控制器统一使用 /api/[controller]/[action] 路由,保留 /api 前缀。 + '/api/Workhour': { + target: 'http://127.0.0.1:120/', + changeOrigin: true, + ws: true, + }, + '/api/User/WorkhourScope': { + target: 'http://127.0.0.1:120/', + changeOrigin: true, + ws: true, + }, '/api': { target: 'http://127.0.0.1:120/', changeOrigin: true, ws: true, - rewrite: (path: string) => path.replace(/^\/api/, ''), }, }, }, @@ -74,4 +84,4 @@ export default ({ mode }) => { }, }, }); -}; \ No newline at end of file +}; diff --git a/productLifecycleManagement/web.bat b/Lifecycle/productLifecycleManagement/web.bat similarity index 100% rename from productLifecycleManagement/web.bat rename to Lifecycle/productLifecycleManagement/web.bat diff --git a/productLifecycleManagement/yarn.lock b/Lifecycle/productLifecycleManagement/yarn.lock similarity index 100% rename from productLifecycleManagement/yarn.lock rename to Lifecycle/productLifecycleManagement/yarn.lock diff --git a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SubmWorkorderHelper.cs b/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SubmWorkorderHelper.cs deleted file mode 100644 index 73b1c4f..0000000 --- a/SK_ERP_WebService/SK_ERP_WebService/Jdy/Helper/SubmWorkorderHelper.cs +++ /dev/null @@ -1,205 +0,0 @@ -using Newtonsoft.Json; -using SK_ERP_WebService.Jdy.Interfaces; -using SK_ERP_WebService.Jdy.Util; -using System.Net; - -namespace SK_ERP_WebService.Jdy.Helper -{ - public class SubmWorkorderHelper - { - private const string UrlForGetDetial = "/jdy/v2/pm/subm_workorder_detail"; - private const string UrlForGetList = "/jdy/v2/pm/subm_workorder"; - private const string GetDetialHttpMethod = WebRequestMethods.Http.Get; - private const string GetListHttpMethod = WebRequestMethods.Http.Get; - - public static bool GetList(IToken token, int page, int pageSize, string? beginTime, string? endTime, ref ErrorMessage msg) - { - string paramValue = $"begin_date={beginTime}&end_date={endTime}&page={page}&page_size={pageSize}"; - string? url = token.GetUrl(UrlForGetList, paramValue); - string result = string.Empty; - string httpText = SignHelper.CreateHttpText(GetListHttpMethod, UrlForGetList, paramValue); - if (!RequestHelper.Request(url, httpText, ref result, GetListHttpMethod, true)) - { - msg = new ErrorMessage(ErrorMessage.ExceptionCode, result); - } - else if (ErrorMessage.IsErrorMessage(result)) - { - msg = ErrorMessage.Parse(result); - } - else - { - try - { - var obj = JsonConvert.DeserializeAnonymousType(result, new - { - errcode = 0, - description = "", - data = new - { - count = 0, - total_page = 0, - cur_page_size = 0, - page_size = 0, - page = 0, - rows = new List() - } - }); - - List list = []; - if (obj != null) - { - foreach (var item in obj.data.rows) - { - if (item != null) - { - ErrorMessage msg2 = new(ErrorMessage.ExceptionCode, ""); - if (GetDetail(token, item.BillNo, ref msg2)) - { - var subm = msg2.Data as SubmWorkorderRow; - subm?.Materials?.ForEach(it => it.SubMaterials = null); - list.Add(subm); - } - } - } - msg = new ErrorMessage(0, "从服务器获取响应成功.", new SubmWorkorderPage { List = list, Count = obj.data.count, PageIndex = obj.data.page, TotalPage = obj.data.total_page }); - return true; - } - - } - catch (Exception ex) - { - msg = new ErrorMessage(ex); - } - } - return false; - } - - public static bool GetDetail(IToken token, string? number, ref ErrorMessage msg) - { - if (!String.IsNullOrEmpty(number)) - { - string numberE = Uri.EscapeDataString(number); - string? url = token.GetUrl(UrlForGetDetial, string.Format("number={0}", numberE)); - string result = string.Empty; - string httpText = SignHelper.CreateHttpText(GetDetialHttpMethod, UrlForGetDetial, string.Format("number={0}", Uri.EscapeDataString(numberE))); - if (!RequestHelper.Request(url, httpText, ref result, GetDetialHttpMethod, true)) - { - msg = new ErrorMessage(ErrorMessage.ExceptionCode, result); - } - else if (ErrorMessage.IsErrorMessage(result)) - { - msg = ErrorMessage.Parse(result); - } - else - { - try - { - var obj = JsonConvert.DeserializeAnonymousType(result, new - { - errcode = 0, - description = "", - data = new SubmWorkorderRow() - }); - if (obj != null) - { - msg = new ErrorMessage(0, "从服务器获取响应成功.", obj.data); - return true; - } - } - catch (Exception ex) - { - msg = new ErrorMessage(ex); - } - } - } - return false; - } - public static bool KitMatchingAnalysis(IToken token, string? number, string? devCode, ref ErrorMessage msg) - { - if (!String.IsNullOrEmpty(number)) - { - string numberE = Uri.EscapeDataString(number); - string? url = token.GetUrl(UrlForGetDetial, string.Format("number={0}", numberE)); - string result = string.Empty; - string httpText = SignHelper.CreateHttpText(GetDetialHttpMethod, UrlForGetDetial, string.Format("number={0}", Uri.EscapeDataString(numberE))); - if (!RequestHelper.Request(url, httpText, ref result, GetDetialHttpMethod, true)) - { - msg = new ErrorMessage(ErrorMessage.ExceptionCode, result); - } - else if (ErrorMessage.IsErrorMessage(result)) - { - msg = ErrorMessage.Parse(result); - } - else - { - try - { - var obj = JsonConvert.DeserializeAnonymousType(result, new - { - errcode = 0, - description = "", - data = new SubmWorkorderRow() - }); - if (obj != null) - { - var list = new List(); - obj.data.Materials?.ForEach(it1 => - { - if (!string.IsNullOrEmpty(devCode)) - { - if (it1.DeviceCode != devCode) - { - return; - } - } - it1.SubMaterials?.ForEach(item => - { - item.DeviceCode = it1.DeviceCode; - item.DeviceName = it1.Name; - float ivnQty = 0; - var stockName = new List(); - ErrorMessage msg2 = new(ErrorMessage.ExceptionCode, ""); - InventoryHelper.GetStockList(token, item.Id, ref msg2); - if (msg2?.Data is List sr) - { - sr?.ForEach(it2 => - { - ivnQty += it2.Imqty; - stockName.Add(it2.Name); - //if (it2.StockId== item.StockId) - //{ - // item.IvnQty = it2.Imqty; - - //} - }); - } - if (stockName.Count > 0) - { - item.IvnQty = ivnQty; - if (item.IvnQty > item.Qty) - { - item.Id = "齐套"; - } - else - { - item.Id = "待备货"; - } - item.StockName = string.Join(",", stockName); - list.Add(item); - } - }); - }); - msg = new ErrorMessage(0, "从服务器获取响应成功.", list); - return true; - } - } - catch (Exception ex) - { - msg = new ErrorMessage(ex); - } - } - } - return false; - } - } -} \ No newline at end of file diff --git a/productLifecycleManagement/src/backup.zip b/productLifecycleManagement/src/backup.zip deleted file mode 100644 index 1ba58a4..0000000 Binary files a/productLifecycleManagement/src/backup.zip and /dev/null differ diff --git a/productLifecycleManagement/src/permission.ts b/productLifecycleManagement/src/permission.ts deleted file mode 100644 index 1d440b0..0000000 --- a/productLifecycleManagement/src/permission.ts +++ /dev/null @@ -1,20 +0,0 @@ -import router from "./router"; - -const whiteList = ["/login"]; // no redirect whitelist -router.beforeEach(async (to, from, next) => { - console.log(from); - const storage: string | null = sessionStorage.getItem( - "lifecycleStorage" - ); - const storeUserInfo: Storage = storage && JSON.parse(storage); - const hasToken = storeUserInfo && storeUserInfo.token; - if (hasToken) { - next(); - } else { - if (whiteList.indexOf(to.path) !== -1) { - next(); - } else { - next(`/login`); - } - } -}); diff --git a/productLifecycleManagement/src/src.zip b/productLifecycleManagement/src/src.zip deleted file mode 100644 index 1ba58a4..0000000 Binary files a/productLifecycleManagement/src/src.zip and /dev/null differ