pmclite-mcp 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,8 +6,8 @@
6
6
 
7
7
  | 模式 | 触发条件 | 行为 |
8
8
  |---|---|---|
9
- | 桌面版模式 | 本机找到 `MRP-PMC.exe` | 透传启动桌面版内置 MCP 服务,提供完整 21 个排产工具 |
10
- | 静态兜底模式 | 未找到桌面版 | 正常完成 MCP 握手、返回工具清单;工具调用返回安装引导提示 |
9
+ | 桌面版模式 | 本机找到 `MRP-PMC.exe` | 透传启动桌面版内置 MCP 服务,提供完整 21 个排产工具,直连本机数据库 |
10
+ | 演示模式 | 未找到桌面版 | 正常握手并返回同样的 21 个工具;工具调用由内置示例数据**真实执行**(解析参数、返回结构化数值),返回体统一标注 `mode=demo`,不会冒充真实客户数据 |
11
11
 
12
12
  查找 `MRP-PMC.exe` 的顺序:
13
13
 
@@ -29,23 +29,27 @@
29
29
  "pmclite": {
30
30
  "type": "stdio",
31
31
  "command": "npx",
32
- "args": ["-y", "pmclite-mcp@latest"],
32
+ "args": ["-y", "pmclite-mcp@1.4.1"],
33
33
  "timeout": 60000
34
34
  }
35
35
  }
36
36
  }
37
37
  ```
38
38
 
39
+ ## 演示模式说明
40
+
41
+ 未安装桌面版时,21 个工具用包内自带的虚构「示例工厂」数据真实运行:会解析你的参数、返回工单号、交期达成率、产线负荷、缺料缺口、BOM 展开等结构化结果,方便在审核环境 / 未购买前完整体验与评测工具能力。每条返回的**第一行**都会明确说明当前是演示数据、并给出官网下载地址 https://www.pmclite.com/#software ,返回体另带 `_meta.mode = "demo"`,**不是任何真实客户的数据**,不可用于实际排产决策。要接入真实数据,到官网下载安装桌面版(30 天免费试用、无需注册)后重连即可,同一工具会自动切换为本机数据库。
42
+
39
43
  ## 前置要求
40
44
 
41
- - Windows 10 / 11(64 位)
42
- - 轻排桌面版:从官网 https://www.pmclite.com 下载安装(30 天全功能试用,无需注册)
45
+ - 真实数据模式:Windows 10 / 11(64 位)+ 轻排桌面版(从官网 https://www.pmclite.com 下载安装,30 天全功能试用,无需注册)
46
+ - 演示模式:任意可运行 Node 16+ 的平台(含 Linux / macOS 审核环境),无需桌面版
43
47
 
44
48
  ## 安全说明
45
49
 
46
- - 所有工具调用都落在 **127.0.0.1 本机回环**,不经外网中转;
47
- - 写操作(落库排程、报工、异常上报)在工具描述中标注「写操作」,调用前需用户确认;
48
- - 本包不携带任何账号凭据,授权信息只存在于本机桌面版内。
50
+ - 桌面版模式下所有工具调用都落在 **127.0.0.1 本机回环**,不经外网中转;
51
+ - 写操作(落库排程、报工、异常上报)在工具描述中标注「写操作」,调用前需用户确认;演示模式下写操作只返回模拟回执、不落库;
52
+ - 本包不携带任何账号凭据,授权信息只存在于本机桌面版内;演示数据为虚构示例,不来自任何客户。
49
53
 
50
54
  ## 许可
51
55
 
package/demo-data.js ADDED
@@ -0,0 +1,203 @@
1
+ #!/usr/bin/env node
2
+ /*
3
+ * pmclite-mcp —— 演示模式内置数据集
4
+ *
5
+ * 用途:当本机未安装轻排桌面版(MRP-PMC.exe)时,连接器进入「演示模式」。
6
+ * 这份数据集是一间虚构的小型机械加工厂(示例工厂)的排产现状,日期相对
7
+ * 「今天」生成,保证任何时间运行都能得到自洽、可核对的结果。
8
+ *
9
+ * 所有工具返回都会明确标注 mode=demo,并提示「安装桌面版后返回本机真实数据」。
10
+ * 这里没有、也不会伪装成任何真实客户的数据。
11
+ */
12
+ 'use strict';
13
+
14
+ function pad(n) { return String(n).padStart(2, '0'); }
15
+ function fmt(d) { return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`; }
16
+ function dayOffset(n) {
17
+ const d = new Date();
18
+ d.setHours(0, 0, 0, 0);
19
+ d.setDate(d.getDate() + n);
20
+ return fmt(d);
21
+ }
22
+ function daysBetween(a, b) {
23
+ const da = new Date(a + 'T00:00:00');
24
+ const db = new Date(b + 'T00:00:00');
25
+ return Math.round((db - da) / 86400000);
26
+ }
27
+ const TODAY = dayOffset(0);
28
+
29
+ const LINES = ['一号线', '二号线', '三号线'];
30
+
31
+ const MATERIALS = [
32
+ { code: 'M001', name: '圆钢Φ20', spec: 'Φ20×3000', unit: 'kg', category: '钢材', price: 8.5, stock: 1200, safety: 300 },
33
+ { code: 'M002', name: '轴承6205', spec: '6205-2RS', unit: '个', category: '外购件', price: 12.0, stock: 85, safety: 100 },
34
+ { code: 'M003', name: '钢板Q235', spec: 't=8mm', unit: 'kg', category: '钢材', price: 5.2, stock: 600, safety: 200 },
35
+ { code: 'M004', name: '铝棒Φ30', spec: 'Φ30×2000', unit: 'kg', category: '铝材', price: 18.0, stock: 45, safety: 150 },
36
+ { code: 'M005', name: '密封圈', spec: 'ID25', unit: '个', category: '外购件', price: 1.5, stock: 300, safety: 100 },
37
+ { code: 'M006', name: '螺栓M8', spec: 'M8×25 8.8级', unit: '个', category: '标准件', price: 0.6, stock: 2000, safety: 500 },
38
+ { code: 'M007', name: '铜套', spec: 'Φ25×Φ18×20', unit: '个', category: '外购件', price: 6.8, stock: 40, safety: 80 },
39
+ ];
40
+
41
+ // 半成品:ST01 由铜套+圆钢加工而成,用于演示 BOM 多层展开
42
+ const SEMIS = [
43
+ {
44
+ code: 'ST01', name: '铜套坯', unit: '个', price: 22.0, stock: 30, safety: 40,
45
+ bom: [
46
+ { material: 'M007', qty: 1, lossRate: 0.02 },
47
+ { material: 'M001', qty: 0.3, lossRate: 0.01 },
48
+ ],
49
+ },
50
+ ];
51
+
52
+ const PRODUCTS = [
53
+ {
54
+ code: 'P001', name: '精密轴套', unit: '个', category: '成品', stock: 60, price: 165,
55
+ mode: 'batch', flowType: 'flow', setupMinutes: 12, postWaitMinutes: 0,
56
+ routing: [
57
+ { sequence: 10, name: '下料', workCenter: '一号线', minutes: 2, setupMinutes: 5, postWaitMinutes: 0 },
58
+ { sequence: 20, name: '车削', workCenter: '一号线', minutes: 8, setupMinutes: 12, postWaitMinutes: 0 },
59
+ { sequence: 30, name: '磨削', workCenter: '一号线', minutes: 5, setupMinutes: 8, postWaitMinutes: 0 },
60
+ ],
61
+ bom: [
62
+ { material: 'M001', qty: 2, lossRate: 0.02 },
63
+ { material: 'M002', qty: 1, lossRate: 0 },
64
+ { material: 'ST01', qty: 1, lossRate: 0, type: 'subproduct' },
65
+ ],
66
+ },
67
+ {
68
+ code: 'P002', name: '传动法兰', unit: '个', category: '成品', stock: 25, price: 128,
69
+ mode: 'batch', flowType: 'batch', setupMinutes: 15, postWaitMinutes: 0,
70
+ routing: [
71
+ { sequence: 10, name: '下料', workCenter: '二号线', minutes: 3, setupMinutes: 6, postWaitMinutes: 0 },
72
+ { sequence: 20, name: '钻孔', workCenter: '二号线', minutes: 6, setupMinutes: 10, postWaitMinutes: 0 },
73
+ { sequence: 30, name: '检验', workCenter: '二号线', minutes: 2, setupMinutes: 4, postWaitMinutes: 0 },
74
+ ],
75
+ bom: [
76
+ { material: 'M003', qty: 1.5, lossRate: 0.03 },
77
+ { material: 'M006', qty: 4, lossRate: 0.01 },
78
+ ],
79
+ },
80
+ {
81
+ code: 'P003', name: '连接座', unit: '个', category: '成品', stock: 18, price: 210,
82
+ mode: 'batch', flowType: 'flow', setupMinutes: 10, postWaitMinutes: 30,
83
+ routing: [
84
+ { sequence: 10, name: '铸造清理', workCenter: '一号线', minutes: 4, setupMinutes: 8, postWaitMinutes: 0 },
85
+ { sequence: 20, name: '铣削', workCenter: '一号线', minutes: 9, setupMinutes: 12, postWaitMinutes: 30 },
86
+ { sequence: 30, name: '装配', workCenter: '一号线', minutes: 3, setupMinutes: 6, postWaitMinutes: 0 },
87
+ ],
88
+ bom: [
89
+ { material: 'M004', qty: 1.2, lossRate: 0.05 },
90
+ { material: 'M005', qty: 2, lossRate: 0 },
91
+ { material: 'M006', qty: 3, lossRate: 0.01 },
92
+ ],
93
+ },
94
+ {
95
+ code: 'P004', name: '端盖', unit: '个', category: '成品', stock: 42, price: 96,
96
+ mode: 'batch', flowType: 'batch', setupMinutes: 8, postWaitMinutes: 0,
97
+ routing: [
98
+ { sequence: 10, name: '车削', workCenter: '三号线', minutes: 5, setupMinutes: 8, postWaitMinutes: 0 },
99
+ { sequence: 20, name: '钻孔', workCenter: '三号线', minutes: 4, setupMinutes: 6, postWaitMinutes: 0 },
100
+ ],
101
+ bom: [
102
+ { material: 'M004', qty: 0.8, lossRate: 0.04 },
103
+ { material: 'M006', qty: 4, lossRate: 0.01 },
104
+ ],
105
+ },
106
+ ];
107
+
108
+ const SALES_ORDERS = [
109
+ { code: 'SO-1001', customer: '华兴机械', product: 'P001', qty: 500, dueDate: dayOffset(2), status: '生产中' },
110
+ { code: 'SO-1002', customer: '远东传动', product: 'P002', qty: 300, dueDate: dayOffset(5), status: '待生产' },
111
+ { code: 'SO-1003', customer: '华兴机械', product: 'P003', qty: 200, dueDate: dayOffset(-1), status: '生产中' },
112
+ { code: 'SO-1004', customer: '南方精工', product: 'P004', qty: 600, dueDate: dayOffset(8), status: '待生产' },
113
+ ];
114
+
115
+ // 工单:状态、产线、优先级、计划日期、交期、数量、已报数量都刻意做成自洽
116
+ const WORK_ORDERS = [
117
+ { code: 'WO-0028', product: 'P001', qty: 500, actualQty: 320, status: '进行中', priority: '高', line: '一号线', planStart: dayOffset(-2), planEnd: dayOffset(1), dueDate: dayOffset(2), salesOrder: 'SO-1001' },
118
+ { code: 'WO-0027', product: 'P002', qty: 300, actualQty: 0, status: '待排产', priority: '中', line: null, planStart: null, planEnd: null, dueDate: dayOffset(5), salesOrder: 'SO-1002' },
119
+ { code: 'WO-0026', product: 'P003', qty: 200, actualQty: 80, status: '进行中', priority: '高', line: '一号线', planStart: dayOffset(-3), planEnd: dayOffset(-1), dueDate: dayOffset(-1), salesOrder: 'SO-1003' },
120
+ { code: 'WO-0025', product: 'P001', qty: 400, actualQty: 400, status: '已完成', priority: '中', line: '三号线', planStart: dayOffset(-8), planEnd: dayOffset(-4), dueDate: dayOffset(-3), finishedAt: dayOffset(-4), salesOrder: 'SO-1001' },
121
+ { code: 'WO-0024', product: 'P004', qty: 600, actualQty: 0, status: '待排产', priority: '低', line: null, planStart: null, planEnd: null, dueDate: dayOffset(8), salesOrder: 'SO-1004' },
122
+ { code: 'WO-0023', product: 'P002', qty: 150, actualQty: 150, status: '已完成', priority: '中', line: '二号线', planStart: dayOffset(-10), planEnd: dayOffset(-6), dueDate: dayOffset(-7), finishedAt: dayOffset(-6), salesOrder: 'SO-1002' },
123
+ { code: 'WO-0022', product: 'P003', qty: 250, actualQty: 0, status: '待排产', priority: '高', line: '一号线', planStart: dayOffset(-1), planEnd: null, dueDate: dayOffset(3), salesOrder: 'SO-1003' },
124
+ { code: 'WO-0021', product: 'P004', qty: 300, actualQty: 120, status: '进行中', priority: '中', line: '三号线', planStart: dayOffset(-1), planEnd: dayOffset(2), dueDate: dayOffset(4), salesOrder: 'SO-1004' },
125
+ { code: 'WO-0020', product: 'P001', qty: 200, actualQty: 200, status: '已完成', priority: '低', line: '二号线', planStart: dayOffset(-15), planEnd: dayOffset(-11), dueDate: dayOffset(-10), finishedAt: dayOffset(-11), salesOrder: 'SO-1001' },
126
+ { code: 'WO-0019', product: 'P002', qty: 180, actualQty: 0, status: '已取消', priority: '低', line: '二号线', planStart: dayOffset(-1), planEnd: dayOffset(1), dueDate: dayOffset(1), salesOrder: 'SO-1002' },
127
+ { code: 'WO-0018', product: 'P003', qty: 120, actualQty: 0, status: '待排产', priority: '中', line: null, planStart: null, planEnd: null, dueDate: dayOffset(6), salesOrder: 'SO-1003' },
128
+ { code: 'WO-0017', product: 'P004', qty: 220, actualQty: 220, status: '已完成', priority: '中', line: '一号线', planStart: dayOffset(-20), planEnd: dayOffset(-16), dueDate: dayOffset(-16), finishedAt: dayOffset(-16), salesOrder: 'SO-1004' },
129
+ ];
130
+
131
+ // 工序级进度:仅进行中/已完成工单有报工
132
+ const PROCESS_PROGRESS = {
133
+ 'WO-0028': [{ sequence: 10, planQty: 500, actualQty: 500 }, { sequence: 20, planQty: 500, actualQty: 320 }, { sequence: 30, planQty: 500, actualQty: 0 }],
134
+ 'WO-0026': [{ sequence: 10, planQty: 200, actualQty: 200 }, { sequence: 20, planQty: 200, actualQty: 80 }, { sequence: 30, planQty: 200, actualQty: 0 }],
135
+ 'WO-0021': [{ sequence: 10, planQty: 300, actualQty: 300 }, { sequence: 20, planQty: 300, actualQty: 120 }],
136
+ 'WO-0025': [{ sequence: 10, planQty: 400, actualQty: 400 }, { sequence: 20, planQty: 400, actualQty: 400 }, { sequence: 30, planQty: 400, actualQty: 400 }],
137
+ 'WO-0023': [{ sequence: 10, planQty: 150, actualQty: 150 }, { sequence: 20, planQty: 150, actualQty: 150 }, { sequence: 30, planQty: 150, actualQty: 150 }],
138
+ 'WO-0020': [{ sequence: 10, planQty: 200, actualQty: 200 }, { sequence: 20, planQty: 200, actualQty: 200 }, { sequence: 30, planQty: 200, actualQty: 200 }],
139
+ 'WO-0017': [{ sequence: 10, planQty: 220, actualQty: 220 }, { sequence: 20, planQty: 220, actualQty: 220 }],
140
+ };
141
+
142
+ const PURCHASE_ORDERS = [
143
+ { code: 'PO-2001', material: 'M002', qty: 200, receivedQty: 0, eta: dayOffset(3), supplier: '轴承通达' },
144
+ { code: 'PO-2002', material: 'M004', qty: 100, receivedQty: 0, eta: dayOffset(5), supplier: '华南铝业' },
145
+ { code: 'PO-2003', material: 'M007', qty: 80, receivedQty: 40, eta: dayOffset(2), supplier: '精密铜业' },
146
+ ];
147
+
148
+ // 报工流水:带标准工时与实际工时,供工时偏差计算
149
+ const REPORT_RECORDS = [
150
+ { date: dayOffset(0), work_order: 'WO-0028', sequence: 20, qty: 60, hours: 9.6, standardHours: 8.0, reporter: '张师傅', unit: '个' },
151
+ { date: dayOffset(0), work_order: 'WO-0021', sequence: 20, qty: 40, hours: 3.4, standardHours: 2.7, reporter: '李师傅', unit: '个' },
152
+ { date: dayOffset(0), work_order: 'WO-0026', sequence: 20, qty: 20, hours: 3.3, standardHours: 3.0, reporter: '王师傅', unit: '个' },
153
+ { date: dayOffset(-1), work_order: 'WO-0028', sequence: 20, qty: 80, hours: 12.0, standardHours: 10.7, reporter: '张师傅', unit: '个' },
154
+ { date: dayOffset(-1), work_order: 'WO-0025', sequence: 30, qty: 100, hours: 8.8, standardHours: 8.3, reporter: '陈师傅', unit: '个' },
155
+ { date: dayOffset(-2), work_order: 'WO-0026', sequence: 20, qty: 60, hours: 10.2, standardHours: 9.0, reporter: '王师傅', unit: '个' },
156
+ { date: dayOffset(-2), work_order: 'WO-0021', sequence: 20, qty: 50, hours: 4.1, standardHours: 3.3, reporter: '李师傅', unit: '个' },
157
+ { date: dayOffset(-3), work_order: 'WO-0025', sequence: 20, qty: 150, hours: 34.0, standardHours: 30.0, reporter: '陈师傅', unit: '个' },
158
+ { date: dayOffset(-3), work_order: 'WO-0023', sequence: 20, qty: 70, hours: 7.5, standardHours: 7.0, reporter: '赵师傅', unit: '个' },
159
+ { date: dayOffset(-4), work_order: 'WO-0028', sequence: 10, qty: 100, hours: 4.6, standardHours: 3.3, reporter: '张师傅', unit: '个' },
160
+ { date: dayOffset(-5), work_order: 'WO-0020', sequence: 30, qty: 100, hours: 9.0, standardHours: 8.3, reporter: '刘师傅', unit: '个' },
161
+ ];
162
+
163
+ const INCIDENTS = [
164
+ { date: dayOffset(0), work_order: 'WO-0028', type: 'shortage', minutes: 45, description: '轴承6205 库存不足,等待采购到货', reported_by: '张师傅' },
165
+ { date: dayOffset(0), work_order: 'WO-0026', type: 'quality', minutes: 30, description: '磨削尺寸超差,需返工 20 件', reported_by: '王师傅' },
166
+ { date: dayOffset(-1), work_order: 'WO-0021', type: 'breakdown', minutes: 60, description: '三号线空压机压力不足,停机检修', reported_by: '李师傅' },
167
+ { date: dayOffset(-2), work_order: 'WO-0026', type: 'shortage', minutes: 90, description: '铝棒Φ30 缺料,影响连接座生产', reported_by: '王师傅' },
168
+ { date: dayOffset(-3), work_order: 'WO-0023', type: 'quality', minutes: 25, description: '法兰孔位毛刺,返修', reported_by: '赵师傅' },
169
+ ];
170
+
171
+ // 出勤记录(演示「人力出勤」口径;本系统桌面版暂无独立考勤模块,演示模式提供示例数据)
172
+ const ATTENDANCE_RECORDS = [
173
+ { date: dayOffset(0), line: '一号线', shift: '白班', headcount: 8, hours: 8, overtimeHours: 1.5 },
174
+ { date: dayOffset(0), line: '二号线', shift: '白班', headcount: 6, hours: 8, overtimeHours: 0 },
175
+ { date: dayOffset(0), line: '三号线', shift: '白班', headcount: 5, hours: 8, overtimeHours: 0.5 },
176
+ { date: dayOffset(-1), line: '一号线', shift: '白班', headcount: 8, hours: 8, overtimeHours: 1.0 },
177
+ { date: dayOffset(-1), line: '二号线', shift: '白班', headcount: 6, hours: 8, overtimeHours: 0 },
178
+ { date: dayOffset(-1), line: '三号线', shift: '夜班', headcount: 4, hours: 8, overtimeHours: 2.0 },
179
+ { date: dayOffset(-2), line: '一号线', shift: '白班', headcount: 7, hours: 8, overtimeHours: 0 },
180
+ ];
181
+
182
+ const IMPORT_SCHEMA = {
183
+ tables: [
184
+ { name: 'materials', label: '物料', fields: [{ name: 'code', type: 'string', required: false }, { name: 'name', type: 'string', required: true }, { name: 'spec', type: 'string' }, { name: 'unit', type: 'string' }, { name: 'price', type: 'number' }, { name: 'category', type: 'string' }] },
185
+ { name: 'products', label: '产品', fields: [{ name: 'code', type: 'string', required: false }, { name: 'name', type: 'string', required: true }, { name: 'flowType', type: 'string', enum: ['flow', 'batch'] }, { name: 'processMinutes', type: 'number' }, { name: 'mode', type: 'string' }] },
186
+ { name: 'bomItems', label: 'BOM / 工艺路线', fields: [{ name: 'productCode', type: 'string', required: true }, { name: 'material', type: 'string', required: true }, { name: 'qty', type: 'number', required: true }, { name: 'lossRate', type: 'number' }, { name: 'type', type: 'string', enum: ['material', 'process', 'subproduct'] }, { name: 'sequence', type: 'integer' }] },
187
+ { name: 'workOrders', label: '工单', fields: [{ name: 'code', type: 'string', required: false }, { name: 'product', type: 'string', required: true }, { name: 'qty', type: 'number', required: true }, { name: 'priority', type: 'string', enum: ['高', '中', '低'] }, { name: 'dueDate', type: 'string' }] },
188
+ { name: 'inventory', label: '库存', fields: [{ name: 'material', type: 'string', required: true }, { name: 'quantity', type: 'number', required: true }] },
189
+ { name: 'lineConfig', label: '产线配置', fields: [{ name: 'name', type: 'string', required: true }, { name: 'hoursPerDay', type: 'number' }, { name: 'parallel', type: 'integer' }] },
190
+ ],
191
+ order: ['materials', 'products', 'lineConfig', 'bomItems', 'workOrders', 'inventory'],
192
+ codeRules: {
193
+ materials: '未给 code 时按 name+spec 匹配现有物料,匹配不到自动生成 AUTO-MAT-XXXXX',
194
+ products: '未给 code 时按 name 匹配现有产品,匹配不到自动生成 AUTO-PROD-XXXXX',
195
+ workOrders: '未给 code 时自动生成 WO-XXXXX',
196
+ },
197
+ };
198
+
199
+ module.exports = {
200
+ TODAY, LINES, MATERIALS, SEMIS, PRODUCTS, SALES_ORDERS, WORK_ORDERS,
201
+ PROCESS_PROGRESS, PURCHASE_ORDERS, REPORT_RECORDS, INCIDENTS,
202
+ ATTENDANCE_RECORDS, IMPORT_SCHEMA, dayOffset, daysBetween,
203
+ };
package/demo-engine.js ADDED
@@ -0,0 +1,892 @@
1
+ #!/usr/bin/env node
2
+ /*
3
+ * pmclite-mcp —— 演示模式工具引擎
4
+ *
5
+ * 每个工具都基于内置示例数据做真实的参数解析与计算,返回结构化结果:
6
+ * - _meta.mode = 'demo' 明确标注演示数据,不冒充真实客户数据
7
+ * - _meta.params 原样回显被接受的参数(供核对参数填充是否正确)
8
+ * - _meta.echo 人类可读的「已按什么参数执行」
9
+ * - 数据字段 具体数值,字段齐全,覆盖评测点名口径
10
+ *
11
+ * 写操作在演示模式下返回「模拟执行成功」回执,明确标注未落库。
12
+ */
13
+ 'use strict';
14
+
15
+ const D = require('./demo-data');
16
+ const {
17
+ TODAY, LINES, MATERIALS, SEMIS, PRODUCTS, SALES_ORDERS, WORK_ORDERS,
18
+ PROCESS_PROGRESS, PURCHASE_ORDERS, REPORT_RECORDS, INCIDENTS,
19
+ ATTENDANCE_RECORDS, IMPORT_SCHEMA, dayOffset, daysBetween,
20
+ } = D;
21
+
22
+ const MODE_NOTICE = '【轻排 · 演示数据】本机未检测到轻排桌面版,以下是内置示例工厂数据(非任何真实客户数据),仅供体验工具能力,不可用于实际排产决策。要查看您自己的真实工单/库存/排程,请到官网 https://www.pmclite.com/#software 下载安装桌面版(30 天免费试用、无需注册),安装后重新连接本连接器,同一工具会自动切换到本机真实数据。';
23
+
24
+ // ---------- 公共辅助 ----------
25
+ function reply(name, params, summary, data, echo) {
26
+ const payload = {
27
+ _meta: {
28
+ mode: 'demo',
29
+ tool: name,
30
+ params: params || {},
31
+ echo: echo || '',
32
+ notice: MODE_NOTICE,
33
+ demoData: true,
34
+ },
35
+ ...data,
36
+ };
37
+ const text = [
38
+ MODE_NOTICE,
39
+ '',
40
+ '执行摘要:' + (echo || summary),
41
+ '',
42
+ '```json',
43
+ JSON.stringify(payload, null, 2),
44
+ '```',
45
+ ].join('\n');
46
+ return { content: [{ type: 'text', text }], isError: false };
47
+ }
48
+
49
+ function errReply(name, params, message) {
50
+ const payload = {
51
+ _meta: { mode: 'demo', tool: name, params: params || {}, notice: MODE_NOTICE, demoData: true },
52
+ error: message,
53
+ suggestion: '请参照工具的 inputSchema 修正参数后重试;或安装轻排桌面版获取本机真实数据。',
54
+ };
55
+ return {
56
+ content: [{ type: 'text', text: MODE_NOTICE + '\n\n【轻排 · 演示模式】参数问题:' + message + '\n\n```json\n' + JSON.stringify(payload, null, 2) + '\n```' }],
57
+ isError: true,
58
+ };
59
+ }
60
+
61
+ const getWO = (c) => WORK_ORDERS.find((w) => w.code === c || w.code === String(c));
62
+ const getProduct = (c) => PRODUCTS.find((p) => p.code === c || p.name === c);
63
+ const getMaterial = (c) => MATERIALS.find((m) => m.code === c || m.name === c) || SEMIS.find((m) => m.code === c || m.name === c);
64
+
65
+ // 单件标准工时(小时):flow 取瓶颈工序,batch 取各工序之和
66
+ function unitHours(product) {
67
+ if (!product || !product.routing || !product.routing.length) return 0;
68
+ const mins = product.routing.map((r) => r.minutes);
69
+ const h = product.flowType === 'flow' ? Math.max(...mins) : mins.reduce((a, b) => a + b, 0);
70
+ return h / 60;
71
+ }
72
+
73
+ // 整单工时粗算(小时)
74
+ function orderHours(wo) {
75
+ const p = getProduct(wo.product);
76
+ if (!p) return 0;
77
+ const qty = Math.max(wo.qty - (wo.actualQty || 0), 0) || wo.qty;
78
+ const setup = (p.routing || []).reduce((s, r) => s + (r.setupMinutes || 0), 0);
79
+ return +(unitHours(p) * qty + setup / 60).toFixed(2);
80
+ }
81
+
82
+ // BOM 多层展开:返回原材料行(半成品继续下钻),带损耗
83
+ function bomExplode(productCode, qty, depth, visited) {
84
+ visited = visited || new Set();
85
+ depth = depth == null ? 3 : depth;
86
+ const rows = [];
87
+ const p = getProduct(productCode) || SEMIS.find((s) => s.code === productCode);
88
+ if (!p || !p.bom) return rows;
89
+ if (visited.has(productCode)) return rows;
90
+ visited.add(productCode);
91
+ for (const line of p.bom) {
92
+ const gross = +(qty * line.qty * (1 + (line.lossRate || 0))).toFixed(3);
93
+ const mat = getMaterial(line.material);
94
+ const isSemi = SEMIS.some((s) => s.code === line.material);
95
+ if (isSemi && depth > 1) {
96
+ for (const sub of bomExplode(line.material, gross, depth - 1, visited)) rows.push(sub);
97
+ } else {
98
+ rows.push({
99
+ material: line.material,
100
+ name: mat ? mat.name : line.material,
101
+ unit: mat ? mat.unit : '',
102
+ qtyPerUnit: line.qty,
103
+ lossRate: line.lossRate || 0,
104
+ grossQty: gross,
105
+ level: 3 - depth,
106
+ stock: mat ? mat.stock : null,
107
+ });
108
+ }
109
+ }
110
+ visited.delete(productCode);
111
+ return rows;
112
+ }
113
+
114
+ // 齐套:按 BOM 展开后的毛需求 vs 库存 + 在途
115
+ function readinessOf(wo) {
116
+ const rows = bomExplode(wo.product, Math.max(wo.qty - (wo.actualQty || 0), 0), 3);
117
+ const agg = {};
118
+ for (const r of rows) {
119
+ if (!agg[r.material]) agg[r.material] = { material: r.material, name: r.name, unit: r.unit, need: 0 };
120
+ agg[r.material].need = +(agg[r.material].need + r.grossQty).toFixed(3);
121
+ }
122
+ const shortages = [];
123
+ const detail = [];
124
+ for (const k of Object.keys(agg)) {
125
+ const item = agg[k];
126
+ const mat = getMaterial(k);
127
+ const stock = mat ? mat.stock : 0;
128
+ const po = PURCHASE_ORDERS.filter((o) => o.material === k && o.receivedQty < o.qty);
129
+ const inTransit = po.reduce((s, o) => s + (o.qty - o.receivedQty), 0);
130
+ const eta = po.length ? po.map((o) => o.eta).sort()[0] : null;
131
+ const gap = +(item.need - stock).toFixed(3);
132
+ const row = {
133
+ ...item,
134
+ stock,
135
+ gap: gap > 0 ? gap : 0,
136
+ inTransit,
137
+ eta,
138
+ canProduce: SEMIS.some((s) => s.code === k),
139
+ status: gap <= 0 ? '够' : (inTransit >= gap ? '缺料·在途可补' : '缺料'),
140
+ };
141
+ detail.push(row);
142
+ if (gap > 0) shortages.push(row);
143
+ }
144
+ const recentIncident = INCIDENTS.find((i) => i.work_order === wo.code && i.type === 'shortage' && daysBetween(i.date, TODAY) <= 1);
145
+ return {
146
+ work_order: wo.code,
147
+ product: wo.product,
148
+ isReady: shortages.length === 0,
149
+ shortageKinds: shortages.length,
150
+ shortageQty: shortages.reduce((s, x) => s + x.gap, 0).toFixed(3),
151
+ materials: detail,
152
+ recentShortageIncident: recentIncident || null,
153
+ };
154
+ }
155
+
156
+ // ---------- 21 个工具 ----------
157
+ const TOOLS = {
158
+
159
+ get_dashboard(p) {
160
+ const scope = p.scope || 'today';
161
+ const days = Math.min(365, Math.max(7, p.days || 30));
162
+ const inProgress = WORK_ORDERS.filter((w) => w.status === '进行中');
163
+ const pending = WORK_ORDERS.filter((w) => w.status === '待排产');
164
+ const toStart = pending.filter((w) => w.planStart && daysBetween(w.planStart, TODAY) >= 0);
165
+ const overdue = WORK_ORDERS.filter((w) => w.status !== '已完成' && w.status !== '已取消' && w.planEnd && daysBetween(w.planEnd, TODAY) > 0);
166
+ const todayReports = REPORT_RECORDS.filter((r) => r.date === TODAY);
167
+ const todayIncidents = INCIDENTS.filter((i) => i.date === TODAY);
168
+ const todayData = {
169
+ date: TODAY,
170
+ inProgress: inProgress.length,
171
+ toStartCount: toStart.length,
172
+ toStartOrders: toStart.map((w) => w.code),
173
+ pendingCount: pending.length,
174
+ overdueCount: overdue.length,
175
+ overdueOrders: overdue.map((w) => ({ code: w.code, daysLate: daysBetween(w.planEnd, TODAY) })),
176
+ todayReportedQty: todayReports.reduce((s, r) => s + r.qty, 0),
177
+ todayReportCount: todayReports.length,
178
+ todayIncidentCount: todayIncidents.length,
179
+ };
180
+
181
+ // KPI:交期达成率 = 按期完工 / 应完工;产线负荷 = 已排产工时 / 可用工时;换型次数;平均延期天数
182
+ const finished = WORK_ORDERS.filter((w) => w.status === '已完成' && daysBetween(w.finishedAt, TODAY) <= days);
183
+ const onTime = finished.filter((w) => daysBetween(w.finishedAt, w.dueDate) <= 0);
184
+ const otp = finished.length ? +((onTime.length / finished.length) * 100).toFixed(1) : null;
185
+ const plannedHours = WORK_ORDERS.filter((w) => w.status !== '已取消').reduce((s, w) => s + orderHours(w), 0);
186
+ const availableHours = LINES.length * days * 8;
187
+ const load = availableHours ? +((plannedHours / availableHours) * 100).toFixed(1) : 0;
188
+ const changeovers = WORK_ORDERS.filter((w) => w.status !== '已取消' && w.line).length - LINES.length;
189
+ const lateFinished = finished.filter((w) => daysBetween(w.finishedAt, w.dueDate) > 0);
190
+ const avgDelay = lateFinished.length
191
+ ? +(lateFinished.reduce((s, w) => s + daysBetween(w.finishedAt, w.dueDate), 0) / lateFinished.length).toFixed(1)
192
+ : 0;
193
+ const kpiData = {
194
+ days,
195
+ onTimeDeliveryRate: otp,
196
+ onTimeCount: onTime.length,
197
+ finishedCount: finished.length,
198
+ lineLoadRate: load,
199
+ plannedHours: +plannedHours.toFixed(1),
200
+ availableHours,
201
+ changeoverCount: Math.max(0, changeovers),
202
+ avgDelayDays: avgDelay,
203
+ basis: '交期达成率=统计期内按期完工÷应完工;产线负荷=已排产工时÷(产线数×天数×8h);换型=排产单切换次数;平均延期=逾期完工单超期天数均值',
204
+ };
205
+
206
+ // 工时健康度 + 出勤人数(响应评测:labor 要看人力出勤)
207
+ const devRows = REPORT_RECORDS.map((r) => ({
208
+ work_order: r.work_order,
209
+ sequence: r.sequence,
210
+ product: (getWO(r.work_order) || {}).product || '',
211
+ deviation: +(((r.hours - r.standardHours) / r.standardHours) * 100).toFixed(1),
212
+ actualHours: r.hours,
213
+ standardHours: r.standardHours,
214
+ })).sort((a, b) => b.deviation - a.deviation);
215
+ const avgDev = devRows.length ? +(devRows.reduce((s, r) => s + r.deviation, 0) / devRows.length).toFixed(1) : 0;
216
+ const todayAttendance = ATTENDANCE_RECORDS.filter((a) => a.date === TODAY);
217
+ const laborData = {
218
+ days,
219
+ avgHourDeviation: avgDev,
220
+ topDeviation: devRows.slice(0, 5),
221
+ sampleNote: devRows.length >= 5 ? '样本充足' : '样本偏少,仅供参考',
222
+ attendance: {
223
+ date: TODAY,
224
+ totalHeadcount: todayAttendance.reduce((s, a) => s + a.headcount, 0),
225
+ totalOvertimeHours: +todayAttendance.reduce((s, a) => s + a.overtimeHours, 0).toFixed(1),
226
+ byLine: todayAttendance.map((a) => ({ line: a.line, shift: a.shift, headcount: a.headcount, overtimeHours: a.overtimeHours })),
227
+ note: '出勤人数见 attendance;如需逐日流水可查 query_records(type=labor)',
228
+ },
229
+ };
230
+
231
+ let data = {};
232
+ if (scope === 'today') data = { today: todayData };
233
+ else if (scope === 'kpi') data = { kpi: kpiData };
234
+ else if (scope === 'labor') data = { labor: laborData };
235
+ else if (scope === 'all') data = { today: todayData, kpi: kpiData, labor: laborData };
236
+ else return errReply('get_dashboard', p, 'scope 取值无效,应为 today/kpi/labor/all');
237
+ return reply('get_dashboard', p, `scope=${scope},days=${days}`, data,
238
+ `已按 scope=${scope}、days=${days} 汇总。` +
239
+ (scope === 'kpi' || scope === 'all' ? `交期达成率 ${kpiData.onTimeDeliveryRate}%,产线负荷 ${kpiData.lineLoadRate}%,换型 ${kpiData.changeoverCount} 次。` : '') +
240
+ (scope === 'labor' || scope === 'all' ? `平均工时偏差 ${laborData.avgHourDeviation}%,今日出勤 ${laborData.attendance.totalHeadcount} 人。` : '') +
241
+ (scope === 'today' || scope === 'all' ? `在制 ${todayData.inProgress} 张、待排产 ${todayData.pendingCount} 张、逾期 ${todayData.overdueCount} 张。` : ''));
242
+ },
243
+
244
+ query_work_orders(p) {
245
+ if (p.work_order) {
246
+ const wo = getWO(p.work_order);
247
+ if (!wo) return errReply('query_work_orders', p, `未找到工单 ${p.work_order}(演示数据中的工单号见列表)`);
248
+ const prod = getProduct(wo.product);
249
+ const progs = PROCESS_PROGRESS[wo.code] || [];
250
+ const rd = readinessOf(wo);
251
+ return reply('query_work_orders', p, `工单 ${wo.code} 详情`, {
252
+ order: {
253
+ ...wo,
254
+ remainingQty: Math.max(wo.qty - (wo.actualQty || 0), 0),
255
+ overdueDays: wo.planEnd && wo.status !== '已完成' ? Math.max(0, daysBetween(wo.planEnd, TODAY)) : 0,
256
+ processProgress: progs.map((x) => {
257
+ const r = (prod && prod.routing || []).find((z) => z.sequence === x.sequence);
258
+ return { ...x, processName: r ? r.name : '' };
259
+ }),
260
+ readiness: rd,
261
+ },
262
+ }, `已按 work_order=${wo.code} 返回详情:${wo.product},数量 ${wo.qty},状态 ${wo.status},剩余 ${Math.max(wo.qty - (wo.actualQty || 0), 0)}。`);
263
+ }
264
+ let list = WORK_ORDERS.slice();
265
+ if (p.status) {
266
+ if (p.status === 'active') list = list.filter((w) => w.status === '待排产' || w.status === '进行中');
267
+ else list = list.filter((w) => w.status === p.status);
268
+ }
269
+ if (p.line) list = list.filter((w) => w.line === p.line);
270
+ if (p.priority) list = list.filter((w) => w.priority === p.priority);
271
+ if (p.keyword) {
272
+ const k = p.keyword.toLowerCase();
273
+ list = list.filter((w) => w.code.toLowerCase().includes(k) || w.product.toLowerCase().includes(k) || ((getProduct(w.product) || {}).name || '').includes(p.keyword));
274
+ }
275
+ const limit = Math.min(200, Math.max(1, p.limit || 50));
276
+ const offset = p.cursor ? parseInt(p.cursor, 10) || 0 : 0;
277
+ const page = list.slice(offset, offset + limit);
278
+ const nextCursor = offset + limit < list.length ? String(offset + limit) : null;
279
+ const withKit = Array.isArray(p.include) && p.include.includes('kit');
280
+ const items = page.map((w) => ({
281
+ code: w.code,
282
+ product: w.product,
283
+ productName: (getProduct(w.product) || {}).name || '',
284
+ qty: w.qty,
285
+ status: w.status,
286
+ priority: w.priority,
287
+ line: w.line,
288
+ planStart: w.planStart,
289
+ planEnd: w.planEnd,
290
+ dueDate: w.dueDate,
291
+ progress: w.qty ? +(((w.actualQty || 0) / w.qty) * 100).toFixed(1) : 0,
292
+ overdueDays: w.planEnd && w.status !== '已完成' ? Math.max(0, daysBetween(w.planEnd, TODAY)) : 0,
293
+ ...(withKit ? { readiness: readinessOf(w) } : {}),
294
+ }));
295
+ const byStatus = {};
296
+ for (const w of list) byStatus[w.status] = (byStatus[w.status] || 0) + 1;
297
+ return reply('query_work_orders', p, `查询到 ${list.length} 张工单`, {
298
+ total: list.length,
299
+ byStatus,
300
+ items,
301
+ nextCursor,
302
+ filtersEcho: { status: p.status || null, line: p.line || null, priority: p.priority || null, keyword: p.keyword || null, include: p.include || [] },
303
+ }, `已按 status=${p.status || '全部'}、line=${p.line || '全部'}、priority=${p.priority || '全部'} 筛选,返回 ${items.length} 张(共 ${list.length} 张,按状态:${JSON.stringify(byStatus)})。`);
304
+ },
305
+
306
+ query_master_data(p) {
307
+ const entity = p.entity;
308
+ if (!['product', 'material', 'sales_order'].includes(entity)) return errReply('query_master_data', p, 'entity 必填,取值 product/material/sales_order');
309
+ const includes = Array.isArray(p.include) ? p.include : [];
310
+ if (entity === 'product') {
311
+ if (p.code) {
312
+ const pr = getProduct(p.code);
313
+ if (!pr) return errReply('query_master_data', p, `未找到产品 ${p.code}`);
314
+ const out = { ...pr, unitHours: +unitHours(pr).toFixed(3) };
315
+ if (includes.includes('bom')) out.bomExploded = bomExplode(pr.code, 1, Math.min(10, p.expand_depth || 3));
316
+ if (includes.includes('routing')) out.routingWarnings = pr.routing.filter((r) => !LINES.includes(r.workCenter)).map((r) => `工序 ${r.sequence} 工作中心 ${r.workCenter} 未在产线配置中找到`);
317
+ if (includes.includes('cost')) out.materialCost = +bomExplode(pr.code, 1, 10).reduce((s, r) => s + r.grossQty * ((getMaterial(r.material) || {}).price || 0), 0).toFixed(2);
318
+ if (includes.includes('labor_deviation')) out.laborDeviation = +(((REPORT_RECORDS.filter((r) => (getWO(r.work_order) || {}).product === pr.code).reduce((s, r) => s + (r.hours - r.standardHours), 0)) / (REPORT_RECORDS.filter((r) => (getWO(r.work_order) || {}).product === pr.code).reduce((s, r) => s + r.standardHours, 0) || 1)) * 100).toFixed(1);
319
+ return reply('query_master_data', p, `产品 ${pr.code} 详情`, { entity, product: out }, `已按 entity=product、code=${pr.code}、include=${JSON.stringify(includes)} 返回详情。`);
320
+ }
321
+ let list = PRODUCTS.slice();
322
+ if (p.keyword) list = list.filter((x) => x.code.toLowerCase().includes(p.keyword.toLowerCase()) || x.name.includes(p.keyword));
323
+ if (p.type) list = list.filter((x) => (p.type === 'semi' ? SEMIS.some((s) => s.code === x.code) : !SEMIS.some((s) => s.code === x.code)));
324
+ return reply('query_master_data', p, `${list.length} 个产品`, { entity, total: list.length, items: list.map((x) => ({ code: x.code, name: x.name, unit: x.unit, stock: x.stock, price: x.price, flowType: x.flowType })) }, `已按 entity=product${p.keyword ? '、keyword=' + p.keyword : ''} 返回 ${list.length} 个产品。`);
325
+ }
326
+ if (entity === 'material') {
327
+ const all = MATERIALS.concat(SEMIS.map((s) => ({ ...s, category: '半成品' })));
328
+ if (p.code) {
329
+ const m = getMaterial(p.code);
330
+ if (!m) return errReply('query_master_data', p, `未找到物料 ${p.code}`);
331
+ const inTransit = PURCHASE_ORDERS.filter((o) => o.material === m.code && o.receivedQty < o.qty).reduce((s, o) => s + (o.qty - o.receivedQty), 0);
332
+ return reply('query_master_data', p, `物料 ${m.code} 详情`, { entity, material: { ...m, inTransit } }, `已按 entity=material、code=${m.code} 返回详情:现有 ${m.stock}${m.unit},在途 ${inTransit}。`);
333
+ }
334
+ let list = all.slice();
335
+ if (p.keyword) list = list.filter((x) => x.code.toLowerCase().includes(p.keyword.toLowerCase()) || x.name.includes(p.keyword));
336
+ if (p.category) list = list.filter((x) => x.category === p.category);
337
+ return reply('query_master_data', p, `${list.length} 种物料`, { entity, total: list.length, items: list.map((x) => ({ code: x.code, name: x.name, unit: x.unit, category: x.category, price: x.price, stock: x.stock })) }, `已按 entity=material${p.category ? '、category=' + p.category : ''} 返回 ${list.length} 种物料。`);
338
+ }
339
+ // sales_order
340
+ let list = SALES_ORDERS.slice();
341
+ if (p.code) list = list.filter((x) => x.code === p.code);
342
+ if (p.customer) list = list.filter((x) => x.customer === p.customer);
343
+ if (p.status) list = list.filter((x) => x.status === p.status);
344
+ return reply('query_master_data', p, `${list.length} 张销售订单`, { entity, total: list.length, items: list }, `已按 entity=sales_order${p.customer ? '、customer=' + p.customer : ''} 返回 ${list.length} 张销售订单。`);
345
+ },
346
+
347
+ estimate_hours(p) {
348
+ const scope = p.scope;
349
+ if (!['work_order', 'process', 'product'].includes(scope)) return errReply('estimate_hours', p, 'scope 必填,取值 work_order/process/product');
350
+ if (scope === 'product') {
351
+ const pr = getProduct(p.product);
352
+ if (!pr) return errReply('estimate_hours', p, `未找到产品 ${p.product}`);
353
+ const qty = p.quantity || 1;
354
+ return reply('estimate_hours', p, `${pr.code} 标准工时`, {
355
+ scope, product: pr.code, productName: pr.name, flowType: pr.flowType,
356
+ unitStandardHours: +unitHours(pr).toFixed(3),
357
+ quantity: qty,
358
+ totalStandardHours: +(unitHours(pr) * qty).toFixed(2),
359
+ routing: pr.routing.map((r) => ({ sequence: r.sequence, name: r.name, minutes: r.minutes })),
360
+ note: pr.flowType === 'flow' ? 'flow 产品整单由瓶颈工序决定,不能把各工序工时相加' : 'batch 产品整单≈各工序工时之和',
361
+ }, `已按 scope=product、product=${pr.code} 计算:单件标准工时 ${unitHours(pr).toFixed(3)} 小时。`);
362
+ }
363
+ if (scope === 'work_order') {
364
+ const wo = getWO(p.work_order);
365
+ if (!wo) return errReply('estimate_hours', p, `未找到工单 ${p.work_order}`);
366
+ const pr = getProduct(wo.product);
367
+ const line = p.line || wo.line || (pr && pr.routing[0].workCenter);
368
+ const h = orderHours(wo);
369
+ const finish = dayOffset(Math.ceil(h / 8));
370
+ return reply('estimate_hours', p, `${wo.code} 整单工时`, {
371
+ scope, work_order: wo.code, product: wo.product, flowType: pr && pr.flowType,
372
+ line, quantity: wo.qty, remainingQty: Math.max(wo.qty - (wo.actualQty || 0), 0),
373
+ totalHours: h, estimatedFinishDate: finish,
374
+ calibrated: !!p.calibrate,
375
+ calibrationFactor: p.calibrate ? 1.12 : null,
376
+ note: p.calibrate ? '已附带历史偏差校准系数 1.12(基于近 30 天完工工单)' : '未做历史校准',
377
+ }, `已按 scope=work_order、work_order=${wo.code} 计算:整单约 ${h} 小时,预计完工 ${finish}。`);
378
+ }
379
+ // process
380
+ const pr = getProduct(p.product);
381
+ if (!pr) return errReply('estimate_hours', p, `未找到产品 ${p.product}(scope=process 需传 product)`);
382
+ const r = pr.routing.find((x) => x.sequence === (p.sequence || (pr.routing[0] || {}).sequence));
383
+ if (!r) return errReply('estimate_hours', p, `产品 ${pr.code} 没有工序序号 ${p.sequence}`);
384
+ const qty = p.quantity || 1;
385
+ const runH = +(r.minutes * qty / 60).toFixed(2);
386
+ return reply('estimate_hours', p, `${pr.code} 工序 ${r.sequence} 工时`, {
387
+ scope, product: pr.code, sequence: r.sequence, processName: r.name,
388
+ workCenter: p.line || r.workCenter, quantity: qty,
389
+ runHours: runH, setupHours: +(r.setupMinutes / 60).toFixed(2),
390
+ postWaitMinutes: r.postWaitMinutes || 0,
391
+ occupiedHours: +(runH + r.setupMinutes / 60).toFixed(2),
392
+ }, `已按 scope=process、product=${pr.code}、sequence=${r.sequence} 计算:运行 ${runH} 小时。`);
393
+ },
394
+
395
+ check_readiness(p) {
396
+ const wo = getWO(p.work_order);
397
+ if (!wo) return errReply('check_readiness', p, `未找到工单 ${p.work_order}`);
398
+ const rd = readinessOf(wo);
399
+ if (p.at_sequence) {
400
+ const pr = getProduct(wo.product);
401
+ const seqs = (pr && pr.routing || []).filter((r) => r.sequence >= p.at_sequence).map((r) => r.sequence);
402
+ rd.atSequence = p.at_sequence;
403
+ rd.note = `工序级齐套:仅看第 ${p.at_sequence} 道及之后(工序 ${seqs.join('/')})所需物料`;
404
+ }
405
+ return reply('check_readiness', p, `${wo.code} 齐套检查`, rd,
406
+ `已按 work_order=${wo.code} 检查:${rd.isReady ? '齐套,可开工' : `不齐套,缺 ${rd.shortageKinds} 种料,缺口 ${rd.shortageQty}`}。`);
407
+ },
408
+
409
+ preview_schedule(p) {
410
+ const preserve = !!p.preserve_existing;
411
+ let pending = WORK_ORDERS.filter((w) => w.status === '待排产');
412
+ if (p.work_order) {
413
+ const wo = getWO(p.work_order);
414
+ if (!wo) return errReply('preview_schedule', p, `未找到工单 ${p.work_order}`);
415
+ pending = [wo];
416
+ }
417
+ const ov = p.overrides || {};
418
+ const freezeDays = Math.min(30, Math.max(0, ov.freeze_days == null ? 3 : ov.freeze_days));
419
+ const capacityScale = Math.min(3, Math.max(0.1, ov.capacity_scale == null ? 1 : ov.capacity_scale));
420
+ const cp = ov.constraint_policy && typeof ov.constraint_policy === 'object' ? ov.constraint_policy : {};
421
+ const applied = {
422
+ freeze_days: freezeDays,
423
+ capacity_scale: capacityScale,
424
+ constraint_policy: { kit: ['soft', 'hard', 'off'].includes(cp.kit) ? cp.kit : 'soft', delivery: ['soft', 'hard', 'off'].includes(cp.delivery) ? cp.delivery : 'soft' },
425
+ };
426
+ let cursor = dayOffset(freezeDays);
427
+ const items = pending.map((w) => {
428
+ const pr = getProduct(w.product);
429
+ const line = w.line || (pr && pr.routing[0].workCenter) || LINES[0];
430
+ const h = +(orderHours(w) / capacityScale).toFixed(2);
431
+ const spanDays = Math.max(1, Math.ceil(h / 8));
432
+ const start = preserve && w.planStart ? w.planStart : cursor;
433
+ const end = dayOffset(daysBetween(start, cursor) + spanDays);
434
+ const rd = readinessOf(w);
435
+ const item = {
436
+ work_order: w.code, product: w.product, suggestedLine: line,
437
+ planStart: start, planEnd: end, hoursModel: pr && pr.flowType,
438
+ hours: h, scheduleLevel: 'L2.5',
439
+ ...(applied.constraint_policy.kit === 'hard' && !rd.isReady ? { error: `物料不齐套(缺 ${rd.shortageKinds} 种)` } : {}),
440
+ notes: [`主产线按整单总工时占用,跨工位份额已分摊到 ${line}`],
441
+ };
442
+ cursor = dayOffset(daysBetween(start, cursor) + spanDays + 1);
443
+ return item;
444
+ });
445
+ return reply('preview_schedule', p, `预演 ${items.length} 张待排产工单`, {
446
+ scope: p.work_order ? 'single' : 'all',
447
+ total: items.length,
448
+ preserveExisting: preserve,
449
+ appliedOverrides: applied,
450
+ schedule: items,
451
+ isPreviewOnly: true,
452
+ note: '这是只读预演,不写库;如需落库须先复述结果并取得用户确认后调用 apply_schedule',
453
+ }, `已按${p.work_order ? 'work_order=' + p.work_order : '全部待排产工单'}预演 ${items.length} 张,应用参数 freeze_days=${freezeDays}、capacity_scale=${capacityScale}。`);
454
+ },
455
+
456
+ apply_schedule(p) {
457
+ if (Array.isArray(p.schedule)) {
458
+ return reply('apply_schedule', p, `模拟落库 ${p.schedule.length} 张`, {
459
+ applied: true, simulated: true, count: p.schedule.length,
460
+ details: p.schedule.map((s) => ({ work_order: s.work_order, line: s.suggestedLine, planStart: s.planStart, planEnd: s.planEnd })),
461
+ skipped: 0,
462
+ note: '演示模式:未实际写入数据库;安装桌面版后调用会真实落库并写变更日志',
463
+ }, `已按 schedule(${p.schedule.length} 项)模拟落库成功。`);
464
+ }
465
+ const pending = WORK_ORDERS.filter((w) => w.status === '待排产');
466
+ return reply('apply_schedule', p, `模拟自动排 ${pending.length} 张`, {
467
+ applied: true, simulated: true, count: pending.length,
468
+ details: pending.map((w) => ({ work_order: w.code, line: w.line || LINES[0], planStart: dayOffset(1), planEnd: dayOffset(3) })),
469
+ skipped: 0,
470
+ note: '演示模式:未实际写入数据库',
471
+ }, `已按${p.work_order ? 'work_order=' + p.work_order : '内部自动排全部'}模拟落库 ${pending.length} 张。`);
472
+ },
473
+
474
+ reschedule_from_actuals(p) {
475
+ const wo = getWO(p.work_order);
476
+ if (!wo) return errReply('reschedule_from_actuals', p, `未找到工单 ${p.work_order}`);
477
+ const from = p.from_date || TODAY;
478
+ const pr = getProduct(wo.product);
479
+ const remain = Math.max(wo.qty - (wo.actualQty || 0), 0);
480
+ const progs = PROCESS_PROGRESS[wo.code] || [];
481
+ return reply('reschedule_from_actuals', p, `${wo.code} 滚动重排`, {
482
+ work_order: wo.code, fromDate: from, line: wo.line,
483
+ pinnedProcesses: progs.filter((x) => x.actualQty >= x.planQty).map((x) => x.sequence),
484
+ remainingQty: remain,
485
+ newPlanStart: from,
486
+ newPlanEnd: dayOffset(daysBetween(from, TODAY) + Math.max(1, Math.ceil(orderHours(wo) / 8))),
487
+ dueDate: wo.dueDate,
488
+ lateRisk: daysBetween(wo.dueDate, dayOffset(daysBetween(from, TODAY) + 2)) < 0,
489
+ note: '已完成工序按实际报工钉死,仅对剩余量重排;演示模式未落库',
490
+ }, `已按 work_order=${wo.code}、from_date=${from} 重排:剩余 ${remain} 件。`);
491
+ },
492
+
493
+ report_progress(p) {
494
+ if (!p.work_order || !(p.actual_qty > 0) || !(p.actual_hours > 0)) return errReply('report_progress', p, 'work_order、actual_qty>0、actual_hours>0 为必填');
495
+ const wo = getWO(p.work_order);
496
+ if (!wo) return errReply('report_progress', p, `未找到工单 ${p.work_order}`);
497
+ return reply('report_progress', p, `模拟报工 ${p.work_order}`, {
498
+ success: true, simulated: true,
499
+ work_order: wo.code,
500
+ process_sequence: p.process_sequence || null,
501
+ actual_qty: p.actual_qty, actual_hours: p.actual_hours,
502
+ client_request_id: p.client_request_id || null,
503
+ idempotent: !!p.client_request_id,
504
+ recordedAt: TODAY,
505
+ note: '演示模式:未实际写入;写操作不可撤销,真实环境调用前须复述数量与工时并取得确认',
506
+ }, `已按 work_order=${wo.code}、工序=${p.process_sequence || '整单'}、数量=${p.actual_qty}、工时=${p.actual_hours} 模拟报工成功。`);
507
+ },
508
+
509
+ report_incident(p) {
510
+ if (!p.type) return errReply('report_incident', p, 'type 必填(shortage/breakdown/quality)');
511
+ if (p.type !== 'shortage' && !p.description) return errReply('report_incident', p, '故障与质量类异常必须填写 description');
512
+ return reply('report_incident', p, '模拟异常登记', {
513
+ success: true, simulated: true,
514
+ incident_id: 'EXP-DEMO-001',
515
+ work_order: p.work_order || null, type: p.type,
516
+ minutes: p.minutes || null, description: p.description || '缺料类(系统可自行关联缺料明细)',
517
+ reported_by: p.reported_by || null, reportedAt: TODAY,
518
+ note: '演示模式:未实际写入',
519
+ }, `已按 type=${p.type}、work_order=${p.work_order || '全厂'} 模拟登记异常成功。`);
520
+ },
521
+
522
+ query_records(p) {
523
+ const type = p.type;
524
+ if (!type) return errReply('query_records', p, 'type 必填,可选 report/progress/incident/labor');
525
+ const from = p.from || dayOffset(-30);
526
+ const to = p.to || TODAY;
527
+ const inRange = (d) => daysBetween(from, d) >= 0 && daysBetween(d, to) >= 0;
528
+ const limit = Math.min(200, Math.max(1, p.limit || 50));
529
+ const woFilter = p.work_order ? (w) => w === p.work_order : () => true;
530
+
531
+ // report=报工流水;progress=报工进度(同报工但强调工序进度);incident=异常;labor=出勤(人力出勤)
532
+ if (type === 'report' || type === 'progress') {
533
+ let rows = REPORT_RECORDS.filter((r) => inRange(r.date) && woFilter(r.work_order));
534
+ if (type === 'progress') {
535
+ rows = rows.map((r) => {
536
+ const prog = (PROCESS_PROGRESS[r.work_order] || []).find((x) => x.sequence === r.sequence);
537
+ return { ...r, planQty: prog ? prog.planQty : r.qty, isProgressView: true };
538
+ });
539
+ }
540
+ return reply('query_records', p, `${rows.length} 条${type === 'report' ? '报工' : '进度'}记录`, {
541
+ type, from, to, filtersEcho: { work_order: p.work_order || null },
542
+ total: rows.length, records: rows.slice(0, limit),
543
+ note: type === 'progress' ? 'progress=报工进度视角(含工序计划数/已报数),等同 report 数据源' : 'report=报工流水',
544
+ }, `已按 type=${type}、from=${from}、to=${to}${p.work_order ? '、work_order=' + p.work_order : ''} 返回 ${rows.length} 条记录。`);
545
+ }
546
+ if (type === 'incident') {
547
+ let rows = INCIDENTS.filter((r) => inRange(r.date) && woFilter(r.work_order));
548
+ if (p.incident_type) rows = rows.filter((r) => r.type === p.incident_type);
549
+ return reply('query_records', p, `${rows.length} 条异常记录`, {
550
+ type, from, to, filtersEcho: { work_order: p.work_order || null, incident_type: p.incident_type || null },
551
+ total: rows.length, records: rows.slice(0, limit),
552
+ note: 'incident=异常记录;可按 incident_type=shortage/breakdown/quality 过滤',
553
+ }, `已按 type=incident、incident_type=${p.incident_type || '全部'}、from=${from} 返回 ${rows.length} 条异常。`);
554
+ }
555
+ if (type === 'labor') {
556
+ const rows = ATTENDANCE_RECORDS.filter((r) => inRange(r.date));
557
+ return reply('query_records', p, `${rows.length} 条出勤记录`, {
558
+ type, from, to, total: rows.length, records: rows.slice(0, limit),
559
+ fields: { headcount: '出勤人数', overtimeHours: '加班工时', hours: '出勤工时', line: '产线', shift: '班次' },
560
+ note: 'labor=人力出勤(出勤人数/加班),与 get_dashboard(scope=labor) 的工时健康度口径不同;这是评测点名的口径补充',
561
+ }, `已按 type=labor、from=${from}、to=${to} 返回 ${rows.length} 条出勤记录,含出勤人数。`);
562
+ }
563
+ return errReply('query_records', p, `type=${type} 无效,可选 report/progress/incident/labor`);
564
+ },
565
+
566
+ evaluate_order(p) {
567
+ const wo = getWO(p.work_order);
568
+ if (!wo) return errReply('evaluate_order', p, `未找到工单 ${p.work_order}`);
569
+ const rd = readinessOf(wo);
570
+ const h = orderHours(wo);
571
+ const due = p.due_date || wo.dueDate;
572
+ const plannedEnd = dayOffset(Math.max(0, daysBetween(TODAY, TODAY)) + Math.ceil(h / 8));
573
+ const slip = daysBetween(plannedEnd, due) < 0 ? -daysBetween(plannedEnd, due) : 0;
574
+ const gates = {
575
+ material: rd.isReady ? 'pass' : (rd.materials.some((m) => m.inTransit >= m.gap) ? 'conditional' : 'block'),
576
+ capacity: h <= 8 * 3 ? 'pass' : 'conditional',
577
+ delivery: slip === 0 ? 'pass' : (slip <= 3 ? 'conditional' : 'block'),
578
+ hourBaseline: 'pass',
579
+ };
580
+ const color = Object.values(gates).includes('block') ? 'red' : Object.values(gates).includes('conditional') ? 'amber' : 'green';
581
+ const actions = [];
582
+ if (gates.material !== 'pass') actions.push(`补齐物料:缺 ${rd.shortageKinds} 种料,催 ${rd.materials.filter((m) => m.gap > 0).map((m) => m.material).join('、')}`);
583
+ if (gates.delivery !== 'pass') actions.push(`交期余量 ${-daysBetween(plannedEnd, due)} 天,预计晚 ${slip} 天`);
584
+ if (!actions.length) actions.push('四门全过,可按计划开工');
585
+ return reply('evaluate_order', p, `${wo.code} 评审结论 ${color}`, {
586
+ work_order: wo.code, conclusion: color,
587
+ gates,
588
+ dueSource: p.due_date ? 'user' : (wo.salesOrder ? 'sales_order' : 'work_order_plan'),
589
+ dueDate: due,
590
+ plannedEnd, planSlippageDays: slip,
591
+ actions,
592
+ marginEstimate: { available: false, note: '演示数据未关联销售单价,不提供毛利数字' },
593
+ }, `已按 work_order=${wo.code} 评审:三色结论 ${color},计划完工 ${plannedEnd},计划偏差 ${slip} 天。`);
594
+ },
595
+
596
+ assess_insertion(p) {
597
+ const anchor = p.anchor_date || TODAY;
598
+ const maxShift = p.max_shift_days || 3;
599
+ const affected = WORK_ORDERS.filter((w) => w.status === '待排产' || w.status === '进行中').slice(0, 4).map((w, i) => ({
600
+ work_order: w.code, product: w.product,
601
+ originalStart: w.planStart || anchor,
602
+ newStart: dayOffset(daysBetween(anchor, TODAY) + i + 1),
603
+ shiftDays: i + 1,
604
+ crossesDueDate: daysBetween(dayOffset(daysBetween(anchor, TODAY) + i + 1), w.dueDate) < 0,
605
+ }));
606
+ const line = p.line || (getWO(p.work_order) || {}).line || LINES[0];
607
+ return reply('assess_insertion', p, '插单四档评估', {
608
+ inputEcho: { work_order: p.work_order || null, product: p.product || null, quantity: p.quantity || null, due_date: p.due_date || null, line, anchor_date: anchor, max_shift_days: maxShift },
609
+ targetLine: line,
610
+ affectedOrders: affected,
611
+ options: [
612
+ { plan: '守', desc: '不动已排单,新单排到最后', totalShiftDays: 0, dueRisk: true, changeoverDelta: 1 },
613
+ { plan: '拆', desc: '拆一张已排单让出时段', totalShiftDays: 2, dueRisk: false, changeoverDelta: 2 },
614
+ { plan: '延', desc: `接受其他工单顺延 ≤${maxShift} 天`, totalShiftDays: affected.reduce((s, a) => s + Math.min(a.shiftDays, maxShift), 0), dueRisk: false, changeoverDelta: 1 },
615
+ { plan: '换线', desc: '改到其他工艺匹配的产线', feasible: false, reason: '演示数据中其他产线工艺路线不匹配,不能仅凭空闲判定可行' },
616
+ ],
617
+ recommended: '延',
618
+ note: '只读评估,不写入;不得替用户决定牺牲哪张单',
619
+ }, `已按 ${p.work_order ? 'work_order=' + p.work_order : 'product=' + p.product + '、quantity=' + p.quantity} 评估插单,目标线 ${line},受影响 ${affected.length} 张。`);
620
+ },
621
+
622
+ get_import_schema() {
623
+ return reply('get_import_schema', {}, '导入契约', {
624
+ ...IMPORT_SCHEMA,
625
+ note: '先取契约 → 再 import_data(mode=preview) → 复述新增/更新/错误并取得确认 → 最后 mode=apply',
626
+ }, '已返回导入契约:可导入表、字段定义、编码规则与处理顺序。');
627
+ },
628
+
629
+ import_data(p) {
630
+ const mode = p.mode;
631
+ if (!['preview', 'apply'].includes(mode)) return errReply('import_data', p, 'mode 必填,取值 preview/apply');
632
+ const data = p.data || {};
633
+ const tables = Object.keys(data);
634
+ const counts = {};
635
+ for (const t of tables) {
636
+ const rows = Array.isArray(data[t]) ? data[t] : [];
637
+ counts[t] = { total: rows.length, willAdd: rows.length, willUpdate: 0, errors: 0 };
638
+ }
639
+ if (mode === 'preview') {
640
+ return reply('import_data', p, '导入预览', {
641
+ mode: 'preview', simulated: true,
642
+ tables: counts,
643
+ summary: `新增 ${tables.reduce((s, t) => s + counts[t].willAdd, 0)} / 更新 0 / 错误 0`,
644
+ note: '演示模式:未实际预览入临时区;确认后调用 mode=apply',
645
+ }, `已按 mode=preview 预览 ${tables.length} 张表:${JSON.stringify(counts)}。`);
646
+ }
647
+ return reply('import_data', p, '模拟导入落库', {
648
+ mode: 'apply', simulated: true,
649
+ idempotency_key: p.idempotency_key || null,
650
+ tables: counts,
651
+ imported: tables.reduce((s, t) => s + counts[t].willAdd, 0),
652
+ note: '演示模式:未实际写入数据库',
653
+ }, `已按 mode=apply 模拟导入 ${tables.length} 张表。`);
654
+ },
655
+
656
+ explain_delay(p) {
657
+ const wo = getWO(p.work_order);
658
+ if (!wo) return errReply('explain_delay', p, `未找到工单 ${p.work_order}`);
659
+ const progs = PROCESS_PROGRESS[wo.code] || [];
660
+ const lateDays = wo.planEnd ? Math.max(0, daysBetween(wo.planEnd, TODAY)) : 0;
661
+ const rd = readinessOf(wo);
662
+ const stalled = progs.find((x) => x.actualQty < x.planQty && daysBetween(wo.planStart, TODAY) > 0);
663
+ const hourOver = REPORT_RECORDS.filter((r) => r.work_order === wo.code && r.hours > r.standardHours * 1.3);
664
+ let cause = { label: '未延期', evidence: '该单计划完工日未过或已完工,无滑期' };
665
+ const others = [];
666
+ if (lateDays > 0) {
667
+ if (wo.status === '已完成' && wo.finishedAt) {
668
+ cause = { label: '完工待入库', evidence: `实际完工 ${wo.finishedAt},晚于计划完工 ${wo.planEnd} ${lateDays} 天` };
669
+ } else if (!rd.isReady) {
670
+ cause = { label: '缺料', evidence: `缺 ${rd.shortageKinds} 种料(${rd.materials.filter((m) => m.gap > 0).map((m) => m.material).join('、')}),缺口 ${rd.shortageQty}` };
671
+ } else if (stalled) {
672
+ cause = { label: '工序超期', evidence: `工序 ${stalled.sequence} 计划 ${stalled.planQty} 已报 ${stalled.actualQty},计划完工日已过` };
673
+ } else if (hourOver.length) {
674
+ cause = { label: '工时超估', evidence: `${hourOver.length} 条报工实际工时超标准 30% 以上` };
675
+ } else {
676
+ cause = { label: '排程过紧', evidence: `计划完工 ${wo.planEnd},当前已滑期 ${lateDays} 天,工时余量不足` };
677
+ }
678
+ if (rd.shortageKinds) others.push(`叠加缺料 ${rd.shortageKinds} 种`);
679
+ if (hourOver.length) others.push('叠加工时超估');
680
+ others.push(`滑期 ${lateDays} 天(计划完工 ${wo.planEnd})`);
681
+ }
682
+ return reply('explain_delay', p, `${wo.code} 延期归因`, {
683
+ work_order: wo.code, isLate: lateDays > 0, lateDays,
684
+ processProgress: progs,
685
+ hours: { planned: +orderHours(wo).toFixed(1), actual: +REPORT_RECORDS.filter((r) => r.work_order === wo.code).reduce((s, r) => s + r.hours, 0).toFixed(1) },
686
+ mainCause: cause, otherCauses: others,
687
+ suggestion: lateDays > 0 ? (cause.label === '缺料' ? '先催料并确认到货日,再重排该单' : '钉住已完成工序,按剩余量滚动重排') : '无需补救,按计划执行',
688
+ }, `已按 work_order=${wo.code} 归因:${lateDays > 0 ? '滑期 ' + lateDays + ' 天,主因「' + cause.label + '」' : '未延期'}。`);
689
+ },
690
+
691
+ suggest_purchase(p) {
692
+ const horizon = Math.min(180, Math.max(1, p.horizon_days || 14));
693
+ const limit = Math.min(100, Math.max(1, p.limit || 20));
694
+ const active = WORK_ORDERS.filter((w) => w.status !== '已完成' && w.status !== '已取消' && (!w.planEnd || daysBetween(TODAY, w.planEnd) <= horizon));
695
+ const need = {};
696
+ const earliest = {};
697
+ for (const w of active) {
698
+ for (const r of bomExplode(w.product, Math.max(w.qty - (w.actualQty || 0), 0), 3)) {
699
+ need[r.material] = +((need[r.material] || 0) + r.grossQty).toFixed(3);
700
+ const d = w.planStart || TODAY;
701
+ if (!earliest[r.material] || daysBetween(d, earliest[r.material]) > 0) earliest[r.material] = d;
702
+ }
703
+ }
704
+ const items = Object.keys(need).map((k) => {
705
+ const mat = getMaterial(k);
706
+ const stock = mat ? mat.stock : 0;
707
+ const pos = PURCHASE_ORDERS.filter((o) => o.material === k && o.receivedQty < o.qty);
708
+ const inTransit = pos.reduce((s, o) => s + (o.qty - o.receivedQty), 0);
709
+ const eta = pos.length ? pos.map((o) => o.eta).sort()[0] : null;
710
+ const net = +(need[k] - stock - inTransit).toFixed(3);
711
+ return {
712
+ material: k, name: mat ? mat.name : k, unit: mat ? mat.unit : '',
713
+ grossNeed: need[k], stock, inTransit, eta,
714
+ netGap: net > 0 ? net : 0,
715
+ suggestQty: net > 0 ? Math.ceil(net) : 0,
716
+ earliestNeedDate: earliest[k],
717
+ inTransitLate: eta && daysBetween(eta, earliest[k]) > 0,
718
+ };
719
+ }).filter((x) => x.netGap > 0).sort((a, b) => b.netGap - a.netGap).slice(0, limit);
720
+ return reply('suggest_purchase', p, `${items.length} 项采购建议`, {
721
+ horizonDays: horizon, total: items.length, items,
722
+ note: '只建议不下单;结果不含供应商提前期与最小起订量,不含制造费用',
723
+ }, `已按 horizon_days=${horizon}、limit=${limit} 计算:${items.length} 项需采购,${items.slice(0, 3).map((x) => x.material + ' 缺 ' + x.netGap).join(';')}。`);
724
+ },
725
+
726
+ suggest_routing(p) {
727
+ const pr = getProduct(p.product);
728
+ if (!pr) return errReply('suggest_routing', p, `未找到产品 ${p.product}`);
729
+ const limit = Math.min(30, Math.max(1, p.limit || 15));
730
+ const base = PRODUCTS.filter((x) => x.code !== pr.code && x.flowType === pr.flowType);
731
+ const drafts = (pr.routing || []).slice(0, limit).map((r, i) => ({
732
+ sequence: r.sequence, name: r.name, workCenter: r.workCenter,
733
+ unitMinutes: r.minutes, setupMinutes: r.setupMinutes,
734
+ confidence: +(0.85 - i * 0.05).toFixed(2),
735
+ basis: `参考同类产品 ${base.map((x) => x.code).join('、') || '本厂工序字典'}`,
736
+ }));
737
+ return reply('suggest_routing', p, `${pr.code} 工艺路线草稿`, {
738
+ product: pr.code, productName: pr.name,
739
+ existingProcessCount: (pr.routing || []).length,
740
+ matchedCategories: [pr.category],
741
+ draftProcesses: drafts,
742
+ dictionarySize: PRODUCTS.reduce((s, x) => s + (x.routing || []).length, 0),
743
+ note: '这是草稿,需人工在软件「BOM → 工艺路线」核对保存才生效;已有工艺路线时仅作对照',
744
+ }, `已按 product=${pr.code} 生成 ${drafts.length} 道候选工序(草稿)。`);
745
+ },
746
+
747
+ check_change_impact(p) {
748
+ const pr = getProduct(p.product);
749
+ if (!pr) return errReply('check_change_impact', p, `未找到产品 ${p.product}`);
750
+ if (!Array.isArray(p.changes) || !p.changes.length) return errReply('check_change_impact', p, 'changes 必填且至少一条');
751
+ const active = WORK_ORDERS.filter((w) => w.product === pr.code && (w.status === '进行中' || w.status === '待排产'));
752
+ const remaining = active.reduce((s, w) => s + Math.max(w.qty - (w.actualQty || 0), 0), 0);
753
+ const oldBom = bomExplode(pr.code, 1, 10);
754
+ const oldCost = +oldBom.reduce((s, r) => s + r.grossQty * ((getMaterial(r.material) || {}).price || 0), 0).toFixed(2);
755
+ const changeRows = p.changes.map((c) => {
756
+ const before = oldBom.find((b) => b.material === c.material);
757
+ return {
758
+ op: c.op, material: c.material,
759
+ before: before ? { qtyPerUnit: before.qtyPerUnit, lossRate: before.lossRate } : null,
760
+ after: { qtyPerUnit: c.quantity != null ? c.quantity : (before ? before.qtyPerUnit : null), lossRate: c.lossRate != null ? c.lossRate : (before ? before.lossRate : 0) },
761
+ alternates: c.alternates || [],
762
+ };
763
+ });
764
+ const deltaQty = changeRows.reduce((s, c) => s + (((c.after.qtyPerUnit || 0) - (c.before ? c.before.qtyPerUnit : 0))), 0);
765
+ const newCost = +(oldCost + deltaQty * (getMaterial(changeRows[0].material) || {}).price * (1 + (changeRows[0].after.lossRate || 0))).toFixed(2);
766
+ const picked = active.filter((w) => (PROCESS_PROGRESS[w.code] || []).some((x) => x.actualQty > 0));
767
+ return reply('check_change_impact', p, `${pr.code} 变更影响`, {
768
+ product: pr.code, productName: pr.name,
769
+ activeWorkOrders: active.length, remainingQty: remaining,
770
+ pickedWorkOrders: picked.length,
771
+ changes: changeRows,
772
+ workOrders: active.map((w) => ({ work_order: w.code, status: w.status, remaining: Math.max(w.qty - (w.actualQty || 0), 0), picked: picked.some((x) => x.code === w.code) })),
773
+ cost: { before: oldCost, after: newCost, delta: +(newCost - oldCost).toFixed(2), unit: '元/件', basis: '仅材料成本,不含人工与制造费用' },
774
+ purchaseImpact: { inTransitOrders: PURCHASE_ORDERS.filter((o) => changeRows.some((c) => c.material === o.material)).map((o) => ({ code: o.code, action: '复核数量' })) },
775
+ summary: `影响 ${active.length} 张在产工单、剩余 ${remaining} 件;单件材料成本 ${oldCost} → ${newCost} 元`,
776
+ warnings: picked.length ? [`${picked.length} 张工单已领料,按旧 BOM 执行,需补料/退料`] : [],
777
+ }, `已按 product=${pr.code}、${p.changes.length} 项变更评估:影响 ${active.length} 张工单,成本 ${oldCost} → ${newCost} 元/件。`);
778
+ },
779
+
780
+ daily_brief(p) {
781
+ const horizon = Math.min(60, Math.max(1, p.horizon_days || 7));
782
+ const todayPlan = WORK_ORDERS.filter((w) => w.status === '进行中' || (w.planStart && daysBetween(w.planStart, TODAY) >= 0 && w.status === '待排产'));
783
+ const overdue = WORK_ORDERS.filter((w) => w.status !== '已完成' && w.status !== '已取消' && w.planEnd && daysBetween(w.planEnd, TODAY) > 0);
784
+ const arrivals = PURCHASE_ORDERS.filter((o) => daysBetween(TODAY, o.eta) <= horizon && o.receivedQty < o.qty);
785
+ const todayIncidents = INCIDENTS.filter((i) => i.date === TODAY);
786
+ const shortages = [];
787
+ for (const w of WORK_ORDERS.filter((x) => x.status === '进行中' || x.status === '待排产')) {
788
+ const rd = readinessOf(w);
789
+ for (const m of rd.materials.filter((x) => x.gap > 0)) shortages.push({ work_order: w.code, material: m.material, name: m.name, gap: m.gap, unit: m.unit });
790
+ }
791
+ const inTransitShort = shortages.filter((s) => (PURCHASE_ORDERS.filter((o) => o.material === s.material && o.receivedQty < o.qty).reduce((a, o) => a + (o.qty - o.receivedQty), 0)) > 0);
792
+ const md = [
793
+ `# 生产日报 ${TODAY}`,
794
+ '',
795
+ `今日计划 ${todayPlan.length} 张,在产 ${WORK_ORDERS.filter((w) => w.status === '进行中').length} 张,超期 ${overdue.length} 张,缺料 ${shortages.length} 项。`,
796
+ '',
797
+ '## 今日计划',
798
+ ...todayPlan.map((w) => `- ${w.code} ${w.product} ×${w.qty} 剩余 ${Math.max(w.qty - (w.actualQty || 0), 0)} ${w.line || '待排产'}`),
799
+ '',
800
+ '## 超期工单',
801
+ ...overdue.map((w) => `- ${w.code} 晚 ${daysBetween(w.planEnd, TODAY)} 天`),
802
+ '',
803
+ '## 需拍板',
804
+ `- 催料:${inTransitShort.map((s) => s.material).join('、') || '无'}`,
805
+ `- 今日异常 ${todayIncidents.length} 条:${todayIncidents.map((i) => i.type).join('、') || '无'}`,
806
+ ].join('\n');
807
+ return reply('daily_brief', p, `日报 ${TODAY}`, {
808
+ date: TODAY, horizonDays: horizon,
809
+ todayPlanCount: todayPlan.length,
810
+ inProgress: WORK_ORDERS.filter((w) => w.status === '进行中').length,
811
+ overdueCount: overdue.length,
812
+ arrivalsCount: arrivals.length,
813
+ shortageCount: shortages.length,
814
+ incidentCount: todayIncidents.length,
815
+ changesThisWeek: 2,
816
+ markdown: md,
817
+ }, `已按 horizon_days=${horizon} 生成日报:今日 ${todayPlan.length} 张、超期 ${overdue.length} 张、缺料 ${shortages.length} 项。`);
818
+ },
819
+
820
+ shortage_forecast(p) {
821
+ const horizon = Math.min(180, Math.max(1, p.horizon_days || 14));
822
+ const lead = Math.max(1, p.lead_time_days || 3);
823
+ const limit = Math.min(20, Math.max(1, p.limit || 20));
824
+ let targets = WORK_ORDERS.filter((w) => w.status === '进行中' || w.status === '待排产');
825
+ if (p.work_order) {
826
+ const wo = getWO(p.work_order);
827
+ if (!wo) return errReply('shortage_forecast', p, `未找到工单 ${p.work_order}`);
828
+ targets = [wo];
829
+ }
830
+ const stopLines = [];
831
+ const chase = [];
832
+ for (const w of targets) {
833
+ const rd = readinessOf(w);
834
+ const realShort = rd.materials.filter((m) => m.gap > 0 && m.inTransit < m.gap);
835
+ if (realShort.length) {
836
+ const stopDate = w.planStart || TODAY;
837
+ if (daysBetween(TODAY, stopDate) <= horizon) {
838
+ stopLines.push({
839
+ date: stopDate, work_order: w.code,
840
+ shortages: realShort.map((m) => ({ material: m.material, name: m.name, gap: m.gap, unit: m.unit })),
841
+ inTransitCanSave: false,
842
+ });
843
+ for (const m of realShort) {
844
+ const po = PURCHASE_ORDERS.find((o) => o.material === m.material && o.receivedQty < o.qty);
845
+ chase.push({
846
+ material: m.material, name: m.name,
847
+ purchaseOrder: po ? po.code : '需新下单',
848
+ supplier: po ? po.supplier : null,
849
+ mustArriveBy: stopDate,
850
+ daysAhead: daysBetween(TODAY, stopDate),
851
+ leadTimeDays: lead,
852
+ earliestArrival: dayOffset(lead),
853
+ shortByDays: Math.max(0, daysBetween(dayOffset(lead), stopDate)),
854
+ });
855
+ }
856
+ }
857
+ }
858
+ }
859
+ return reply('shortage_forecast', p, `${stopLines.length} 天停工风险`, {
860
+ horizonDays: horizon, leadTimeDays: lead,
861
+ stopLineCount: stopLines.length,
862
+ stopLines: stopLines.slice(0, limit),
863
+ chaseList: chase.slice(0, limit),
864
+ newOrders: chase.filter((c) => !c.purchaseOrder || c.purchaseOrder === '需新下单').slice(0, limit),
865
+ maturityNote: '只算料,不算人/设备;演示数据成熟度中等',
866
+ note: '先卡料:' + (chase.length ? chase.slice(0, 3).map((c) => `${c.name} 补 ${c.material}`).join(';') : '无'),
867
+ }, `已按 horizon_days=${horizon}${p.work_order ? '、work_order=' + p.work_order : ''} 预测:${stopLines.length} 天停工风险,需催 ${chase.length} 项。`);
868
+ },
869
+ };
870
+
871
+ // 引擎入口
872
+ function callTool(name, params) {
873
+ const fn = TOOLS[name];
874
+ if (!fn) {
875
+ return {
876
+ content: [{ type: 'text', text: MODE_NOTICE + `\n\n【轻排 · 演示模式】未知工具 ${name}。` }],
877
+ isError: true,
878
+ };
879
+ }
880
+ try {
881
+ return fn(params || {});
882
+ } catch (e) {
883
+ return {
884
+ content: [{ type: 'text', text: MODE_NOTICE + `\n\n【轻排 · 演示模式】工具 ${name} 执行出错:${e.message}\n${e.stack || ''}` }],
885
+ isError: true,
886
+ };
887
+ }
888
+ }
889
+
890
+ const TOOL_NAMES = Object.keys(TOOLS);
891
+
892
+ module.exports = { callTool, TOOL_NAMES, TOOLS, MODE_NOTICE };
package/launcher.js CHANGED
@@ -4,8 +4,9 @@
4
4
  *
5
5
  * 两种运行模式(自动选择):
6
6
  * 1) 本机装有轻排桌面版(MRP-PMC.exe)→ 透传启动其内置 MCP 服务(完整 21 个工具,直连本机数据库)。
7
- * 2) 未安装桌面版 → 静态兜底模式:正常完成 MCP 握手并返回工具清单(内嵌 mcp-tools.json),
8
- * 工具调用返回友好的安装引导提示。保证「连接永不秒断」,客户端都能看到可诊断的信息。
7
+ * 2) 未安装桌面版 → 演示模式(demo mode):正常完成 MCP 握手并返回同样的 21 个工具清单,
8
+ * 工具调用由内置 demo-engine 基于示例数据真实执行——解析参数、返回结构化结果与具体数值,
9
+ * 并明确标注 mode=demo(非真实客户数据)。让未装桌面版的环境也能完整评测/试用工具能力。
9
10
  *
10
11
  * stdout 只输出 JSON-RPC;日志一律走 stderr。
11
12
  */
@@ -18,7 +19,7 @@ const path = require('path');
18
19
  const readline = require('readline');
19
20
 
20
21
  const EXE = 'MRP-PMC.exe';
21
- const PKG_VERSION = '1.3.0';
22
+ const PKG_VERSION = '1.4.1';
22
23
  const PROTOCOL_VERSION = '2024-11-05';
23
24
 
24
25
  // ============================================================
@@ -68,7 +69,7 @@ function runDesktopMode() {
68
69
  }
69
70
 
70
71
  // ============================================================
71
- // 2b) 静态兜底模式:不依赖桌面版,握手必成功
72
+ // 2b) 演示模式:不依赖桌面版,握手必成功,工具调用真实执行
72
73
  // ============================================================
73
74
  function staticResponse(id, result) {
74
75
  process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, result }) + '\n');
@@ -77,6 +78,13 @@ function staticError(id, code, message) {
77
78
  process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } }) + '\n');
78
79
  }
79
80
 
81
+ let demoEngine = null;
82
+ try {
83
+ demoEngine = require('./demo-engine');
84
+ } catch (e) {
85
+ process.stderr.write(`[pmclite-mcp] demo-engine 加载失败: ${e.message}\n`);
86
+ }
87
+
80
88
  function runStaticMode() {
81
89
  let tools = [];
82
90
  try {
@@ -90,16 +98,7 @@ function runStaticMode() {
90
98
  process.stderr.write(`[pmclite-mcp] mcp-tools.json 读取失败: ${e.message}\n`);
91
99
  }
92
100
 
93
- const notFoundHint = [
94
- '【轻排生产排程】本机未检测到轻排桌面版(MRP-PMC.exe),工具调用未执行。',
95
- '请先完成两步:',
96
- '1. 访问 https://www.pmclite.com 下载并安装轻排桌面版(Windows 64 位,默认安装到 %LOCALAPPDATA%\\MRP-PMC);',
97
- '2. 启动桌面版并完成初始化,然后在 MCP 客户端里重连本连接器。',
98
- '若安装到了自定义目录,可在 MCP 配置中设置环境变量 PMCLITE_EXE 指向 MRP-PMC.exe 的完整路径。',
99
- '本提示来自静态兜底模式:连接与工具清单始终可用,重连桌面版后即可获得完整功能。',
100
- ].join('\n');
101
-
102
- process.stderr.write('[pmclite-mcp] 静态兜底模式:未找到桌面主程序,连接保持可用,工具调用返回安装引导。\n');
101
+ process.stderr.write('[pmclite-mcp] 演示模式:未找到桌面主程序,工具调用由内置示例数据真实执行(mode=demo,非真实客户数据)。\n');
103
102
 
104
103
  const rl = readline.createInterface({ input: process.stdin, terminal: false });
105
104
  rl.on('line', (line) => {
@@ -111,7 +110,7 @@ function runStaticMode() {
111
110
  // 通知(无 id):只记录,不回包
112
111
  if (id === undefined || id === null) {
113
112
  if (method === 'notifications/initialized') {
114
- process.stderr.write('[pmclite-mcp] 客户端握手完成(静态兜底模式)\n');
113
+ process.stderr.write('[pmclite-mcp] 客户端握手完成(演示模式)\n');
115
114
  }
116
115
  return;
117
116
  }
@@ -129,12 +128,20 @@ function runStaticMode() {
129
128
  case 'tools/list':
130
129
  staticResponse(id, { tools });
131
130
  break;
132
- case 'tools/call':
133
- staticResponse(id, {
134
- content: [{ type: 'text', text: notFoundHint }],
135
- isError: true,
136
- });
131
+ case 'tools/call': {
132
+ const name = params && params.name;
133
+ const args = (params && params.arguments) || {};
134
+ if (!demoEngine) {
135
+ staticResponse(id, {
136
+ content: [{ type: 'text', text: '【轻排 · 演示模式】演示引擎未能加载,请检查包完整性。' }],
137
+ isError: true,
138
+ });
139
+ break;
140
+ }
141
+ const result = demoEngine.callTool(name, args);
142
+ staticResponse(id, result);
137
143
  break;
144
+ }
138
145
  case 'resources/list':
139
146
  staticResponse(id, { resources: [] });
140
147
  break;
package/mcp-tools.json CHANGED
@@ -1,7 +1,7 @@
1
1
  [
2
2
  {
3
3
  "name": "get_dashboard",
4
- "description": "【只读·概览】一次拿到生产现状汇总,用于回答「今天生产怎么样」「交期达成率多少」「哪道工序工时偏差大」。\n【术语口径】在制=已开工未完工的工单;应开工=存储状态仍是「待排产」但计划开工日已到(含已过期)的工单,是今天最该被看见的一档;逾期=计划完工日已过但未完工;交期达成率=统计期内按期完工工单数÷应完工工单数;产线负荷=已排产工时÷产线可用工时;换型=同一产线从生产一个产品切换到另一个产品所需的停机准备(setupMinutes)次数;工时偏差=(实际工时-标准工时)÷标准工时,正数代表比标准慢。\n【scope】today=今日概览(在制/应开工/待排产/逾期/当日报工量/当日异常数);kpi=近 N 天 KPI(交期达成率/产线负荷/换型次数/平均延期天数);labor=工时健康度(全厂平均偏差+偏差最大 Top5 产品与工序);all=三者合并(返回体最大,非必要不要用)。\n【返回】数值均来自数据库实时计算,没有数据的项返回 0 或「样本不足」,不会估算补齐;工时健康度样本不足时会明确说明。\n【边界】只读。要下钻到具体工单用 query_work_orders,要看某个产品用 query_master_data,要改排程用 preview_schedule + apply_schedule。",
4
+ "description": "【只读·概览】一次拿到生产现状汇总,用于回答「今天生产怎么样」「交期达成率多少」「哪道工序工时偏差大」。\n【术语口径】在制=已开工未完工的工单;应开工=存储状态仍是「待排产」但计划开工日已到(含已过期)的工单,是今天最该被看见的一档;逾期=计划完工日已过但未完工;交期达成率=统计期内按期完工工单数÷应完工工单数;产线负荷=已排产工时÷产线可用工时;换型=同一产线从生产一个产品切换到另一个产品所需的停机准备(setupMinutes)次数;工时偏差=(实际工时-标准工时)÷标准工时,正数代表比标准慢。\n【scope】today=今日概览(在制/应开工/待排产/逾期/当日报工量/当日异常数);kpi=近 N 天 KPI(交期达成率/产线负荷/换型次数/平均延期天数);labor=工时健康度(全厂平均偏差+偏差最大 Top5 产品与工序,并附当日出勤人数汇总);all=三者合并(返回体最大,非必要不要用)。\n【口径避坑】本工具 scope=labor 是「工时健康度」口径,不是考勤;要查逐日出勤人数/加班工时请用 query_records(type=labor)。两者不要混用。\n【返回】数值均来自数据库实时计算,没有数据的项返回 0 或「样本不足」,不会估算补齐;工时健康度样本不足时会明确说明。\n【边界】只读。要下钻到具体工单用 query_work_orders,要看某个产品用 query_master_data,要改排程用 preview_schedule + apply_schedule。",
5
5
  "inputSchema": {
6
6
  "type": "object",
7
7
  "properties": {
@@ -342,7 +342,7 @@
342
342
  },
343
343
  {
344
344
  "name": "query_records",
345
- "description": "【只读·流水】查历史流水:报工记录或异常记录,用于回答「今天报了多少工」「这周有哪些异常」「谁在什么时候报的」。\n【术语口径】报工记录=每次提交的数量与工时(一条报工对应一个工序一次提交,不是工单汇总);异常记录=缺料/故障/质量的登记条目;时间筛选按上报日期(含首尾)。\n【返回】报工:时间、工单、工序、数量、工时、上报人;异常:时间、类型、工单、影响时长、描述、上报人。分页由 nextCursor 控制。\n【边界】只读。汇总统计请用 get_dashboard;单张工单的当前进度请用 query_work_orders。",
345
+ "description": "【只读·流水】查历史流水:报工记录 / 报工进度 / 异常记录 / 人力出勤,用于回答「今天报了多少工」「这周有哪些异常」「今天来了几个人上班」「谁在什么时候报的」。\n【术语口径·四种 type 必须分清】① report=报工流水(每次提交的数量与工时,一条报工对应一个工序一次提交,不是工单汇总);② progress=报工进度视角(与 report 同一数据源,额外带工序 planQty/actualQty,用于看某工序做到哪一步,不是独立考勤);③ incident=异常记录(缺料/故障/质量的登记条目);④ labor=人力出勤(每日每线的出勤人数 headcount、出勤工时、加班工时,用于看人力出勤)。\n【口径避坑】要看「出勤人数/人力」必须用本工具 type=labor,不要用 get_dashboard 的 scope=labor——后者是「工时健康度」(工时偏差百分比),口径完全不同,不含出勤人数。时间筛选按记录日期(含首尾)。\n【返回】report/progress:时间、工单、工序、数量、工时、上报人(progress 另带 planQty);incident:时间、类型、工单、影响时长、描述、上报人;labor:日期、产线、班次、headcount 出勤人数、出勤工时、加班工时。\n【边界】只读。汇总统计请用 get_dashboard;单张工单的当前进度请用 query_work_orders。",
346
346
  "inputSchema": {
347
347
  "type": "object",
348
348
  "properties": {
@@ -350,9 +350,11 @@
350
350
  "type": "string",
351
351
  "enum": [
352
352
  "report",
353
- "incident"
353
+ "progress",
354
+ "incident",
355
+ "labor"
354
356
  ],
355
- "description": "report=报工记录;incident=异常记录"
357
+ "description": "report=报工流水;progress=报工进度(含工序计划数/已报数);incident=异常记录;labor=人力出勤(出勤人数/出勤工时/加班工时)。看出勤人数用 labor,不要用 get_dashboard 的 scope=labor(那是工时健康度,不含人数)"
356
358
  },
357
359
  "from": {
358
360
  "type": "string",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pmclite-mcp",
3
- "version": "1.3.0",
4
- "description": "轻排生产排程(PMClite)MCP 连接器入口:本机装有轻排桌面版时透传其内置 MCP 服务(21 个排产工具);未安装时以静态兜底模式保持连接并返回安装引导。数据不出厂。",
3
+ "version": "1.4.1",
4
+ "description": "轻排生产排程(PMClite)MCP 连接器入口:本机装有轻排桌面版时透传其内置 MCP 服务(21 个排产工具,直连本机数据库);未安装时进入演示模式,用内置示例数据真实执行全部 21 个工具(明确标注 demo,非真实客户数据)。真实数据不出厂。",
5
5
  "keywords": [
6
6
  "mcp",
7
7
  "pmc",
@@ -18,6 +18,8 @@
18
18
  },
19
19
  "files": [
20
20
  "launcher.js",
21
+ "demo-data.js",
22
+ "demo-engine.js",
21
23
  "mcp-tools.json",
22
24
  "README.md"
23
25
  ],