pmclite-mcp 1.4.2 → 1.5.0

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.
Files changed (5) hide show
  1. package/README.md +56 -56
  2. package/demo-engine.js +1264 -1023
  3. package/launcher.js +173 -173
  4. package/mcp-tools.json +195 -1
  5. package/package.json +40 -40
package/demo-engine.js CHANGED
@@ -1,1023 +1,1264 @@
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
- // ---------- 排序策略(P2 多方案比选,与桌面版 compare_schedule_strategies 同口径) ----------
157
- const STRATEGY_IDS = ['current', 'edd', 'changeover_cluster', 'spt'];
158
- const STRATEGY_LABELS = {
159
- current: '现状默认(按默认优先级)',
160
- edd: '交期优先 EDD',
161
- changeover_cluster: '换型聚类(同产品连排)',
162
- spt: '最短工时优先 SPT',
163
- };
164
- const CHANGEOVER_MINUTES = 30; // 演示口径:同产线切换产品固定 30 分钟
165
-
166
- // 稳定排序:不改入参集合,只改顺序(current = 保持传入顺序)
167
- function sortPending(pending, strategy) {
168
- const arr = pending.slice();
169
- if (strategy === 'edd') {
170
- arr.sort((a, b) => String(a.dueDate || '9999-12-31').localeCompare(String(b.dueDate || '9999-12-31')));
171
- } else if (strategy === 'changeover_cluster') {
172
- const groups = new Map();
173
- for (const w of arr) {
174
- if (!groups.has(w.product)) groups.set(w.product, []);
175
- groups.get(w.product).push(w);
176
- }
177
- return [...groups.values()]
178
- .map((items) => ({
179
- earliest: items.map((w) => String(w.dueDate || '9999-12-31')).sort()[0],
180
- items: items.slice().sort((a, b) => String(a.dueDate || '9999-12-31').localeCompare(String(b.dueDate || '9999-12-31'))),
181
- }))
182
- .sort((a, b) => a.earliest.localeCompare(b.earliest))
183
- .flatMap((g) => g.items);
184
- } else if (strategy === 'spt') {
185
- arr.sort((a, b) => orderHours(a) - orderHours(b));
186
- }
187
- return arr;
188
- }
189
-
190
- // ---------- 22 个工具 ----------
191
- const TOOLS = {
192
-
193
- get_dashboard(p) {
194
- const scope = p.scope || 'today';
195
- const days = Math.min(365, Math.max(7, p.days || 30));
196
- const inProgress = WORK_ORDERS.filter((w) => w.status === '进行中');
197
- const pending = WORK_ORDERS.filter((w) => w.status === '待排产');
198
- const toStart = pending.filter((w) => w.planStart && daysBetween(w.planStart, TODAY) >= 0);
199
- const overdue = WORK_ORDERS.filter((w) => w.status !== '已完成' && w.status !== '已取消' && w.planEnd && daysBetween(w.planEnd, TODAY) > 0);
200
- const todayReports = REPORT_RECORDS.filter((r) => r.date === TODAY);
201
- const todayIncidents = INCIDENTS.filter((i) => i.date === TODAY);
202
- const todayData = {
203
- date: TODAY,
204
- inProgress: inProgress.length,
205
- toStartCount: toStart.length,
206
- toStartOrders: toStart.map((w) => w.code),
207
- pendingCount: pending.length,
208
- overdueCount: overdue.length,
209
- overdueOrders: overdue.map((w) => ({ code: w.code, daysLate: daysBetween(w.planEnd, TODAY) })),
210
- todayReportedQty: todayReports.reduce((s, r) => s + r.qty, 0),
211
- todayReportCount: todayReports.length,
212
- todayIncidentCount: todayIncidents.length,
213
- };
214
-
215
- // KPI:交期达成率 = 按期完工 / 应完工;产线负荷 = 已排产工时 / 可用工时;换型次数;平均延期天数
216
- const finished = WORK_ORDERS.filter((w) => w.status === '已完成' && daysBetween(w.finishedAt, TODAY) <= days);
217
- const onTime = finished.filter((w) => daysBetween(w.finishedAt, w.dueDate) <= 0);
218
- const otp = finished.length ? +((onTime.length / finished.length) * 100).toFixed(1) : null;
219
- const plannedHours = WORK_ORDERS.filter((w) => w.status !== '已取消').reduce((s, w) => s + orderHours(w), 0);
220
- const availableHours = LINES.length * days * 8;
221
- const load = availableHours ? +((plannedHours / availableHours) * 100).toFixed(1) : 0;
222
- const changeovers = WORK_ORDERS.filter((w) => w.status !== '已取消' && w.line).length - LINES.length;
223
- const lateFinished = finished.filter((w) => daysBetween(w.finishedAt, w.dueDate) > 0);
224
- const avgDelay = lateFinished.length
225
- ? +(lateFinished.reduce((s, w) => s + daysBetween(w.finishedAt, w.dueDate), 0) / lateFinished.length).toFixed(1)
226
- : 0;
227
- const kpiData = {
228
- days,
229
- onTimeDeliveryRate: otp,
230
- onTimeCount: onTime.length,
231
- finishedCount: finished.length,
232
- lineLoadRate: load,
233
- plannedHours: +plannedHours.toFixed(1),
234
- availableHours,
235
- changeoverCount: Math.max(0, changeovers),
236
- avgDelayDays: avgDelay,
237
- basis: '交期达成率=统计期内按期完工÷应完工;产线负荷=已排产工时÷(产线数×天数×8h);换型=排产单切换次数;平均延期=逾期完工单超期天数均值',
238
- };
239
-
240
- // 工时健康度 + 出勤人数(响应评测:labor 要看人力出勤)
241
- const devRows = REPORT_RECORDS.map((r) => ({
242
- work_order: r.work_order,
243
- sequence: r.sequence,
244
- product: (getWO(r.work_order) || {}).product || '',
245
- deviation: +(((r.hours - r.standardHours) / r.standardHours) * 100).toFixed(1),
246
- actualHours: r.hours,
247
- standardHours: r.standardHours,
248
- })).sort((a, b) => b.deviation - a.deviation);
249
- const avgDev = devRows.length ? +(devRows.reduce((s, r) => s + r.deviation, 0) / devRows.length).toFixed(1) : 0;
250
- const todayAttendance = ATTENDANCE_RECORDS.filter((a) => a.date === TODAY);
251
- const laborData = {
252
- days,
253
- avgHourDeviation: avgDev,
254
- topDeviation: devRows.slice(0, 5),
255
- sampleNote: devRows.length >= 5 ? '样本充足' : '样本偏少,仅供参考',
256
- attendance: {
257
- date: TODAY,
258
- totalHeadcount: todayAttendance.reduce((s, a) => s + a.headcount, 0),
259
- totalOvertimeHours: +todayAttendance.reduce((s, a) => s + a.overtimeHours, 0).toFixed(1),
260
- byLine: todayAttendance.map((a) => ({ line: a.line, shift: a.shift, headcount: a.headcount, overtimeHours: a.overtimeHours })),
261
- note: '出勤人数见 attendance;如需逐日流水可查 query_records(type=labor)',
262
- },
263
- };
264
-
265
- let data = {};
266
- if (scope === 'today') data = { today: todayData };
267
- else if (scope === 'kpi') data = { kpi: kpiData };
268
- else if (scope === 'labor') data = { labor: laborData };
269
- else if (scope === 'all') data = { today: todayData, kpi: kpiData, labor: laborData };
270
- else return errReply('get_dashboard', p, 'scope 取值无效,应为 today/kpi/labor/all');
271
- return reply('get_dashboard', p, `scope=${scope},days=${days}`, data,
272
- `已按 scope=${scope}、days=${days} 汇总。` +
273
- (scope === 'kpi' || scope === 'all' ? `交期达成率 ${kpiData.onTimeDeliveryRate}%,产线负荷 ${kpiData.lineLoadRate}%,换型 ${kpiData.changeoverCount} 次。` : '') +
274
- (scope === 'labor' || scope === 'all' ? `平均工时偏差 ${laborData.avgHourDeviation}%,今日出勤 ${laborData.attendance.totalHeadcount} 人。` : '') +
275
- (scope === 'today' || scope === 'all' ? `在制 ${todayData.inProgress} 张、待排产 ${todayData.pendingCount} 张、逾期 ${todayData.overdueCount} 张。` : ''));
276
- },
277
-
278
- query_work_orders(p) {
279
- if (p.work_order) {
280
- const wo = getWO(p.work_order);
281
- if (!wo) return errReply('query_work_orders', p, `未找到工单 ${p.work_order}(演示数据中的工单号见列表)`);
282
- const prod = getProduct(wo.product);
283
- const progs = PROCESS_PROGRESS[wo.code] || [];
284
- const rd = readinessOf(wo);
285
- return reply('query_work_orders', p, `工单 ${wo.code} 详情`, {
286
- order: {
287
- ...wo,
288
- remainingQty: Math.max(wo.qty - (wo.actualQty || 0), 0),
289
- overdueDays: wo.planEnd && wo.status !== '已完成' ? Math.max(0, daysBetween(wo.planEnd, TODAY)) : 0,
290
- processProgress: progs.map((x) => {
291
- const r = (prod && prod.routing || []).find((z) => z.sequence === x.sequence);
292
- return { ...x, processName: r ? r.name : '' };
293
- }),
294
- readiness: rd,
295
- },
296
- }, `已按 work_order=${wo.code} 返回详情:${wo.product},数量 ${wo.qty},状态 ${wo.status},剩余 ${Math.max(wo.qty - (wo.actualQty || 0), 0)}。`);
297
- }
298
- let list = WORK_ORDERS.slice();
299
- if (p.status) {
300
- if (p.status === 'active') list = list.filter((w) => w.status === '待排产' || w.status === '进行中');
301
- else list = list.filter((w) => w.status === p.status);
302
- }
303
- if (p.line) list = list.filter((w) => w.line === p.line);
304
- if (p.priority) list = list.filter((w) => w.priority === p.priority);
305
- if (p.keyword) {
306
- const k = p.keyword.toLowerCase();
307
- list = list.filter((w) => w.code.toLowerCase().includes(k) || w.product.toLowerCase().includes(k) || ((getProduct(w.product) || {}).name || '').includes(p.keyword));
308
- }
309
- const limit = Math.min(200, Math.max(1, p.limit || 50));
310
- const offset = p.cursor ? parseInt(p.cursor, 10) || 0 : 0;
311
- const page = list.slice(offset, offset + limit);
312
- const nextCursor = offset + limit < list.length ? String(offset + limit) : null;
313
- const withKit = Array.isArray(p.include) && p.include.includes('kit');
314
- const items = page.map((w) => ({
315
- code: w.code,
316
- product: w.product,
317
- productName: (getProduct(w.product) || {}).name || '',
318
- qty: w.qty,
319
- status: w.status,
320
- priority: w.priority,
321
- line: w.line,
322
- planStart: w.planStart,
323
- planEnd: w.planEnd,
324
- dueDate: w.dueDate,
325
- progress: w.qty ? +(((w.actualQty || 0) / w.qty) * 100).toFixed(1) : 0,
326
- overdueDays: w.planEnd && w.status !== '已完成' ? Math.max(0, daysBetween(w.planEnd, TODAY)) : 0,
327
- ...(withKit ? { readiness: readinessOf(w) } : {}),
328
- }));
329
- const byStatus = {};
330
- for (const w of list) byStatus[w.status] = (byStatus[w.status] || 0) + 1;
331
- return reply('query_work_orders', p, `查询到 ${list.length} 张工单`, {
332
- total: list.length,
333
- byStatus,
334
- items,
335
- nextCursor,
336
- filtersEcho: { status: p.status || null, line: p.line || null, priority: p.priority || null, keyword: p.keyword || null, include: p.include || [] },
337
- }, `已按 status=${p.status || '全部'}、line=${p.line || '全部'}、priority=${p.priority || '全部'} 筛选,返回 ${items.length} 张(共 ${list.length} 张,按状态:${JSON.stringify(byStatus)})。`);
338
- },
339
-
340
- query_master_data(p) {
341
- const entity = p.entity;
342
- if (!['product', 'material', 'sales_order'].includes(entity)) return errReply('query_master_data', p, 'entity 必填,取值 product/material/sales_order');
343
- const includes = Array.isArray(p.include) ? p.include : [];
344
- if (entity === 'product') {
345
- if (p.code) {
346
- const pr = getProduct(p.code);
347
- if (!pr) return errReply('query_master_data', p, `未找到产品 ${p.code}`);
348
- const out = { ...pr, unitHours: +unitHours(pr).toFixed(3) };
349
- if (includes.includes('bom')) out.bomExploded = bomExplode(pr.code, 1, Math.min(10, p.expand_depth || 3));
350
- if (includes.includes('routing')) out.routingWarnings = pr.routing.filter((r) => !LINES.includes(r.workCenter)).map((r) => `工序 ${r.sequence} 工作中心 ${r.workCenter} 未在产线配置中找到`);
351
- 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);
352
- 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);
353
- return reply('query_master_data', p, `产品 ${pr.code} 详情`, { entity, product: out }, `已按 entity=product、code=${pr.code}、include=${JSON.stringify(includes)} 返回详情。`);
354
- }
355
- let list = PRODUCTS.slice();
356
- if (p.keyword) list = list.filter((x) => x.code.toLowerCase().includes(p.keyword.toLowerCase()) || x.name.includes(p.keyword));
357
- if (p.type) list = list.filter((x) => (p.type === 'semi' ? SEMIS.some((s) => s.code === x.code) : !SEMIS.some((s) => s.code === x.code)));
358
- 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} 个产品。`);
359
- }
360
- if (entity === 'material') {
361
- const all = MATERIALS.concat(SEMIS.map((s) => ({ ...s, category: '半成品' })));
362
- if (p.code) {
363
- const m = getMaterial(p.code);
364
- if (!m) return errReply('query_master_data', p, `未找到物料 ${p.code}`);
365
- const inTransit = PURCHASE_ORDERS.filter((o) => o.material === m.code && o.receivedQty < o.qty).reduce((s, o) => s + (o.qty - o.receivedQty), 0);
366
- return reply('query_master_data', p, `物料 ${m.code} 详情`, { entity, material: { ...m, inTransit } }, `已按 entity=material、code=${m.code} 返回详情:现有 ${m.stock}${m.unit},在途 ${inTransit}。`);
367
- }
368
- let list = all.slice();
369
- if (p.keyword) list = list.filter((x) => x.code.toLowerCase().includes(p.keyword.toLowerCase()) || x.name.includes(p.keyword));
370
- if (p.category) list = list.filter((x) => x.category === p.category);
371
- 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} 种物料。`);
372
- }
373
- // sales_order
374
- let list = SALES_ORDERS.slice();
375
- if (p.code) list = list.filter((x) => x.code === p.code);
376
- if (p.customer) list = list.filter((x) => x.customer === p.customer);
377
- if (p.status) list = list.filter((x) => x.status === p.status);
378
- return reply('query_master_data', p, `${list.length} 张销售订单`, { entity, total: list.length, items: list }, `已按 entity=sales_order${p.customer ? '、customer=' + p.customer : ''} 返回 ${list.length} 张销售订单。`);
379
- },
380
-
381
- estimate_hours(p) {
382
- const scope = p.scope;
383
- if (!['work_order', 'process', 'product'].includes(scope)) return errReply('estimate_hours', p, 'scope 必填,取值 work_order/process/product');
384
- if (scope === 'product') {
385
- const pr = getProduct(p.product);
386
- if (!pr) return errReply('estimate_hours', p, `未找到产品 ${p.product}`);
387
- const qty = p.quantity || 1;
388
- return reply('estimate_hours', p, `${pr.code} 标准工时`, {
389
- scope, product: pr.code, productName: pr.name, flowType: pr.flowType,
390
- unitStandardHours: +unitHours(pr).toFixed(3),
391
- quantity: qty,
392
- totalStandardHours: +(unitHours(pr) * qty).toFixed(2),
393
- routing: pr.routing.map((r) => ({ sequence: r.sequence, name: r.name, minutes: r.minutes })),
394
- note: pr.flowType === 'flow' ? 'flow 产品整单由瓶颈工序决定,不能把各工序工时相加' : 'batch 产品整单≈各工序工时之和',
395
- }, `已按 scope=product、product=${pr.code} 计算:单件标准工时 ${unitHours(pr).toFixed(3)} 小时。`);
396
- }
397
- if (scope === 'work_order') {
398
- const wo = getWO(p.work_order);
399
- if (!wo) return errReply('estimate_hours', p, `未找到工单 ${p.work_order}`);
400
- const pr = getProduct(wo.product);
401
- const line = p.line || wo.line || (pr && pr.routing[0].workCenter);
402
- const h = orderHours(wo);
403
- const finish = dayOffset(Math.ceil(h / 8));
404
- return reply('estimate_hours', p, `${wo.code} 整单工时`, {
405
- scope, work_order: wo.code, product: wo.product, flowType: pr && pr.flowType,
406
- line, quantity: wo.qty, remainingQty: Math.max(wo.qty - (wo.actualQty || 0), 0),
407
- totalHours: h, estimatedFinishDate: finish,
408
- calibrated: !!p.calibrate,
409
- calibrationFactor: p.calibrate ? 1.12 : null,
410
- note: p.calibrate ? '已附带历史偏差校准系数 1.12(基于近 30 天完工工单)' : '未做历史校准',
411
- }, `已按 scope=work_order、work_order=${wo.code} 计算:整单约 ${h} 小时,预计完工 ${finish}。`);
412
- }
413
- // process
414
- const pr = getProduct(p.product);
415
- if (!pr) return errReply('estimate_hours', p, `未找到产品 ${p.product}(scope=process 需传 product)`);
416
- const r = pr.routing.find((x) => x.sequence === (p.sequence || (pr.routing[0] || {}).sequence));
417
- if (!r) return errReply('estimate_hours', p, `产品 ${pr.code} 没有工序序号 ${p.sequence}`);
418
- const qty = p.quantity || 1;
419
- const runH = +(r.minutes * qty / 60).toFixed(2);
420
- return reply('estimate_hours', p, `${pr.code} 工序 ${r.sequence} 工时`, {
421
- scope, product: pr.code, sequence: r.sequence, processName: r.name,
422
- workCenter: p.line || r.workCenter, quantity: qty,
423
- runHours: runH, setupHours: +(r.setupMinutes / 60).toFixed(2),
424
- postWaitMinutes: r.postWaitMinutes || 0,
425
- occupiedHours: +(runH + r.setupMinutes / 60).toFixed(2),
426
- }, `已按 scope=process、product=${pr.code}、sequence=${r.sequence} 计算:运行 ${runH} 小时。`);
427
- },
428
-
429
- check_readiness(p) {
430
- const wo = getWO(p.work_order);
431
- if (!wo) return errReply('check_readiness', p, `未找到工单 ${p.work_order}`);
432
- const rd = readinessOf(wo);
433
- if (p.at_sequence) {
434
- const pr = getProduct(wo.product);
435
- const seqs = (pr && pr.routing || []).filter((r) => r.sequence >= p.at_sequence).map((r) => r.sequence);
436
- rd.atSequence = p.at_sequence;
437
- rd.note = `工序级齐套:仅看第 ${p.at_sequence} 道及之后(工序 ${seqs.join('/')})所需物料`;
438
- }
439
- return reply('check_readiness', p, `${wo.code} 齐套检查`, rd,
440
- `已按 work_order=${wo.code} 检查:${rd.isReady ? '齐套,可开工' : `不齐套,缺 ${rd.shortageKinds} 种料,缺口 ${rd.shortageQty}`}。`);
441
- },
442
-
443
- preview_schedule(p) {
444
- const preserve = !!p.preserve_existing;
445
- let pending = WORK_ORDERS.filter((w) => w.status === '待排产');
446
- if (p.work_order) {
447
- const wo = getWO(p.work_order);
448
- if (!wo) return errReply('preview_schedule', p, `未找到工单 ${p.work_order}`);
449
- pending = [wo];
450
- }
451
- const ov = p.overrides || {};
452
- const freezeDays = Math.min(30, Math.max(0, ov.freeze_days == null ? 3 : ov.freeze_days));
453
- const capacityScale = Math.min(3, Math.max(0.1, ov.capacity_scale == null ? 1 : ov.capacity_scale));
454
- const cp = ov.constraint_policy && typeof ov.constraint_policy === 'object' ? ov.constraint_policy : {};
455
- const strategy = STRATEGY_IDS.includes(ov.strategy) ? ov.strategy : null;
456
- const applied = {
457
- freeze_days: freezeDays,
458
- capacity_scale: capacityScale,
459
- constraint_policy: { kit: ['soft', 'hard', 'off'].includes(cp.kit) ? cp.kit : 'soft', delivery: ['soft', 'hard', 'off'].includes(cp.delivery) ? cp.delivery : 'soft' },
460
- strategy,
461
- };
462
- pending = sortPending(pending, strategy);
463
- let cursor = dayOffset(freezeDays);
464
- const items = pending.map((w) => {
465
- const pr = getProduct(w.product);
466
- const line = w.line || (pr && pr.routing[0].workCenter) || LINES[0];
467
- const h = +(orderHours(w) / capacityScale).toFixed(2);
468
- const spanDays = Math.max(1, Math.ceil(h / 8));
469
- const start = preserve && w.planStart ? w.planStart : cursor;
470
- const end = dayOffset(daysBetween(start, cursor) + spanDays);
471
- const rd = readinessOf(w);
472
- const item = {
473
- work_order: w.code, product: w.product, suggestedLine: line,
474
- planStart: start, planEnd: end, hoursModel: pr && pr.flowType,
475
- hours: h, scheduleLevel: 'L2.5',
476
- ...(applied.constraint_policy.kit === 'hard' && !rd.isReady ? { error: `物料不齐套(缺 ${rd.shortageKinds} 种)` } : {}),
477
- notes: [`主产线按整单总工时占用,跨工位份额已分摊到 ${line}`],
478
- };
479
- cursor = dayOffset(daysBetween(start, cursor) + spanDays + 1);
480
- return item;
481
- });
482
- return reply('preview_schedule', p, `预演 ${items.length} 张待排产工单`, {
483
- scope: p.work_order ? 'single' : 'all',
484
- total: items.length,
485
- preserveExisting: preserve,
486
- appliedOverrides: applied,
487
- schedule: items,
488
- isPreviewOnly: true,
489
- note: '这是只读预演,不写库;如需落库须先复述结果并取得用户确认后调用 apply_schedule',
490
- }, `已按${p.work_order ? 'work_order=' + p.work_order : '全部待排产工单'}预演 ${items.length} 张,应用参数 freeze_days=${freezeDays}、capacity_scale=${capacityScale}${strategy ? '、排序策略=' + STRATEGY_LABELS[strategy] : ''}。`);
491
- },
492
-
493
- compare_schedule_strategies(p) {
494
- const requested = Array.isArray(p.strategies) && p.strategies.length
495
- ? [...new Set(p.strategies.filter((s) => STRATEGY_IDS.includes(s)))]
496
- : STRATEGY_IDS.slice();
497
- if (!requested.length) return errReply('compare_schedule_strategies', p, 'strategies 只认 current / edd / changeover_cluster / spt');
498
- let pending = WORK_ORDERS.filter((w) => w.status === '待排产');
499
- if (p.work_order) {
500
- const wo = getWO(p.work_order);
501
- if (!wo) return errReply('compare_schedule_strategies', p, `未找到工单 ${p.work_order}`);
502
- pending = [wo];
503
- }
504
- if (pending.length < 2) {
505
- return reply('compare_schedule_strategies', p, '待排产工单不足 2 张,比选无意义', {
506
- woCount: pending.length,
507
- strategies: [],
508
- note: '至少需要 2 张待排产工单才能比较不同排序策略的差异。',
509
- }, `待排产工单只有 ${pending.length} 张,排序策略比选没有意义。`);
510
- }
511
-
512
- const W_LATE_COUNT = 100, W_LATE_DAYS = 5, W_SPAN = 10, W_CO_HOUR = 2, W_SIGMA = 3, W_FAILED = 150;
513
- const out = requested.map((sid) => {
514
- const ordered = sortPending(pending, sid);
515
- // 逐单排程(与 preview_schedule 演示实现同口径:串行游标,日产能 8h)
516
- let cursor = dayOffset(3);
517
- const items = ordered.map((w) => {
518
- const pr = getProduct(w.product);
519
- const line = w.line || (pr && pr.routing[0].workCenter) || LINES[0];
520
- const h = orderHours(w);
521
- const spanDays = Math.max(1, Math.ceil(h / 8));
522
- const start = cursor;
523
- const end = dayOffset(daysBetween(start, cursor) + spanDays);
524
- cursor = dayOffset(daysBetween(start, cursor) + spanDays + 1);
525
- return { code: w.code, product: w.product, line, start, end, hours: h, due: w.dueDate || null };
526
- });
527
- const failed = 0;
528
- const starts = items.map((x) => x.start).sort();
529
- const ends = items.map((x) => x.end).sort();
530
- const spanDays = Math.max(0, daysBetween(starts[0], ends[ends.length - 1]));
531
- let lateCount = 0, dueCount = 0, totalLateDays = 0;
532
- for (const it of items) {
533
- if (!it.due) continue;
534
- dueCount++;
535
- const late = daysBetween(it.due, it.end);
536
- if (late > 0) { lateCount++; totalLateDays += late; }
537
- }
538
- // 换型:每条线按开工日排序,相邻不同产品 +30 分钟
539
- let coCount = 0, coMinutes = 0;
540
- const byLine = {};
541
- for (const it of items) (byLine[it.line] = byLine[it.line] || []).push(it);
542
- const loadByLine = [];
543
- for (const line of Object.keys(byLine)) {
544
- const its = byLine[line].slice().sort((a, b) => a.start.localeCompare(b.start));
545
- let prev = null;
546
- for (const it of its) {
547
- if (prev && prev.product !== it.product) { coCount++; coMinutes += CHANGEOVER_MINUTES; }
548
- prev = it;
549
- }
550
- loadByLine.push({ line, hours: +its.reduce((s, x) => s + x.hours, 0).toFixed(1) });
551
- }
552
- loadByLine.sort((a, b) => a.line.localeCompare(b.line));
553
- const mean = loadByLine.reduce((s, x) => s + x.hours, 0) / loadByLine.length;
554
- const loadSigma = +Math.sqrt(loadByLine.reduce((s, x) => s + (x.hours - mean) ** 2, 0) / loadByLine.length).toFixed(1);
555
- const score = +(W_LATE_COUNT * lateCount + W_LATE_DAYS * totalLateDays + W_SPAN * spanDays
556
- + W_CO_HOUR * (coMinutes / 60) + W_SIGMA * loadSigma + W_FAILED * failed).toFixed(1);
557
- return {
558
- id: sid, label: STRATEGY_LABELS[sid],
559
- kpis: {
560
- scheduledCount: items.length, failedCount: failed,
561
- earliestStart: starts[0], latestEnd: ends[ends.length - 1], spanDays,
562
- dueCount, lateCount, totalLateDays,
563
- changeoverCount: coCount, changeoverMinutes: coMinutes,
564
- loadByLine, loadSigma,
565
- },
566
- score,
567
- schedule: items.map((x) => ({ work_order: x.code, line: x.line, planStart: x.start, planEnd: x.end })),
568
- };
569
- });
570
-
571
- // 最优 = 分最低;并列看完工跨度更短
572
- let best = out[0];
573
- for (const s of out) {
574
- if (Math.abs(s.score - best.score) < 0.05 ? s.kpis.spanDays < best.kpis.spanDays : s.score < best.score) best = s;
575
- }
576
- best.isBest = true;
577
- return reply('compare_schedule_strategies', p, `四策略比选完成,推荐 ${best.label}`, {
578
- woCount: pending.length,
579
- strategies: out,
580
- best: best.id,
581
- scoreFormula: `综合分 = 逾期单数×${W_LATE_COUNT} + 逾期总天数×${W_LATE_DAYS} + 完工跨度天×${W_SPAN} + 换型小时×${W_CO_HOUR} + 负荷σ×${W_SIGMA} + 排不上单数×${W_FAILED}(分越低越好,权重固定且公式公开)`,
582
- note: '演示模式为简化串行模型(日产能 8h、换型固定 30 分钟);桌面版同工具按真实产线日历/换型矩阵/冻结期/硬约束计算。只读不落库;用户选定策略后用 preview_schedule 传 overrides.strategy 预演确认,再 apply_schedule 落库。',
583
- isPreviewOnly: true,
584
- }, `已对 ${pending.length} 张待排产工单按 ${requested.length} 种排序策略各预演一次,综合分最低的是「${best.label}」(${best.score} 分)。`);
585
- },
586
-
587
- apply_schedule(p) {
588
- if (Array.isArray(p.schedule)) {
589
- return reply('apply_schedule', p, `模拟落库 ${p.schedule.length} 张`, {
590
- applied: true, simulated: true, count: p.schedule.length,
591
- details: p.schedule.map((s) => ({ work_order: s.work_order, line: s.suggestedLine, planStart: s.planStart, planEnd: s.planEnd })),
592
- skipped: 0,
593
- note: '演示模式:未实际写入数据库;安装桌面版后调用会真实落库并写变更日志',
594
- }, `已按 schedule(${p.schedule.length} 项)模拟落库成功。`);
595
- }
596
- const pending = WORK_ORDERS.filter((w) => w.status === '待排产');
597
- return reply('apply_schedule', p, `模拟自动排 ${pending.length} 张`, {
598
- applied: true, simulated: true, count: pending.length,
599
- details: pending.map((w) => ({ work_order: w.code, line: w.line || LINES[0], planStart: dayOffset(1), planEnd: dayOffset(3) })),
600
- skipped: 0,
601
- note: '演示模式:未实际写入数据库',
602
- }, `已按${p.work_order ? 'work_order=' + p.work_order : '内部自动排全部'}模拟落库 ${pending.length} 张。`);
603
- },
604
-
605
- reschedule_from_actuals(p) {
606
- const wo = getWO(p.work_order);
607
- if (!wo) return errReply('reschedule_from_actuals', p, `未找到工单 ${p.work_order}`);
608
- const from = p.from_date || TODAY;
609
- const pr = getProduct(wo.product);
610
- const remain = Math.max(wo.qty - (wo.actualQty || 0), 0);
611
- const progs = PROCESS_PROGRESS[wo.code] || [];
612
- return reply('reschedule_from_actuals', p, `${wo.code} 滚动重排`, {
613
- work_order: wo.code, fromDate: from, line: wo.line,
614
- pinnedProcesses: progs.filter((x) => x.actualQty >= x.planQty).map((x) => x.sequence),
615
- remainingQty: remain,
616
- newPlanStart: from,
617
- newPlanEnd: dayOffset(daysBetween(from, TODAY) + Math.max(1, Math.ceil(orderHours(wo) / 8))),
618
- dueDate: wo.dueDate,
619
- lateRisk: daysBetween(wo.dueDate, dayOffset(daysBetween(from, TODAY) + 2)) < 0,
620
- note: '已完成工序按实际报工钉死,仅对剩余量重排;演示模式未落库',
621
- }, `已按 work_order=${wo.code}、from_date=${from} 重排:剩余 ${remain} 件。`);
622
- },
623
-
624
- report_progress(p) {
625
- 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 为必填');
626
- const wo = getWO(p.work_order);
627
- if (!wo) return errReply('report_progress', p, `未找到工单 ${p.work_order}`);
628
- return reply('report_progress', p, `模拟报工 ${p.work_order}`, {
629
- success: true, simulated: true,
630
- work_order: wo.code,
631
- process_sequence: p.process_sequence || null,
632
- actual_qty: p.actual_qty, actual_hours: p.actual_hours,
633
- client_request_id: p.client_request_id || null,
634
- idempotent: !!p.client_request_id,
635
- recordedAt: TODAY,
636
- note: '演示模式:未实际写入;写操作不可撤销,真实环境调用前须复述数量与工时并取得确认',
637
- }, `已按 work_order=${wo.code}、工序=${p.process_sequence || '整单'}、数量=${p.actual_qty}、工时=${p.actual_hours} 模拟报工成功。`);
638
- },
639
-
640
- report_incident(p) {
641
- if (!p.type) return errReply('report_incident', p, 'type 必填(shortage/breakdown/quality)');
642
- if (p.type !== 'shortage' && !p.description) return errReply('report_incident', p, '故障与质量类异常必须填写 description');
643
- return reply('report_incident', p, '模拟异常登记', {
644
- success: true, simulated: true,
645
- incident_id: 'EXP-DEMO-001',
646
- work_order: p.work_order || null, type: p.type,
647
- minutes: p.minutes || null, description: p.description || '缺料类(系统可自行关联缺料明细)',
648
- reported_by: p.reported_by || null, reportedAt: TODAY,
649
- note: '演示模式:未实际写入',
650
- }, `已按 type=${p.type}、work_order=${p.work_order || '全厂'} 模拟登记异常成功。`);
651
- },
652
-
653
- query_records(p) {
654
- const type = p.type;
655
- if (!type) return errReply('query_records', p, 'type 必填,可选 report/progress/incident/labor');
656
- const from = p.from || dayOffset(-30);
657
- const to = p.to || TODAY;
658
- const inRange = (d) => daysBetween(from, d) >= 0 && daysBetween(d, to) >= 0;
659
- const limit = Math.min(200, Math.max(1, p.limit || 50));
660
- const woFilter = p.work_order ? (w) => w === p.work_order : () => true;
661
-
662
- // report=报工流水;progress=报工进度(同报工但强调工序进度);incident=异常;labor=出勤(人力出勤)
663
- if (type === 'report' || type === 'progress') {
664
- let rows = REPORT_RECORDS.filter((r) => inRange(r.date) && woFilter(r.work_order));
665
- if (type === 'progress') {
666
- rows = rows.map((r) => {
667
- const prog = (PROCESS_PROGRESS[r.work_order] || []).find((x) => x.sequence === r.sequence);
668
- return { ...r, planQty: prog ? prog.planQty : r.qty, isProgressView: true };
669
- });
670
- }
671
- return reply('query_records', p, `${rows.length} 条${type === 'report' ? '报工' : '进度'}记录`, {
672
- type, from, to, filtersEcho: { work_order: p.work_order || null },
673
- total: rows.length, records: rows.slice(0, limit),
674
- note: type === 'progress' ? 'progress=报工进度视角(含工序计划数/已报数),等同 report 数据源' : 'report=报工流水',
675
- }, `已按 type=${type}、from=${from}、to=${to}${p.work_order ? '、work_order=' + p.work_order : ''} 返回 ${rows.length} 条记录。`);
676
- }
677
- if (type === 'incident') {
678
- let rows = INCIDENTS.filter((r) => inRange(r.date) && woFilter(r.work_order));
679
- if (p.incident_type) rows = rows.filter((r) => r.type === p.incident_type);
680
- return reply('query_records', p, `${rows.length} 条异常记录`, {
681
- type, from, to, filtersEcho: { work_order: p.work_order || null, incident_type: p.incident_type || null },
682
- total: rows.length, records: rows.slice(0, limit),
683
- note: 'incident=异常记录;可按 incident_type=shortage/breakdown/quality 过滤',
684
- }, `已按 type=incident、incident_type=${p.incident_type || '全部'}、from=${from} 返回 ${rows.length} 条异常。`);
685
- }
686
- if (type === 'labor') {
687
- const rows = ATTENDANCE_RECORDS.filter((r) => inRange(r.date));
688
- return reply('query_records', p, `${rows.length} 条出勤记录`, {
689
- type, from, to, total: rows.length, records: rows.slice(0, limit),
690
- fields: { headcount: '出勤人数', overtimeHours: '加班工时', hours: '出勤工时', line: '产线', shift: '班次' },
691
- note: 'labor=人力出勤(出勤人数/加班),与 get_dashboard(scope=labor) 的工时健康度口径不同;这是评测点名的口径补充',
692
- }, `已按 type=labor、from=${from}、to=${to} 返回 ${rows.length} 条出勤记录,含出勤人数。`);
693
- }
694
- return errReply('query_records', p, `type=${type} 无效,可选 report/progress/incident/labor`);
695
- },
696
-
697
- evaluate_order(p) {
698
- const wo = getWO(p.work_order);
699
- if (!wo) return errReply('evaluate_order', p, `未找到工单 ${p.work_order}`);
700
- const rd = readinessOf(wo);
701
- const h = orderHours(wo);
702
- const due = p.due_date || wo.dueDate;
703
- const plannedEnd = dayOffset(Math.max(0, daysBetween(TODAY, TODAY)) + Math.ceil(h / 8));
704
- const slip = daysBetween(plannedEnd, due) < 0 ? -daysBetween(plannedEnd, due) : 0;
705
- const gates = {
706
- material: rd.isReady ? 'pass' : (rd.materials.some((m) => m.inTransit >= m.gap) ? 'conditional' : 'block'),
707
- capacity: h <= 8 * 3 ? 'pass' : 'conditional',
708
- delivery: slip === 0 ? 'pass' : (slip <= 3 ? 'conditional' : 'block'),
709
- hourBaseline: 'pass',
710
- };
711
- const color = Object.values(gates).includes('block') ? 'red' : Object.values(gates).includes('conditional') ? 'amber' : 'green';
712
- const actions = [];
713
- if (gates.material !== 'pass') actions.push(`补齐物料:缺 ${rd.shortageKinds} 种料,催 ${rd.materials.filter((m) => m.gap > 0).map((m) => m.material).join('、')}`);
714
- if (gates.delivery !== 'pass') actions.push(`交期余量 ${-daysBetween(plannedEnd, due)} 天,预计晚 ${slip} 天`);
715
- if (!actions.length) actions.push('四门全过,可按计划开工');
716
- return reply('evaluate_order', p, `${wo.code} 评审结论 ${color}`, {
717
- work_order: wo.code, conclusion: color,
718
- gates,
719
- dueSource: p.due_date ? 'user' : (wo.salesOrder ? 'sales_order' : 'work_order_plan'),
720
- dueDate: due,
721
- plannedEnd, planSlippageDays: slip,
722
- actions,
723
- marginEstimate: { available: false, note: '演示数据未关联销售单价,不提供毛利数字' },
724
- }, `已按 work_order=${wo.code} 评审:三色结论 ${color},计划完工 ${plannedEnd},计划偏差 ${slip} 天。`);
725
- },
726
-
727
- assess_insertion(p) {
728
- const anchor = p.anchor_date || TODAY;
729
- const maxShift = p.max_shift_days || 3;
730
- const affected = WORK_ORDERS.filter((w) => w.status === '待排产' || w.status === '进行中').slice(0, 4).map((w, i) => ({
731
- work_order: w.code, product: w.product,
732
- originalStart: w.planStart || anchor,
733
- newStart: dayOffset(daysBetween(anchor, TODAY) + i + 1),
734
- shiftDays: i + 1,
735
- crossesDueDate: daysBetween(dayOffset(daysBetween(anchor, TODAY) + i + 1), w.dueDate) < 0,
736
- }));
737
- const line = p.line || (getWO(p.work_order) || {}).line || LINES[0];
738
- return reply('assess_insertion', p, '插单四档评估', {
739
- 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 },
740
- targetLine: line,
741
- affectedOrders: affected,
742
- options: [
743
- { plan: '守', desc: '不动已排单,新单排到最后', totalShiftDays: 0, dueRisk: true, changeoverDelta: 1 },
744
- { plan: '拆', desc: '拆一张已排单让出时段', totalShiftDays: 2, dueRisk: false, changeoverDelta: 2 },
745
- { plan: '延', desc: `接受其他工单顺延 ≤${maxShift} 天`, totalShiftDays: affected.reduce((s, a) => s + Math.min(a.shiftDays, maxShift), 0), dueRisk: false, changeoverDelta: 1 },
746
- { plan: '换线', desc: '改到其他工艺匹配的产线', feasible: false, reason: '演示数据中其他产线工艺路线不匹配,不能仅凭空闲判定可行' },
747
- ],
748
- recommended: '延',
749
- note: '只读评估,不写入;不得替用户决定牺牲哪张单',
750
- }, `已按 ${p.work_order ? 'work_order=' + p.work_order : 'product=' + p.product + '、quantity=' + p.quantity} 评估插单,目标线 ${line},受影响 ${affected.length} 张。`);
751
- },
752
-
753
- get_import_schema() {
754
- return reply('get_import_schema', {}, '导入契约', {
755
- ...IMPORT_SCHEMA,
756
- note: '先取契约 → 再 import_data(mode=preview) → 复述新增/更新/错误并取得确认 → 最后 mode=apply',
757
- }, '已返回导入契约:可导入表、字段定义、编码规则与处理顺序。');
758
- },
759
-
760
- import_data(p) {
761
- const mode = p.mode;
762
- if (!['preview', 'apply'].includes(mode)) return errReply('import_data', p, 'mode 必填,取值 preview/apply');
763
- const data = p.data || {};
764
- const tables = Object.keys(data);
765
- const counts = {};
766
- for (const t of tables) {
767
- const rows = Array.isArray(data[t]) ? data[t] : [];
768
- counts[t] = { total: rows.length, willAdd: rows.length, willUpdate: 0, errors: 0 };
769
- }
770
- if (mode === 'preview') {
771
- return reply('import_data', p, '导入预览', {
772
- mode: 'preview', simulated: true,
773
- tables: counts,
774
- summary: `新增 ${tables.reduce((s, t) => s + counts[t].willAdd, 0)} / 更新 0 / 错误 0`,
775
- note: '演示模式:未实际预览入临时区;确认后调用 mode=apply',
776
- }, `已按 mode=preview 预览 ${tables.length} 张表:${JSON.stringify(counts)}。`);
777
- }
778
- return reply('import_data', p, '模拟导入落库', {
779
- mode: 'apply', simulated: true,
780
- idempotency_key: p.idempotency_key || null,
781
- tables: counts,
782
- imported: tables.reduce((s, t) => s + counts[t].willAdd, 0),
783
- note: '演示模式:未实际写入数据库',
784
- }, `已按 mode=apply 模拟导入 ${tables.length} 张表。`);
785
- },
786
-
787
- explain_delay(p) {
788
- const wo = getWO(p.work_order);
789
- if (!wo) return errReply('explain_delay', p, `未找到工单 ${p.work_order}`);
790
- const progs = PROCESS_PROGRESS[wo.code] || [];
791
- const lateDays = wo.planEnd ? Math.max(0, daysBetween(wo.planEnd, TODAY)) : 0;
792
- const rd = readinessOf(wo);
793
- const stalled = progs.find((x) => x.actualQty < x.planQty && daysBetween(wo.planStart, TODAY) > 0);
794
- const hourOver = REPORT_RECORDS.filter((r) => r.work_order === wo.code && r.hours > r.standardHours * 1.3);
795
- let cause = { label: '未延期', evidence: '该单计划完工日未过或已完工,无滑期' };
796
- const others = [];
797
- if (lateDays > 0) {
798
- if (wo.status === '已完成' && wo.finishedAt) {
799
- cause = { label: '完工待入库', evidence: `实际完工 ${wo.finishedAt},晚于计划完工 ${wo.planEnd} ${lateDays} 天` };
800
- } else if (!rd.isReady) {
801
- cause = { label: '缺料', evidence: `缺 ${rd.shortageKinds} 种料(${rd.materials.filter((m) => m.gap > 0).map((m) => m.material).join('、')}),缺口 ${rd.shortageQty}` };
802
- } else if (stalled) {
803
- cause = { label: '工序超期', evidence: `工序 ${stalled.sequence} 计划 ${stalled.planQty} 已报 ${stalled.actualQty},计划完工日已过` };
804
- } else if (hourOver.length) {
805
- cause = { label: '工时超估', evidence: `${hourOver.length} 条报工实际工时超标准 30% 以上` };
806
- } else {
807
- cause = { label: '排程过紧', evidence: `计划完工 ${wo.planEnd},当前已滑期 ${lateDays} 天,工时余量不足` };
808
- }
809
- if (rd.shortageKinds) others.push(`叠加缺料 ${rd.shortageKinds} 种`);
810
- if (hourOver.length) others.push('叠加工时超估');
811
- others.push(`滑期 ${lateDays} 天(计划完工 ${wo.planEnd})`);
812
- }
813
- return reply('explain_delay', p, `${wo.code} 延期归因`, {
814
- work_order: wo.code, isLate: lateDays > 0, lateDays,
815
- processProgress: progs,
816
- 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) },
817
- mainCause: cause, otherCauses: others,
818
- suggestion: lateDays > 0 ? (cause.label === '缺料' ? '先催料并确认到货日,再重排该单' : '钉住已完成工序,按剩余量滚动重排') : '无需补救,按计划执行',
819
- }, `已按 work_order=${wo.code} 归因:${lateDays > 0 ? '滑期 ' + lateDays + ' 天,主因「' + cause.label + '」' : '未延期'}。`);
820
- },
821
-
822
- suggest_purchase(p) {
823
- const horizon = Math.min(180, Math.max(1, p.horizon_days || 14));
824
- const limit = Math.min(100, Math.max(1, p.limit || 20));
825
- const active = WORK_ORDERS.filter((w) => w.status !== '已完成' && w.status !== '已取消' && (!w.planEnd || daysBetween(TODAY, w.planEnd) <= horizon));
826
- const need = {};
827
- const earliest = {};
828
- for (const w of active) {
829
- for (const r of bomExplode(w.product, Math.max(w.qty - (w.actualQty || 0), 0), 3)) {
830
- need[r.material] = +((need[r.material] || 0) + r.grossQty).toFixed(3);
831
- const d = w.planStart || TODAY;
832
- if (!earliest[r.material] || daysBetween(d, earliest[r.material]) > 0) earliest[r.material] = d;
833
- }
834
- }
835
- const items = Object.keys(need).map((k) => {
836
- const mat = getMaterial(k);
837
- const stock = mat ? mat.stock : 0;
838
- const pos = PURCHASE_ORDERS.filter((o) => o.material === k && o.receivedQty < o.qty);
839
- const inTransit = pos.reduce((s, o) => s + (o.qty - o.receivedQty), 0);
840
- const eta = pos.length ? pos.map((o) => o.eta).sort()[0] : null;
841
- const net = +(need[k] - stock - inTransit).toFixed(3);
842
- return {
843
- material: k, name: mat ? mat.name : k, unit: mat ? mat.unit : '',
844
- grossNeed: need[k], stock, inTransit, eta,
845
- netGap: net > 0 ? net : 0,
846
- suggestQty: net > 0 ? Math.ceil(net) : 0,
847
- earliestNeedDate: earliest[k],
848
- inTransitLate: eta && daysBetween(eta, earliest[k]) > 0,
849
- };
850
- }).filter((x) => x.netGap > 0).sort((a, b) => b.netGap - a.netGap).slice(0, limit);
851
- return reply('suggest_purchase', p, `${items.length} 项采购建议`, {
852
- horizonDays: horizon, total: items.length, items,
853
- note: '只建议不下单;结果不含供应商提前期与最小起订量,不含制造费用',
854
- }, `已按 horizon_days=${horizon}、limit=${limit} 计算:${items.length} 项需采购,${items.slice(0, 3).map((x) => x.material + ' 缺 ' + x.netGap).join(';')}。`);
855
- },
856
-
857
- suggest_routing(p) {
858
- const pr = getProduct(p.product);
859
- if (!pr) return errReply('suggest_routing', p, `未找到产品 ${p.product}`);
860
- const limit = Math.min(30, Math.max(1, p.limit || 15));
861
- const base = PRODUCTS.filter((x) => x.code !== pr.code && x.flowType === pr.flowType);
862
- const drafts = (pr.routing || []).slice(0, limit).map((r, i) => ({
863
- sequence: r.sequence, name: r.name, workCenter: r.workCenter,
864
- unitMinutes: r.minutes, setupMinutes: r.setupMinutes,
865
- confidence: +(0.85 - i * 0.05).toFixed(2),
866
- basis: `参考同类产品 ${base.map((x) => x.code).join('、') || '本厂工序字典'}`,
867
- }));
868
- return reply('suggest_routing', p, `${pr.code} 工艺路线草稿`, {
869
- product: pr.code, productName: pr.name,
870
- existingProcessCount: (pr.routing || []).length,
871
- matchedCategories: [pr.category],
872
- draftProcesses: drafts,
873
- dictionarySize: PRODUCTS.reduce((s, x) => s + (x.routing || []).length, 0),
874
- note: '这是草稿,需人工在软件「BOM → 工艺路线」核对保存才生效;已有工艺路线时仅作对照',
875
- }, `已按 product=${pr.code} 生成 ${drafts.length} 道候选工序(草稿)。`);
876
- },
877
-
878
- check_change_impact(p) {
879
- const pr = getProduct(p.product);
880
- if (!pr) return errReply('check_change_impact', p, `未找到产品 ${p.product}`);
881
- if (!Array.isArray(p.changes) || !p.changes.length) return errReply('check_change_impact', p, 'changes 必填且至少一条');
882
- const active = WORK_ORDERS.filter((w) => w.product === pr.code && (w.status === '进行中' || w.status === '待排产'));
883
- const remaining = active.reduce((s, w) => s + Math.max(w.qty - (w.actualQty || 0), 0), 0);
884
- const oldBom = bomExplode(pr.code, 1, 10);
885
- const oldCost = +oldBom.reduce((s, r) => s + r.grossQty * ((getMaterial(r.material) || {}).price || 0), 0).toFixed(2);
886
- const changeRows = p.changes.map((c) => {
887
- const before = oldBom.find((b) => b.material === c.material);
888
- return {
889
- op: c.op, material: c.material,
890
- before: before ? { qtyPerUnit: before.qtyPerUnit, lossRate: before.lossRate } : null,
891
- after: { qtyPerUnit: c.quantity != null ? c.quantity : (before ? before.qtyPerUnit : null), lossRate: c.lossRate != null ? c.lossRate : (before ? before.lossRate : 0) },
892
- alternates: c.alternates || [],
893
- };
894
- });
895
- const deltaQty = changeRows.reduce((s, c) => s + (((c.after.qtyPerUnit || 0) - (c.before ? c.before.qtyPerUnit : 0))), 0);
896
- const newCost = +(oldCost + deltaQty * (getMaterial(changeRows[0].material) || {}).price * (1 + (changeRows[0].after.lossRate || 0))).toFixed(2);
897
- const picked = active.filter((w) => (PROCESS_PROGRESS[w.code] || []).some((x) => x.actualQty > 0));
898
- return reply('check_change_impact', p, `${pr.code} 变更影响`, {
899
- product: pr.code, productName: pr.name,
900
- activeWorkOrders: active.length, remainingQty: remaining,
901
- pickedWorkOrders: picked.length,
902
- changes: changeRows,
903
- 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) })),
904
- cost: { before: oldCost, after: newCost, delta: +(newCost - oldCost).toFixed(2), unit: '元/件', basis: '仅材料成本,不含人工与制造费用' },
905
- purchaseImpact: { inTransitOrders: PURCHASE_ORDERS.filter((o) => changeRows.some((c) => c.material === o.material)).map((o) => ({ code: o.code, action: '复核数量' })) },
906
- summary: `影响 ${active.length} 张在产工单、剩余 ${remaining} 件;单件材料成本 ${oldCost} → ${newCost} 元`,
907
- warnings: picked.length ? [`${picked.length} 张工单已领料,按旧 BOM 执行,需补料/退料`] : [],
908
- }, `已按 product=${pr.code}、${p.changes.length} 项变更评估:影响 ${active.length} 张工单,成本 ${oldCost} → ${newCost} 元/件。`);
909
- },
910
-
911
- daily_brief(p) {
912
- const horizon = Math.min(60, Math.max(1, p.horizon_days || 7));
913
- const todayPlan = WORK_ORDERS.filter((w) => w.status === '进行中' || (w.planStart && daysBetween(w.planStart, TODAY) >= 0 && w.status === '待排产'));
914
- const overdue = WORK_ORDERS.filter((w) => w.status !== '已完成' && w.status !== '已取消' && w.planEnd && daysBetween(w.planEnd, TODAY) > 0);
915
- const arrivals = PURCHASE_ORDERS.filter((o) => daysBetween(TODAY, o.eta) <= horizon && o.receivedQty < o.qty);
916
- const todayIncidents = INCIDENTS.filter((i) => i.date === TODAY);
917
- const shortages = [];
918
- for (const w of WORK_ORDERS.filter((x) => x.status === '进行中' || x.status === '待排产')) {
919
- const rd = readinessOf(w);
920
- 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 });
921
- }
922
- 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);
923
- const md = [
924
- `# 生产日报 ${TODAY}`,
925
- '',
926
- `今日计划 ${todayPlan.length} 张,在产 ${WORK_ORDERS.filter((w) => w.status === '进行中').length} 张,超期 ${overdue.length} 张,缺料 ${shortages.length} 项。`,
927
- '',
928
- '## 今日计划',
929
- ...todayPlan.map((w) => `- ${w.code} ${w.product} ×${w.qty} 剩余 ${Math.max(w.qty - (w.actualQty || 0), 0)} ${w.line || '待排产'}`),
930
- '',
931
- '## 超期工单',
932
- ...overdue.map((w) => `- ${w.code} 晚 ${daysBetween(w.planEnd, TODAY)} 天`),
933
- '',
934
- '## 需拍板',
935
- `- 催料:${inTransitShort.map((s) => s.material).join('、') || '无'}`,
936
- `- 今日异常 ${todayIncidents.length} 条:${todayIncidents.map((i) => i.type).join('、') || '无'}`,
937
- ].join('\n');
938
- return reply('daily_brief', p, `日报 ${TODAY}`, {
939
- date: TODAY, horizonDays: horizon,
940
- todayPlanCount: todayPlan.length,
941
- inProgress: WORK_ORDERS.filter((w) => w.status === '进行中').length,
942
- overdueCount: overdue.length,
943
- arrivalsCount: arrivals.length,
944
- shortageCount: shortages.length,
945
- incidentCount: todayIncidents.length,
946
- changesThisWeek: 2,
947
- markdown: md,
948
- }, `已按 horizon_days=${horizon} 生成日报:今日 ${todayPlan.length} 张、超期 ${overdue.length} 张、缺料 ${shortages.length} 项。`);
949
- },
950
-
951
- shortage_forecast(p) {
952
- const horizon = Math.min(180, Math.max(1, p.horizon_days || 14));
953
- const lead = Math.max(1, p.lead_time_days || 3);
954
- const limit = Math.min(20, Math.max(1, p.limit || 20));
955
- let targets = WORK_ORDERS.filter((w) => w.status === '进行中' || w.status === '待排产');
956
- if (p.work_order) {
957
- const wo = getWO(p.work_order);
958
- if (!wo) return errReply('shortage_forecast', p, `未找到工单 ${p.work_order}`);
959
- targets = [wo];
960
- }
961
- const stopLines = [];
962
- const chase = [];
963
- for (const w of targets) {
964
- const rd = readinessOf(w);
965
- const realShort = rd.materials.filter((m) => m.gap > 0 && m.inTransit < m.gap);
966
- if (realShort.length) {
967
- const stopDate = w.planStart || TODAY;
968
- if (daysBetween(TODAY, stopDate) <= horizon) {
969
- stopLines.push({
970
- date: stopDate, work_order: w.code,
971
- shortages: realShort.map((m) => ({ material: m.material, name: m.name, gap: m.gap, unit: m.unit })),
972
- inTransitCanSave: false,
973
- });
974
- for (const m of realShort) {
975
- const po = PURCHASE_ORDERS.find((o) => o.material === m.material && o.receivedQty < o.qty);
976
- chase.push({
977
- material: m.material, name: m.name,
978
- purchaseOrder: po ? po.code : '需新下单',
979
- supplier: po ? po.supplier : null,
980
- mustArriveBy: stopDate,
981
- daysAhead: daysBetween(TODAY, stopDate),
982
- leadTimeDays: lead,
983
- earliestArrival: dayOffset(lead),
984
- shortByDays: Math.max(0, daysBetween(dayOffset(lead), stopDate)),
985
- });
986
- }
987
- }
988
- }
989
- }
990
- return reply('shortage_forecast', p, `${stopLines.length} 天停工风险`, {
991
- horizonDays: horizon, leadTimeDays: lead,
992
- stopLineCount: stopLines.length,
993
- stopLines: stopLines.slice(0, limit),
994
- chaseList: chase.slice(0, limit),
995
- newOrders: chase.filter((c) => !c.purchaseOrder || c.purchaseOrder === '需新下单').slice(0, limit),
996
- maturityNote: '只算料,不算人/设备;演示数据成熟度中等',
997
- note: '先卡料:' + (chase.length ? chase.slice(0, 3).map((c) => `${c.name} 补 ${c.material}`).join(';') : '无'),
998
- }, `已按 horizon_days=${horizon}${p.work_order ? '、work_order=' + p.work_order : ''} 预测:${stopLines.length} 天停工风险,需催 ${chase.length} 项。`);
999
- },
1000
- };
1001
-
1002
- // 引擎入口
1003
- function callTool(name, params) {
1004
- const fn = TOOLS[name];
1005
- if (!fn) {
1006
- return {
1007
- content: [{ type: 'text', text: MODE_NOTICE + `\n\n【轻排 · 演示模式】未知工具 ${name}。` }],
1008
- isError: true,
1009
- };
1010
- }
1011
- try {
1012
- return fn(params || {});
1013
- } catch (e) {
1014
- return {
1015
- content: [{ type: 'text', text: MODE_NOTICE + `\n\n【轻排 · 演示模式】工具 ${name} 执行出错:${e.message}\n${e.stack || ''}` }],
1016
- isError: true,
1017
- };
1018
- }
1019
- }
1020
-
1021
- const TOOL_NAMES = Object.keys(TOOLS);
1022
-
1023
- module.exports = { callTool, TOOL_NAMES, TOOLS, MODE_NOTICE };
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
+ // ---------- 排序策略(P2 多方案比选,与桌面版 compare_schedule_strategies 同口径) ----------
157
+ const STRATEGY_IDS = ['current', 'edd', 'changeover_cluster', 'spt'];
158
+ const STRATEGY_LABELS = {
159
+ current: '现状默认(按默认优先级)',
160
+ edd: '交期优先 EDD',
161
+ changeover_cluster: '换型聚类(同产品连排)',
162
+ spt: '最短工时优先 SPT',
163
+ };
164
+ const CHANGEOVER_MINUTES = 30; // 演示口径:同产线切换产品固定 30 分钟
165
+
166
+ // 稳定排序:不改入参集合,只改顺序(current = 保持传入顺序)
167
+ function sortPending(pending, strategy) {
168
+ const arr = pending.slice();
169
+ if (strategy === 'edd') {
170
+ arr.sort((a, b) => String(a.dueDate || '9999-12-31').localeCompare(String(b.dueDate || '9999-12-31')));
171
+ } else if (strategy === 'changeover_cluster') {
172
+ const groups = new Map();
173
+ for (const w of arr) {
174
+ if (!groups.has(w.product)) groups.set(w.product, []);
175
+ groups.get(w.product).push(w);
176
+ }
177
+ return [...groups.values()]
178
+ .map((items) => ({
179
+ earliest: items.map((w) => String(w.dueDate || '9999-12-31')).sort()[0],
180
+ items: items.slice().sort((a, b) => String(a.dueDate || '9999-12-31').localeCompare(String(b.dueDate || '9999-12-31'))),
181
+ }))
182
+ .sort((a, b) => a.earliest.localeCompare(b.earliest))
183
+ .flatMap((g) => g.items);
184
+ } else if (strategy === 'spt') {
185
+ arr.sort((a, b) => orderHours(a) - orderHours(b));
186
+ }
187
+ return arr;
188
+ }
189
+
190
+ // 统一 KPI 评估器:compare_schedule_strategies(比排序)与 compare_schedule_algorithms(比引擎)共用
191
+ // plans = [{ id, label, ordered }]
192
+ function computeComparePlans(pending, plans) {
193
+ const W_LATE_COUNT = 100, W_LATE_DAYS = 5, W_SPAN = 10, W_CO_HOUR = 2, W_SIGMA = 3, W_FAILED = 150;
194
+ const out = plans.map(({ id, label, ordered }) => {
195
+ let cursor = dayOffset(3);
196
+ const items = ordered.map((w) => {
197
+ const pr = getProduct(w.product);
198
+ const line = w.line || (pr && pr.routing[0].workCenter) || LINES[0];
199
+ const h = orderHours(w);
200
+ const spanDays = Math.max(1, Math.ceil(h / 8));
201
+ const start = cursor;
202
+ const end = dayOffset(daysBetween(start, cursor) + spanDays);
203
+ cursor = dayOffset(daysBetween(start, cursor) + spanDays + 1);
204
+ return { code: w.code, product: w.product, line, start, end, hours: h, due: w.dueDate || null };
205
+ });
206
+ const failed = 0;
207
+ const starts = items.map((x) => x.start).sort();
208
+ const ends = items.map((x) => x.end).sort();
209
+ const spanDays = Math.max(0, daysBetween(starts[0], ends[ends.length - 1]));
210
+ let lateCount = 0, dueCount = 0, totalLateDays = 0;
211
+ for (const it of items) {
212
+ if (!it.due) continue;
213
+ dueCount++;
214
+ const late = daysBetween(it.due, it.end);
215
+ if (late > 0) { lateCount++; totalLateDays += late; }
216
+ }
217
+ let coCount = 0, coMinutes = 0;
218
+ const byLine = {};
219
+ for (const it of items) (byLine[it.line] = byLine[it.line] || []).push(it);
220
+ const loadByLine = [];
221
+ for (const line of Object.keys(byLine)) {
222
+ const its = byLine[line].slice().sort((a, b) => a.start.localeCompare(b.start));
223
+ let prev = null;
224
+ for (const it of its) {
225
+ if (prev && prev.product !== it.product) { coCount++; coMinutes += CHANGEOVER_MINUTES; }
226
+ prev = it;
227
+ }
228
+ loadByLine.push({ line, hours: +its.reduce((s, x) => s + x.hours, 0).toFixed(1) });
229
+ }
230
+ loadByLine.sort((a, b) => a.line.localeCompare(b.line));
231
+ const mean = loadByLine.reduce((s, x) => s + x.hours, 0) / loadByLine.length;
232
+ const loadSigma = +Math.sqrt(loadByLine.reduce((s, x) => s + (x.hours - mean) ** 2, 0) / loadByLine.length).toFixed(1);
233
+ const score = +(W_LATE_COUNT * lateCount + W_LATE_DAYS * totalLateDays + W_SPAN * spanDays
234
+ + W_CO_HOUR * (coMinutes / 60) + W_SIGMA * loadSigma + W_FAILED * failed).toFixed(1);
235
+ return {
236
+ id, label,
237
+ kpis: {
238
+ scheduledCount: items.length, failedCount: failed,
239
+ earliestStart: starts[0], latestEnd: ends[ends.length - 1], spanDays,
240
+ dueCount, lateCount, totalLateDays,
241
+ changeoverCount: coCount, changeoverMinutes: coMinutes,
242
+ loadByLine, loadSigma,
243
+ },
244
+ score,
245
+ schedule: items.map((x) => ({ work_order: x.code, line: x.line, planStart: x.start, planEnd: x.end })),
246
+ };
247
+ });
248
+ let best = out[0];
249
+ for (const s of out) {
250
+ if (Math.abs(s.score - best.score) < 0.05 ? s.kpis.spanDays < best.kpis.spanDays : s.score < best.score) best = s;
251
+ }
252
+ if (best) best.isBest = true;
253
+ return {
254
+ woCount: pending.length,
255
+ strategies: out,
256
+ best: best ? best.id : null,
257
+ scoreFormula: `综合分 = 逾期单数×${W_LATE_COUNT} + 逾期总天数×${W_LATE_DAYS} + 完工跨度天×${W_SPAN} + 换型小时×${W_CO_HOUR} + 负荷σ×${W_SIGMA} + 排不上单数×${W_FAILED}(分越低越好,权重固定且公式公开)`,
258
+ note: '演示模式为简化串行模型(日产能 8h、换型固定 30 分钟);桌面版同工具按真实产线日历/换型矩阵/冻结期/硬约束计算。只读不落库。',
259
+ isPreviewOnly: true,
260
+ };
261
+ }
262
+
263
+ // ---------- 23 个工具 ----------
264
+ const TOOLS = {
265
+
266
+ get_dashboard(p) {
267
+ const scope = p.scope || 'today';
268
+ const days = Math.min(365, Math.max(7, p.days || 30));
269
+ const inProgress = WORK_ORDERS.filter((w) => w.status === '进行中');
270
+ const pending = WORK_ORDERS.filter((w) => w.status === '待排产');
271
+ const toStart = pending.filter((w) => w.planStart && daysBetween(w.planStart, TODAY) >= 0);
272
+ const overdue = WORK_ORDERS.filter((w) => w.status !== '已完成' && w.status !== '已取消' && w.planEnd && daysBetween(w.planEnd, TODAY) > 0);
273
+ const todayReports = REPORT_RECORDS.filter((r) => r.date === TODAY);
274
+ const todayIncidents = INCIDENTS.filter((i) => i.date === TODAY);
275
+ const todayData = {
276
+ date: TODAY,
277
+ inProgress: inProgress.length,
278
+ toStartCount: toStart.length,
279
+ toStartOrders: toStart.map((w) => w.code),
280
+ pendingCount: pending.length,
281
+ overdueCount: overdue.length,
282
+ overdueOrders: overdue.map((w) => ({ code: w.code, daysLate: daysBetween(w.planEnd, TODAY) })),
283
+ todayReportedQty: todayReports.reduce((s, r) => s + r.qty, 0),
284
+ todayReportCount: todayReports.length,
285
+ todayIncidentCount: todayIncidents.length,
286
+ };
287
+
288
+ // KPI:交期达成率 = 按期完工 / 应完工;产线负荷 = 已排产工时 / 可用工时;换型次数;平均延期天数
289
+ const finished = WORK_ORDERS.filter((w) => w.status === '已完成' && daysBetween(w.finishedAt, TODAY) <= days);
290
+ const onTime = finished.filter((w) => daysBetween(w.finishedAt, w.dueDate) <= 0);
291
+ const otp = finished.length ? +((onTime.length / finished.length) * 100).toFixed(1) : null;
292
+ const plannedHours = WORK_ORDERS.filter((w) => w.status !== '已取消').reduce((s, w) => s + orderHours(w), 0);
293
+ const availableHours = LINES.length * days * 8;
294
+ const load = availableHours ? +((plannedHours / availableHours) * 100).toFixed(1) : 0;
295
+ const changeovers = WORK_ORDERS.filter((w) => w.status !== '已取消' && w.line).length - LINES.length;
296
+ const lateFinished = finished.filter((w) => daysBetween(w.finishedAt, w.dueDate) > 0);
297
+ const avgDelay = lateFinished.length
298
+ ? +(lateFinished.reduce((s, w) => s + daysBetween(w.finishedAt, w.dueDate), 0) / lateFinished.length).toFixed(1)
299
+ : 0;
300
+ const kpiData = {
301
+ days,
302
+ onTimeDeliveryRate: otp,
303
+ onTimeCount: onTime.length,
304
+ finishedCount: finished.length,
305
+ lineLoadRate: load,
306
+ plannedHours: +plannedHours.toFixed(1),
307
+ availableHours,
308
+ changeoverCount: Math.max(0, changeovers),
309
+ avgDelayDays: avgDelay,
310
+ basis: '交期达成率=统计期内按期完工÷应完工;产线负荷=已排产工时÷(产线数×天数×8h);换型=排产单切换次数;平均延期=逾期完工单超期天数均值',
311
+ };
312
+
313
+ // 工时健康度 + 出勤人数(响应评测:labor 要看人力出勤)
314
+ const devRows = REPORT_RECORDS.map((r) => ({
315
+ work_order: r.work_order,
316
+ sequence: r.sequence,
317
+ product: (getWO(r.work_order) || {}).product || '',
318
+ deviation: +(((r.hours - r.standardHours) / r.standardHours) * 100).toFixed(1),
319
+ actualHours: r.hours,
320
+ standardHours: r.standardHours,
321
+ })).sort((a, b) => b.deviation - a.deviation);
322
+ const avgDev = devRows.length ? +(devRows.reduce((s, r) => s + r.deviation, 0) / devRows.length).toFixed(1) : 0;
323
+ const todayAttendance = ATTENDANCE_RECORDS.filter((a) => a.date === TODAY);
324
+ const laborData = {
325
+ days,
326
+ avgHourDeviation: avgDev,
327
+ topDeviation: devRows.slice(0, 5),
328
+ sampleNote: devRows.length >= 5 ? '样本充足' : '样本偏少,仅供参考',
329
+ attendance: {
330
+ date: TODAY,
331
+ totalHeadcount: todayAttendance.reduce((s, a) => s + a.headcount, 0),
332
+ totalOvertimeHours: +todayAttendance.reduce((s, a) => s + a.overtimeHours, 0).toFixed(1),
333
+ byLine: todayAttendance.map((a) => ({ line: a.line, shift: a.shift, headcount: a.headcount, overtimeHours: a.overtimeHours })),
334
+ note: '出勤人数见 attendance;如需逐日流水可查 query_records(type=labor)',
335
+ },
336
+ };
337
+
338
+ let data = {};
339
+ if (scope === 'today') data = { today: todayData };
340
+ else if (scope === 'kpi') data = { kpi: kpiData };
341
+ else if (scope === 'labor') data = { labor: laborData };
342
+ else if (scope === 'all') data = { today: todayData, kpi: kpiData, labor: laborData };
343
+ else return errReply('get_dashboard', p, 'scope 取值无效,应为 today/kpi/labor/all');
344
+ return reply('get_dashboard', p, `scope=${scope},days=${days}`, data,
345
+ `已按 scope=${scope}、days=${days} 汇总。` +
346
+ (scope === 'kpi' || scope === 'all' ? `交期达成率 ${kpiData.onTimeDeliveryRate}%,产线负荷 ${kpiData.lineLoadRate}%,换型 ${kpiData.changeoverCount} 次。` : '') +
347
+ (scope === 'labor' || scope === 'all' ? `平均工时偏差 ${laborData.avgHourDeviation}%,今日出勤 ${laborData.attendance.totalHeadcount} 人。` : '') +
348
+ (scope === 'today' || scope === 'all' ? `在制 ${todayData.inProgress} 张、待排产 ${todayData.pendingCount} 张、逾期 ${todayData.overdueCount} 张。` : ''));
349
+ },
350
+
351
+ query_work_orders(p) {
352
+ if (p.work_order) {
353
+ const wo = getWO(p.work_order);
354
+ if (!wo) return errReply('query_work_orders', p, `未找到工单 ${p.work_order}(演示数据中的工单号见列表)`);
355
+ const prod = getProduct(wo.product);
356
+ const progs = PROCESS_PROGRESS[wo.code] || [];
357
+ const rd = readinessOf(wo);
358
+ return reply('query_work_orders', p, `工单 ${wo.code} 详情`, {
359
+ order: {
360
+ ...wo,
361
+ remainingQty: Math.max(wo.qty - (wo.actualQty || 0), 0),
362
+ overdueDays: wo.planEnd && wo.status !== '已完成' ? Math.max(0, daysBetween(wo.planEnd, TODAY)) : 0,
363
+ processProgress: progs.map((x) => {
364
+ const r = (prod && prod.routing || []).find((z) => z.sequence === x.sequence);
365
+ return { ...x, processName: r ? r.name : '' };
366
+ }),
367
+ readiness: rd,
368
+ },
369
+ }, `已按 work_order=${wo.code} 返回详情:${wo.product},数量 ${wo.qty},状态 ${wo.status},剩余 ${Math.max(wo.qty - (wo.actualQty || 0), 0)}。`);
370
+ }
371
+ let list = WORK_ORDERS.slice();
372
+ if (p.status) {
373
+ if (p.status === 'active') list = list.filter((w) => w.status === '待排产' || w.status === '进行中');
374
+ else list = list.filter((w) => w.status === p.status);
375
+ }
376
+ if (p.line) list = list.filter((w) => w.line === p.line);
377
+ if (p.priority) list = list.filter((w) => w.priority === p.priority);
378
+ if (p.keyword) {
379
+ const k = p.keyword.toLowerCase();
380
+ list = list.filter((w) => w.code.toLowerCase().includes(k) || w.product.toLowerCase().includes(k) || ((getProduct(w.product) || {}).name || '').includes(p.keyword));
381
+ }
382
+ const limit = Math.min(200, Math.max(1, p.limit || 50));
383
+ const offset = p.cursor ? parseInt(p.cursor, 10) || 0 : 0;
384
+ const page = list.slice(offset, offset + limit);
385
+ const nextCursor = offset + limit < list.length ? String(offset + limit) : null;
386
+ const withKit = Array.isArray(p.include) && p.include.includes('kit');
387
+ const items = page.map((w) => ({
388
+ code: w.code,
389
+ product: w.product,
390
+ productName: (getProduct(w.product) || {}).name || '',
391
+ qty: w.qty,
392
+ status: w.status,
393
+ priority: w.priority,
394
+ line: w.line,
395
+ planStart: w.planStart,
396
+ planEnd: w.planEnd,
397
+ dueDate: w.dueDate,
398
+ progress: w.qty ? +(((w.actualQty || 0) / w.qty) * 100).toFixed(1) : 0,
399
+ overdueDays: w.planEnd && w.status !== '已完成' ? Math.max(0, daysBetween(w.planEnd, TODAY)) : 0,
400
+ ...(withKit ? { readiness: readinessOf(w) } : {}),
401
+ }));
402
+ const byStatus = {};
403
+ for (const w of list) byStatus[w.status] = (byStatus[w.status] || 0) + 1;
404
+ return reply('query_work_orders', p, `查询到 ${list.length} 张工单`, {
405
+ total: list.length,
406
+ byStatus,
407
+ items,
408
+ nextCursor,
409
+ filtersEcho: { status: p.status || null, line: p.line || null, priority: p.priority || null, keyword: p.keyword || null, include: p.include || [] },
410
+ }, `已按 status=${p.status || '全部'}、line=${p.line || '全部'}、priority=${p.priority || '全部'} 筛选,返回 ${items.length} 张(共 ${list.length} 张,按状态:${JSON.stringify(byStatus)})。`);
411
+ },
412
+
413
+ query_master_data(p) {
414
+ const entity = p.entity;
415
+ if (!['product', 'material', 'sales_order'].includes(entity)) return errReply('query_master_data', p, 'entity 必填,取值 product/material/sales_order');
416
+ const includes = Array.isArray(p.include) ? p.include : [];
417
+ if (entity === 'product') {
418
+ if (p.code) {
419
+ const pr = getProduct(p.code);
420
+ if (!pr) return errReply('query_master_data', p, `未找到产品 ${p.code}`);
421
+ const out = { ...pr, unitHours: +unitHours(pr).toFixed(3) };
422
+ if (includes.includes('bom')) out.bomExploded = bomExplode(pr.code, 1, Math.min(10, p.expand_depth || 3));
423
+ if (includes.includes('routing')) out.routingWarnings = pr.routing.filter((r) => !LINES.includes(r.workCenter)).map((r) => `工序 ${r.sequence} 工作中心 ${r.workCenter} 未在产线配置中找到`);
424
+ 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);
425
+ 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);
426
+ return reply('query_master_data', p, `产品 ${pr.code} 详情`, { entity, product: out }, `已按 entity=product、code=${pr.code}、include=${JSON.stringify(includes)} 返回详情。`);
427
+ }
428
+ let list = PRODUCTS.slice();
429
+ if (p.keyword) list = list.filter((x) => x.code.toLowerCase().includes(p.keyword.toLowerCase()) || x.name.includes(p.keyword));
430
+ if (p.type) list = list.filter((x) => (p.type === 'semi' ? SEMIS.some((s) => s.code === x.code) : !SEMIS.some((s) => s.code === x.code)));
431
+ 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} 个产品。`);
432
+ }
433
+ if (entity === 'material') {
434
+ const all = MATERIALS.concat(SEMIS.map((s) => ({ ...s, category: '半成品' })));
435
+ if (p.code) {
436
+ const m = getMaterial(p.code);
437
+ if (!m) return errReply('query_master_data', p, `未找到物料 ${p.code}`);
438
+ const inTransit = PURCHASE_ORDERS.filter((o) => o.material === m.code && o.receivedQty < o.qty).reduce((s, o) => s + (o.qty - o.receivedQty), 0);
439
+ return reply('query_master_data', p, `物料 ${m.code} 详情`, { entity, material: { ...m, inTransit } }, `已按 entity=material、code=${m.code} 返回详情:现有 ${m.stock}${m.unit},在途 ${inTransit}。`);
440
+ }
441
+ let list = all.slice();
442
+ if (p.keyword) list = list.filter((x) => x.code.toLowerCase().includes(p.keyword.toLowerCase()) || x.name.includes(p.keyword));
443
+ if (p.category) list = list.filter((x) => x.category === p.category);
444
+ 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} 种物料。`);
445
+ }
446
+ // sales_order
447
+ let list = SALES_ORDERS.slice();
448
+ if (p.code) list = list.filter((x) => x.code === p.code);
449
+ if (p.customer) list = list.filter((x) => x.customer === p.customer);
450
+ if (p.status) list = list.filter((x) => x.status === p.status);
451
+ return reply('query_master_data', p, `${list.length} 张销售订单`, { entity, total: list.length, items: list }, `已按 entity=sales_order${p.customer ? '、customer=' + p.customer : ''} 返回 ${list.length} 张销售订单。`);
452
+ },
453
+
454
+ estimate_hours(p) {
455
+ const scope = p.scope;
456
+ if (!['work_order', 'process', 'product'].includes(scope)) return errReply('estimate_hours', p, 'scope 必填,取值 work_order/process/product');
457
+ if (scope === 'product') {
458
+ const pr = getProduct(p.product);
459
+ if (!pr) return errReply('estimate_hours', p, `未找到产品 ${p.product}`);
460
+ const qty = p.quantity || 1;
461
+ return reply('estimate_hours', p, `${pr.code} 标准工时`, {
462
+ scope, product: pr.code, productName: pr.name, flowType: pr.flowType,
463
+ unitStandardHours: +unitHours(pr).toFixed(3),
464
+ quantity: qty,
465
+ totalStandardHours: +(unitHours(pr) * qty).toFixed(2),
466
+ routing: pr.routing.map((r) => ({ sequence: r.sequence, name: r.name, minutes: r.minutes })),
467
+ note: pr.flowType === 'flow' ? 'flow 产品整单由瓶颈工序决定,不能把各工序工时相加' : 'batch 产品整单≈各工序工时之和',
468
+ }, `已按 scope=product、product=${pr.code} 计算:单件标准工时 ${unitHours(pr).toFixed(3)} 小时。`);
469
+ }
470
+ if (scope === 'work_order') {
471
+ const wo = getWO(p.work_order);
472
+ if (!wo) return errReply('estimate_hours', p, `未找到工单 ${p.work_order}`);
473
+ const pr = getProduct(wo.product);
474
+ const line = p.line || wo.line || (pr && pr.routing[0].workCenter);
475
+ const h = orderHours(wo);
476
+ const finish = dayOffset(Math.ceil(h / 8));
477
+ return reply('estimate_hours', p, `${wo.code} 整单工时`, {
478
+ scope, work_order: wo.code, product: wo.product, flowType: pr && pr.flowType,
479
+ line, quantity: wo.qty, remainingQty: Math.max(wo.qty - (wo.actualQty || 0), 0),
480
+ totalHours: h, estimatedFinishDate: finish,
481
+ calibrated: !!p.calibrate,
482
+ calibrationFactor: p.calibrate ? 1.12 : null,
483
+ note: p.calibrate ? '已附带历史偏差校准系数 1.12(基于近 30 天完工工单)' : '未做历史校准',
484
+ }, `已按 scope=work_order、work_order=${wo.code} 计算:整单约 ${h} 小时,预计完工 ${finish}。`);
485
+ }
486
+ // process
487
+ const pr = getProduct(p.product);
488
+ if (!pr) return errReply('estimate_hours', p, `未找到产品 ${p.product}(scope=process 需传 product)`);
489
+ const r = pr.routing.find((x) => x.sequence === (p.sequence || (pr.routing[0] || {}).sequence));
490
+ if (!r) return errReply('estimate_hours', p, `产品 ${pr.code} 没有工序序号 ${p.sequence}`);
491
+ const qty = p.quantity || 1;
492
+ const runH = +(r.minutes * qty / 60).toFixed(2);
493
+ return reply('estimate_hours', p, `${pr.code} 工序 ${r.sequence} 工时`, {
494
+ scope, product: pr.code, sequence: r.sequence, processName: r.name,
495
+ workCenter: p.line || r.workCenter, quantity: qty,
496
+ runHours: runH, setupHours: +(r.setupMinutes / 60).toFixed(2),
497
+ postWaitMinutes: r.postWaitMinutes || 0,
498
+ occupiedHours: +(runH + r.setupMinutes / 60).toFixed(2),
499
+ }, `已按 scope=process、product=${pr.code}、sequence=${r.sequence} 计算:运行 ${runH} 小时。`);
500
+ },
501
+
502
+ check_readiness(p) {
503
+ const wo = getWO(p.work_order);
504
+ if (!wo) return errReply('check_readiness', p, `未找到工单 ${p.work_order}`);
505
+ const rd = readinessOf(wo);
506
+ if (p.at_sequence) {
507
+ const pr = getProduct(wo.product);
508
+ const seqs = (pr && pr.routing || []).filter((r) => r.sequence >= p.at_sequence).map((r) => r.sequence);
509
+ rd.atSequence = p.at_sequence;
510
+ rd.note = `工序级齐套:仅看第 ${p.at_sequence} 道及之后(工序 ${seqs.join('/')})所需物料`;
511
+ }
512
+ return reply('check_readiness', p, `${wo.code} 齐套检查`, rd,
513
+ `已按 work_order=${wo.code} 检查:${rd.isReady ? '齐套,可开工' : `不齐套,缺 ${rd.shortageKinds} 种料,缺口 ${rd.shortageQty}`}。`);
514
+ },
515
+
516
+ preview_schedule(p) {
517
+ const preserve = !!p.preserve_existing;
518
+ let pending = WORK_ORDERS.filter((w) => w.status === '待排产');
519
+ if (p.work_order) {
520
+ const wo = getWO(p.work_order);
521
+ if (!wo) return errReply('preview_schedule', p, `未找到工单 ${p.work_order}`);
522
+ pending = [wo];
523
+ }
524
+ const ov = p.overrides || {};
525
+ const freezeDays = Math.min(30, Math.max(0, ov.freeze_days == null ? 3 : ov.freeze_days));
526
+ const capacityScale = Math.min(3, Math.max(0.1, ov.capacity_scale == null ? 1 : ov.capacity_scale));
527
+ const cp = ov.constraint_policy && typeof ov.constraint_policy === 'object' ? ov.constraint_policy : {};
528
+ const strategy = STRATEGY_IDS.includes(ov.strategy) ? ov.strategy : null;
529
+ const applied = {
530
+ freeze_days: freezeDays,
531
+ capacity_scale: capacityScale,
532
+ constraint_policy: { kit: ['soft', 'hard', 'off'].includes(cp.kit) ? cp.kit : 'soft', delivery: ['soft', 'hard', 'off'].includes(cp.delivery) ? cp.delivery : 'soft' },
533
+ strategy,
534
+ };
535
+ pending = sortPending(pending, strategy);
536
+ let cursor = dayOffset(freezeDays);
537
+ const items = pending.map((w) => {
538
+ const pr = getProduct(w.product);
539
+ const line = w.line || (pr && pr.routing[0].workCenter) || LINES[0];
540
+ const h = +(orderHours(w) / capacityScale).toFixed(2);
541
+ const spanDays = Math.max(1, Math.ceil(h / 8));
542
+ const start = preserve && w.planStart ? w.planStart : cursor;
543
+ const end = dayOffset(daysBetween(start, cursor) + spanDays);
544
+ const rd = readinessOf(w);
545
+ const item = {
546
+ work_order: w.code, product: w.product, suggestedLine: line,
547
+ planStart: start, planEnd: end, hoursModel: pr && pr.flowType,
548
+ hours: h, scheduleLevel: 'L2.5',
549
+ ...(applied.constraint_policy.kit === 'hard' && !rd.isReady ? { error: `物料不齐套(缺 ${rd.shortageKinds} 种)` } : {}),
550
+ notes: [`主产线按整单总工时占用,跨工位份额已分摊到 ${line}`],
551
+ };
552
+ cursor = dayOffset(daysBetween(start, cursor) + spanDays + 1);
553
+ return item;
554
+ });
555
+ return reply('preview_schedule', p, `预演 ${items.length} 张待排产工单`, {
556
+ scope: p.work_order ? 'single' : 'all',
557
+ total: items.length,
558
+ preserveExisting: preserve,
559
+ appliedOverrides: applied,
560
+ schedule: items,
561
+ isPreviewOnly: true,
562
+ note: '这是只读预演,不写库;如需落库须先复述结果并取得用户确认后调用 apply_schedule',
563
+ }, `已按${p.work_order ? 'work_order=' + p.work_order : '全部待排产工单'}预演 ${items.length} 张,应用参数 freeze_days=${freezeDays}、capacity_scale=${capacityScale}${strategy ? '、排序策略=' + STRATEGY_LABELS[strategy] : ''}。`);
564
+ },
565
+
566
+ compare_schedule_strategies(p) {
567
+ const requested = Array.isArray(p.strategies) && p.strategies.length
568
+ ? [...new Set(p.strategies.filter((s) => STRATEGY_IDS.includes(s)))]
569
+ : STRATEGY_IDS.slice();
570
+ if (!requested.length) return errReply('compare_schedule_strategies', p, 'strategies 只认 current / edd / changeover_cluster / spt');
571
+ let pending = WORK_ORDERS.filter((w) => w.status === '待排产');
572
+ if (p.work_order) {
573
+ const wo = getWO(p.work_order);
574
+ if (!wo) return errReply('compare_schedule_strategies', p, `未找到工单 ${p.work_order}`);
575
+ pending = [wo];
576
+ }
577
+ if (pending.length < 2) {
578
+ return reply('compare_schedule_strategies', p, '待排产工单不足 2 张,比选无意义', {
579
+ woCount: pending.length,
580
+ strategies: [],
581
+ note: '至少需要 2 张待排产工单才能比较不同排序策略的差异。',
582
+ }, `待排产工单只有 ${pending.length} 张,排序策略比选没有意义。`);
583
+ }
584
+
585
+ const plans = requested.map((sid) => ({ id: sid, label: STRATEGY_LABELS[sid], ordered: sortPending(pending, sid) }));
586
+ const data = computeComparePlans(pending, plans);
587
+ const best = plans.find((x) => x.id === data.best) || plans[0];
588
+ return reply('compare_schedule_strategies', p, `四策略比选完成,推荐 ${best.label}`, data,
589
+ `已对 ${pending.length} 张待排产工单按 ${requested.length} 种排序策略各预演一次,综合分最低的是「${best.label}」(${best.score} 分)。`);
590
+ },
591
+
592
+ apply_schedule(p) {
593
+ if (Array.isArray(p.schedule)) {
594
+ return reply('apply_schedule', p, `模拟落库 ${p.schedule.length} 张`, {
595
+ applied: true, simulated: true, count: p.schedule.length,
596
+ details: p.schedule.map((s) => ({ work_order: s.work_order, line: s.suggestedLine, planStart: s.planStart, planEnd: s.planEnd })),
597
+ skipped: 0,
598
+ note: '演示模式:未实际写入数据库;安装桌面版后调用会真实落库并写变更日志',
599
+ }, `已按 schedule(${p.schedule.length} 项)模拟落库成功。`);
600
+ }
601
+ const pending = WORK_ORDERS.filter((w) => w.status === '待排产');
602
+ return reply('apply_schedule', p, `模拟自动排 ${pending.length} 张`, {
603
+ applied: true, simulated: true, count: pending.length,
604
+ details: pending.map((w) => ({ work_order: w.code, line: w.line || LINES[0], planStart: dayOffset(1), planEnd: dayOffset(3) })),
605
+ skipped: 0,
606
+ note: '演示模式:未实际写入数据库',
607
+ }, `已按${p.work_order ? 'work_order=' + p.work_order : '内部自动排全部'}模拟落库 ${pending.length} 张。`);
608
+ },
609
+
610
+ compare_schedule_algorithms(p) {
611
+ const IDS = ['baseline', 'bottleneck_first', 'local_improve', 'constraint_aware', 'window_search'];
612
+ const LABELS = {
613
+ baseline: '标准排程(贪心基线)',
614
+ bottleneck_first: '瓶颈优先(进阶·只读)',
615
+ local_improve: '局部改进(进阶·只读)',
616
+ constraint_aware: '硬约束传播(进阶·只读)',
617
+ window_search: '窗口精确搜索(实验·只读)',
618
+ };
619
+ let requested = Array.isArray(p.engines) && p.engines.length
620
+ ? [...new Set(p.engines.filter((s) => IDS.includes(s)))] : IDS.slice();
621
+ if (!requested.length) return errReply('compare_schedule_algorithms', p, 'engines 只认 baseline / bottleneck_first / local_improve / constraint_aware / window_search');
622
+ if (!requested.includes('baseline')) requested.unshift('baseline');
623
+ let pending = WORK_ORDERS.filter((w) => w.status === '待排产');
624
+ if (p.work_order) {
625
+ const wo = getWO(p.work_order);
626
+ if (!wo) return errReply('compare_schedule_algorithms', p, `未找到工单 ${p.work_order}`);
627
+ pending = [wo];
628
+ }
629
+ if (pending.length < 2) {
630
+ return reply('compare_schedule_algorithms', p, '待排产工单不足 2 张,算法比选无意义', {
631
+ woCount: pending.length, engines: [], note: '至少需要 2 张待排产工单。',
632
+ }, `待排产工单只有 ${pending.length} 张,算法比选没有意义。`);
633
+ }
634
+ const base = sortPending(pending, 'current');
635
+ const lineLoad = {};
636
+ for (const w of pending) {
637
+ const ln = w.line || LINES[0];
638
+ lineLoad[ln] = (lineLoad[ln] || 0) + orderHours(w);
639
+ }
640
+ const bottleneck = Object.keys(lineLoad).sort((a, b) => lineLoad[b] - lineLoad[a])[0];
641
+ const bottleneckOrder = [...pending.filter((w) => (w.line || LINES[0]) === bottleneck),
642
+ ...pending.filter((w) => (w.line || LINES[0]) !== bottleneck)];
643
+ const baseEval = computeComparePlans(pending, [{ id: 'baseline', label: LABELS.baseline, ordered: base }]).strategies[0];
644
+ let localOrder = base.slice();
645
+ const swapped = base.slice();
646
+ if (swapped.length > 1) { const t = swapped[0]; swapped[0] = swapped[1]; swapped[1] = t; }
647
+ const swapEval = computeComparePlans(pending, [{ id: 'local_improve', label: LABELS.local_improve, ordered: swapped }]).strategies[0];
648
+ if (swapEval.score < baseEval.score) localOrder = swapped;
649
+ // 实验求解档:前 N 张工单有界枚举,纯 JS 实现,不引入外部求解器。
650
+ const windowLimit = Math.min(5, base.length);
651
+ const permuteWindow = (limit, max) => {
652
+ const out = [], cur = [], used = new Array(limit).fill(false);
653
+ const walk = () => {
654
+ if (out.length >= max) return;
655
+ if (cur.length === limit) { out.push(cur.slice()); return; }
656
+ for (let i = 0; i < limit; i++) {
657
+ if (used[i]) continue;
658
+ used[i] = true; cur.push(i); walk(); cur.pop(); used[i] = false;
659
+ if (out.length >= max) return;
660
+ }
661
+ };
662
+ if (limit > 0) walk();
663
+ return out;
664
+ };
665
+ let windowOrder = base.slice();
666
+ let windowBestEval = baseEval;
667
+ let windowAccepted = 0;
668
+ for (const perm of permuteWindow(windowLimit, 60).slice(1)) {
669
+ const cand = base.slice();
670
+ perm.forEach((idx, slot) => { cand[slot] = base[idx]; });
671
+ const ev = computeComparePlans(pending, [{ id: 'probe', label: '', ordered: cand }]).strategies[0];
672
+ if (ev.score + 0.05 < windowBestEval.score) { windowBestEval = ev; windowOrder = cand; windowAccepted++; }
673
+ }
674
+ const orders = {
675
+ baseline: base,
676
+ bottleneck_first: bottleneckOrder,
677
+ local_improve: localOrder,
678
+ constraint_aware: base.slice(),
679
+ window_search: windowOrder,
680
+ };
681
+ const plans = requested.map((id) => ({ id, label: LABELS[id], ordered: orders[id] }));
682
+ const data = computeComparePlans(pending, plans);
683
+ const engines = data.strategies.map((s) => ({
684
+ ...s,
685
+ baselineScore: baseEval.score,
686
+ deltaScore: +(s.score - baseEval.score).toFixed(1),
687
+ hardBlocked: [],
688
+ explanation: s.id === 'baseline'
689
+ ? '标准排程:传入顺序即优先级,单次贪心分配。'
690
+ : s.id === 'bottleneck_first'
691
+ ? `瓶颈优先:按待排工时识别瓶颈产线 ${bottleneck},先连排瓶颈线工单。`
692
+ : s.id === 'local_improve'
693
+ ? `局部改进:以基线为起点试探相邻交换,接受 ${localOrder === base ? 0 : 1} 次 KPI 变好的调整。`
694
+ : s.id === 'constraint_aware'
695
+ ? '硬约束传播:演示模式无真实缺料/交期数据,hardBlocked 为空;桌面版返回真实拦截原因。'
696
+ : `窗口精确搜索(实验):前 ${windowLimit} 张工单枚举最多 60 种排列,接受 ${windowAccepted} 次改进;无外部求解器。`,
697
+ }));
698
+ const bestEngine = engines.reduce((a, b) => (b.score < a.score ? b : a), engines[0]);
699
+
700
+ // 阶段 3 影子运行:只读轮换到达顺序,验证优势是否稳定;窗口搜索不参与。
701
+ let shadow = null;
702
+ if (p.shadow === true) {
703
+ const rounds = Math.max(2, Math.min(5, Number(p.shadow_rounds || p.shadowRounds) || 3));
704
+ const scoreOrder = (list, ordered) =>
705
+ computeComparePlans(list, [{ id: 'x', label: '', ordered }]).strategies[0].score;
706
+ const rows = requested.filter((id) => id !== 'baseline' && id !== 'window_search').map((id) => {
707
+ const deltas = [];
708
+ let wins = 0;
709
+ for (let r = 1; r <= rounds; r++) {
710
+ const rotated = pending.slice(r).concat(pending.slice(0, r));
711
+ const b = sortPending(rotated, 'current');
712
+ let adv = b;
713
+ if (id === 'bottleneck_first') {
714
+ const load = {};
715
+ rotated.forEach((w) => { const ln = w.line || LINES[0]; load[ln] = (load[ln] || 0) + orderHours(w); });
716
+ const bl = Object.keys(load).sort((x, y) => load[y] - load[x])[0];
717
+ adv = [...rotated.filter((w) => (w.line || LINES[0]) === bl),
718
+ ...rotated.filter((w) => (w.line || LINES[0]) !== bl)];
719
+ } else if (id === 'local_improve') {
720
+ const c = b.slice();
721
+ if (c.length > 1) { const t = c[0]; c[0] = c[1]; c[1] = t; }
722
+ adv = scoreOrder(rotated, c) < scoreOrder(rotated, b) ? c : b;
723
+ }
724
+ const d = +(scoreOrder(rotated, adv) - scoreOrder(rotated, b)).toFixed(1);
725
+ deltas.push(d);
726
+ if (d < -0.05) wins++;
727
+ }
728
+ const avg = +(deltas.reduce((a, b) => a + b, 0) / deltas.length).toFixed(1);
729
+ return {
730
+ id, label: LABELS[id], rounds, deltas, wins, avgDeltaScore: avg,
731
+ consistentWin: wins === rounds && avg < -0.05,
732
+ };
733
+ });
734
+ const any = rows.some((r) => r.consistentWin);
735
+ shadow = {
736
+ enabled: true, rounds, rows,
737
+ note: '演示模式:只读轮换到达顺序;窗口搜索不参与影子轮次。',
738
+ recommendation: any
739
+ ? '影子运行多轮稳定优于基线,但演示模式未判定真实门禁,仅建议小范围试用。'
740
+ : '影子运行未显示稳定优势:维持标准排程。',
741
+ };
742
+ }
743
+
744
+ return reply('compare_schedule_algorithms', p, `算法比选完成,推荐 ${bestEngine.label}`, {
745
+ woCount: pending.length,
746
+ engines,
747
+ best: bestEngine.id,
748
+ baselineEngine: 'baseline',
749
+ unlock: { standardAlwaysAvailable: true, advancedPreviewScore: 60, advancedApplyScore: 80,
750
+ gates: [
751
+ { key: 'changeover', title: '换型矩阵覆盖率', ratio: null, status: 'unknown', target: '≥90%', detail: '演示模式不读取真实换型矩阵', suggestion: '在桌面版评分卡查看真实覆盖率' },
752
+ { key: 'schedule', title: '冻结期/交期可信度', ratio: null, status: 'unknown', target: '≥90%', detail: '演示模式不读取真实交期与冻结期', suggestion: '在桌面版评分卡查看真实可信度' },
753
+ { key: 'reporting', title: '报工及时率', ratio: null, status: 'unknown', target: '≥85%', detail: '演示模式不读取真实报工记录', suggestion: '在桌面版评分卡查看真实及时率' },
754
+ ],
755
+ gatesPassed: false,
756
+ note: '进阶引擎默认只读预演;演示模式无法判定真实硬门禁,不会提示可应用。' },
757
+ shadow,
758
+ scoreFormula: data.scoreFormula,
759
+ note: '演示模式为简化串行模型;deltaScore<0 表示相对标准基线更优(分更低)。只读不落库。',
760
+ isPreviewOnly: true,
761
+ }, `已对 ${pending.length} 张待排产工单按 ${requested.length} 档引擎预演,综合分最低的是「${bestEngine.label}」(${bestEngine.score} 分)。`);
762
+ },
763
+
764
+ reschedule_from_actuals(p) {
765
+ const wo = getWO(p.work_order);
766
+ if (!wo) return errReply('reschedule_from_actuals', p, `未找到工单 ${p.work_order}`);
767
+ const from = p.from_date || TODAY;
768
+ const pr = getProduct(wo.product);
769
+ const remain = Math.max(wo.qty - (wo.actualQty || 0), 0);
770
+ const progs = PROCESS_PROGRESS[wo.code] || [];
771
+ return reply('reschedule_from_actuals', p, `${wo.code} 滚动重排`, {
772
+ work_order: wo.code, fromDate: from, line: wo.line,
773
+ pinnedProcesses: progs.filter((x) => x.actualQty >= x.planQty).map((x) => x.sequence),
774
+ remainingQty: remain,
775
+ newPlanStart: from,
776
+ newPlanEnd: dayOffset(daysBetween(from, TODAY) + Math.max(1, Math.ceil(orderHours(wo) / 8))),
777
+ dueDate: wo.dueDate,
778
+ lateRisk: daysBetween(wo.dueDate, dayOffset(daysBetween(from, TODAY) + 2)) < 0,
779
+ note: '已完成工序按实际报工钉死,仅对剩余量重排;演示模式未落库',
780
+ }, `已按 work_order=${wo.code}、from_date=${from} 重排:剩余 ${remain} 件。`);
781
+ },
782
+
783
+ report_progress(p) {
784
+ 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 为必填');
785
+ const wo = getWO(p.work_order);
786
+ if (!wo) return errReply('report_progress', p, `未找到工单 ${p.work_order}`);
787
+ return reply('report_progress', p, `模拟报工 ${p.work_order}`, {
788
+ success: true, simulated: true,
789
+ work_order: wo.code,
790
+ process_sequence: p.process_sequence || null,
791
+ actual_qty: p.actual_qty, actual_hours: p.actual_hours,
792
+ client_request_id: p.client_request_id || null,
793
+ idempotent: !!p.client_request_id,
794
+ recordedAt: TODAY,
795
+ note: '演示模式:未实际写入;写操作不可撤销,真实环境调用前须复述数量与工时并取得确认',
796
+ }, `已按 work_order=${wo.code}、工序=${p.process_sequence || '整单'}、数量=${p.actual_qty}、工时=${p.actual_hours} 模拟报工成功。`);
797
+ },
798
+
799
+ report_incident(p) {
800
+ if (!p.type) return errReply('report_incident', p, 'type 必填(shortage/breakdown/quality)');
801
+ if (p.type !== 'shortage' && !p.description) return errReply('report_incident', p, '故障与质量类异常必须填写 description');
802
+ return reply('report_incident', p, '模拟异常登记', {
803
+ success: true, simulated: true,
804
+ incident_id: 'EXP-DEMO-001',
805
+ work_order: p.work_order || null, type: p.type,
806
+ minutes: p.minutes || null, description: p.description || '缺料类(系统可自行关联缺料明细)',
807
+ reported_by: p.reported_by || null, reportedAt: TODAY,
808
+ note: '演示模式:未实际写入',
809
+ }, `已按 type=${p.type}、work_order=${p.work_order || '全厂'} 模拟登记异常成功。`);
810
+ },
811
+
812
+ query_records(p) {
813
+ const type = p.type;
814
+ if (!type) return errReply('query_records', p, 'type 必填,可选 report/progress/incident/labor');
815
+ const from = p.from || dayOffset(-30);
816
+ const to = p.to || TODAY;
817
+ const inRange = (d) => daysBetween(from, d) >= 0 && daysBetween(d, to) >= 0;
818
+ const limit = Math.min(200, Math.max(1, p.limit || 50));
819
+ const woFilter = p.work_order ? (w) => w === p.work_order : () => true;
820
+
821
+ // report=报工流水;progress=报工进度(同报工但强调工序进度);incident=异常;labor=出勤(人力出勤)
822
+ if (type === 'report' || type === 'progress') {
823
+ let rows = REPORT_RECORDS.filter((r) => inRange(r.date) && woFilter(r.work_order));
824
+ if (type === 'progress') {
825
+ rows = rows.map((r) => {
826
+ const prog = (PROCESS_PROGRESS[r.work_order] || []).find((x) => x.sequence === r.sequence);
827
+ return { ...r, planQty: prog ? prog.planQty : r.qty, isProgressView: true };
828
+ });
829
+ }
830
+ return reply('query_records', p, `${rows.length} 条${type === 'report' ? '报工' : '进度'}记录`, {
831
+ type, from, to, filtersEcho: { work_order: p.work_order || null },
832
+ total: rows.length, records: rows.slice(0, limit),
833
+ note: type === 'progress' ? 'progress=报工进度视角(含工序计划数/已报数),等同 report 数据源' : 'report=报工流水',
834
+ }, `已按 type=${type}、from=${from}、to=${to}${p.work_order ? '、work_order=' + p.work_order : ''} 返回 ${rows.length} 条记录。`);
835
+ }
836
+ if (type === 'incident') {
837
+ let rows = INCIDENTS.filter((r) => inRange(r.date) && woFilter(r.work_order));
838
+ if (p.incident_type) rows = rows.filter((r) => r.type === p.incident_type);
839
+ return reply('query_records', p, `${rows.length} 条异常记录`, {
840
+ type, from, to, filtersEcho: { work_order: p.work_order || null, incident_type: p.incident_type || null },
841
+ total: rows.length, records: rows.slice(0, limit),
842
+ note: 'incident=异常记录;可按 incident_type=shortage/breakdown/quality 过滤',
843
+ }, `已按 type=incident、incident_type=${p.incident_type || '全部'}、from=${from} 返回 ${rows.length} 条异常。`);
844
+ }
845
+ if (type === 'labor') {
846
+ const rows = ATTENDANCE_RECORDS.filter((r) => inRange(r.date));
847
+ return reply('query_records', p, `${rows.length} 条出勤记录`, {
848
+ type, from, to, total: rows.length, records: rows.slice(0, limit),
849
+ fields: { headcount: '出勤人数', overtimeHours: '加班工时', hours: '出勤工时', line: '产线', shift: '班次' },
850
+ note: 'labor=人力出勤(出勤人数/加班),与 get_dashboard(scope=labor) 的工时健康度口径不同;这是评测点名的口径补充',
851
+ }, `已按 type=labor、from=${from}、to=${to} 返回 ${rows.length} 条出勤记录,含出勤人数。`);
852
+ }
853
+ return errReply('query_records', p, `type=${type} 无效,可选 report/progress/incident/labor`);
854
+ },
855
+
856
+ evaluate_order(p) {
857
+ const wo = getWO(p.work_order);
858
+ if (!wo) return errReply('evaluate_order', p, `未找到工单 ${p.work_order}`);
859
+ const rd = readinessOf(wo);
860
+ const h = orderHours(wo);
861
+ const due = p.due_date || wo.dueDate;
862
+ const plannedEnd = dayOffset(Math.max(0, daysBetween(TODAY, TODAY)) + Math.ceil(h / 8));
863
+ const slip = daysBetween(plannedEnd, due) < 0 ? -daysBetween(plannedEnd, due) : 0;
864
+ const gates = {
865
+ material: rd.isReady ? 'pass' : (rd.materials.some((m) => m.inTransit >= m.gap) ? 'conditional' : 'block'),
866
+ capacity: h <= 8 * 3 ? 'pass' : 'conditional',
867
+ delivery: slip === 0 ? 'pass' : (slip <= 3 ? 'conditional' : 'block'),
868
+ hourBaseline: 'pass',
869
+ };
870
+ const color = Object.values(gates).includes('block') ? 'red' : Object.values(gates).includes('conditional') ? 'amber' : 'green';
871
+ const actions = [];
872
+ if (gates.material !== 'pass') actions.push(`补齐物料:缺 ${rd.shortageKinds} 种料,催 ${rd.materials.filter((m) => m.gap > 0).map((m) => m.material).join('、')}`);
873
+ if (gates.delivery !== 'pass') actions.push(`交期余量 ${-daysBetween(plannedEnd, due)} 天,预计晚 ${slip} 天`);
874
+ if (!actions.length) actions.push('四门全过,可按计划开工');
875
+ return reply('evaluate_order', p, `${wo.code} 评审结论 ${color}`, {
876
+ work_order: wo.code, conclusion: color,
877
+ gates,
878
+ dueSource: p.due_date ? 'user' : (wo.salesOrder ? 'sales_order' : 'work_order_plan'),
879
+ dueDate: due,
880
+ plannedEnd, planSlippageDays: slip,
881
+ actions,
882
+ marginEstimate: { available: false, note: '演示数据未关联销售单价,不提供毛利数字' },
883
+ }, `已按 work_order=${wo.code} 评审:三色结论 ${color},计划完工 ${plannedEnd},计划偏差 ${slip} 天。`);
884
+ },
885
+
886
+ assess_insertion(p) {
887
+ const anchor = p.anchor_date || TODAY;
888
+ const maxShift = p.max_shift_days || 3;
889
+ const affected = WORK_ORDERS.filter((w) => w.status === '待排产' || w.status === '进行中').slice(0, 4).map((w, i) => ({
890
+ work_order: w.code, product: w.product,
891
+ originalStart: w.planStart || anchor,
892
+ newStart: dayOffset(daysBetween(anchor, TODAY) + i + 1),
893
+ shiftDays: i + 1,
894
+ crossesDueDate: daysBetween(dayOffset(daysBetween(anchor, TODAY) + i + 1), w.dueDate) < 0,
895
+ }));
896
+ const line = p.line || (getWO(p.work_order) || {}).line || LINES[0];
897
+ return reply('assess_insertion', p, '插单四档评估', {
898
+ 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 },
899
+ targetLine: line,
900
+ affectedOrders: affected,
901
+ options: [
902
+ { plan: '守', desc: '不动已排单,新单排到最后', totalShiftDays: 0, dueRisk: true, changeoverDelta: 1 },
903
+ { plan: '拆', desc: '拆一张已排单让出时段', totalShiftDays: 2, dueRisk: false, changeoverDelta: 2 },
904
+ { plan: '延', desc: `接受其他工单顺延 ≤${maxShift} 天`, totalShiftDays: affected.reduce((s, a) => s + Math.min(a.shiftDays, maxShift), 0), dueRisk: false, changeoverDelta: 1 },
905
+ { plan: '换线', desc: '改到其他工艺匹配的产线', feasible: false, reason: '演示数据中其他产线工艺路线不匹配,不能仅凭空闲判定可行' },
906
+ ],
907
+ recommended: '延',
908
+ note: '只读评估,不写入;不得替用户决定牺牲哪张单',
909
+ }, `已按 ${p.work_order ? 'work_order=' + p.work_order : 'product=' + p.product + '、quantity=' + p.quantity} 评估插单,目标线 ${line},受影响 ${affected.length} 张。`);
910
+ },
911
+
912
+ get_import_schema() {
913
+ return reply('get_import_schema', {}, '导入契约', {
914
+ ...IMPORT_SCHEMA,
915
+ note: '先取契约 → 再 import_data(mode=preview) → 复述新增/更新/错误并取得确认 → 最后 mode=apply',
916
+ }, '已返回导入契约:可导入表、字段定义、编码规则与处理顺序。');
917
+ },
918
+
919
+ import_data(p) {
920
+ const mode = p.mode;
921
+ if (!['preview', 'apply'].includes(mode)) return errReply('import_data', p, 'mode 必填,取值 preview/apply');
922
+ const data = p.data || {};
923
+ const tables = Object.keys(data);
924
+ const counts = {};
925
+ for (const t of tables) {
926
+ const rows = Array.isArray(data[t]) ? data[t] : [];
927
+ counts[t] = { total: rows.length, willAdd: rows.length, willUpdate: 0, errors: 0 };
928
+ }
929
+ if (mode === 'preview') {
930
+ return reply('import_data', p, '导入预览', {
931
+ mode: 'preview', simulated: true,
932
+ tables: counts,
933
+ summary: `新增 ${tables.reduce((s, t) => s + counts[t].willAdd, 0)} / 更新 0 / 错误 0`,
934
+ note: '演示模式:未实际预览入临时区;确认后调用 mode=apply',
935
+ }, `已按 mode=preview 预览 ${tables.length} 张表:${JSON.stringify(counts)}。`);
936
+ }
937
+ return reply('import_data', p, '模拟导入落库', {
938
+ mode: 'apply', simulated: true,
939
+ idempotency_key: p.idempotency_key || null,
940
+ tables: counts,
941
+ imported: tables.reduce((s, t) => s + counts[t].willAdd, 0),
942
+ note: '演示模式:未实际写入数据库',
943
+ }, `已按 mode=apply 模拟导入 ${tables.length} 张表。`);
944
+ },
945
+
946
+ explain_delay(p) {
947
+ const wo = getWO(p.work_order);
948
+ if (!wo) return errReply('explain_delay', p, `未找到工单 ${p.work_order}`);
949
+ const progs = PROCESS_PROGRESS[wo.code] || [];
950
+ const lateDays = wo.planEnd ? Math.max(0, daysBetween(wo.planEnd, TODAY)) : 0;
951
+ const rd = readinessOf(wo);
952
+ const stalled = progs.find((x) => x.actualQty < x.planQty && daysBetween(wo.planStart, TODAY) > 0);
953
+ const hourOver = REPORT_RECORDS.filter((r) => r.work_order === wo.code && r.hours > r.standardHours * 1.3);
954
+ let cause = { label: '未延期', evidence: '该单计划完工日未过或已完工,无滑期' };
955
+ const others = [];
956
+ if (lateDays > 0) {
957
+ if (wo.status === '已完成' && wo.finishedAt) {
958
+ cause = { label: '完工待入库', evidence: `实际完工 ${wo.finishedAt},晚于计划完工 ${wo.planEnd} ${lateDays} 天` };
959
+ } else if (!rd.isReady) {
960
+ cause = { label: '缺料', evidence: `缺 ${rd.shortageKinds} 种料(${rd.materials.filter((m) => m.gap > 0).map((m) => m.material).join('、')}),缺口 ${rd.shortageQty}` };
961
+ } else if (stalled) {
962
+ cause = { label: '工序超期', evidence: `工序 ${stalled.sequence} 计划 ${stalled.planQty} 已报 ${stalled.actualQty},计划完工日已过` };
963
+ } else if (hourOver.length) {
964
+ cause = { label: '工时超估', evidence: `${hourOver.length} 条报工实际工时超标准 30% 以上` };
965
+ } else {
966
+ cause = { label: '排程过紧', evidence: `计划完工 ${wo.planEnd},当前已滑期 ${lateDays} 天,工时余量不足` };
967
+ }
968
+ if (rd.shortageKinds) others.push(`叠加缺料 ${rd.shortageKinds} 种`);
969
+ if (hourOver.length) others.push('叠加工时超估');
970
+ others.push(`滑期 ${lateDays} 天(计划完工 ${wo.planEnd})`);
971
+ }
972
+ return reply('explain_delay', p, `${wo.code} 延期归因`, {
973
+ work_order: wo.code, isLate: lateDays > 0, lateDays,
974
+ processProgress: progs,
975
+ 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) },
976
+ mainCause: cause, otherCauses: others,
977
+ suggestion: lateDays > 0 ? (cause.label === '缺料' ? '先催料并确认到货日,再重排该单' : '钉住已完成工序,按剩余量滚动重排') : '无需补救,按计划执行',
978
+ }, `已按 work_order=${wo.code} 归因:${lateDays > 0 ? '滑期 ' + lateDays + ' 天,主因「' + cause.label + '」' : '未延期'}。`);
979
+ },
980
+
981
+ suggest_purchase(p) {
982
+ const horizon = Math.min(180, Math.max(1, p.horizon_days || 14));
983
+ const limit = Math.min(100, Math.max(1, p.limit || 20));
984
+ const active = WORK_ORDERS.filter((w) => w.status !== '已完成' && w.status !== '已取消' && (!w.planEnd || daysBetween(TODAY, w.planEnd) <= horizon));
985
+ const need = {};
986
+ const earliest = {};
987
+ for (const w of active) {
988
+ for (const r of bomExplode(w.product, Math.max(w.qty - (w.actualQty || 0), 0), 3)) {
989
+ need[r.material] = +((need[r.material] || 0) + r.grossQty).toFixed(3);
990
+ const d = w.planStart || TODAY;
991
+ if (!earliest[r.material] || daysBetween(d, earliest[r.material]) > 0) earliest[r.material] = d;
992
+ }
993
+ }
994
+ const items = Object.keys(need).map((k) => {
995
+ const mat = getMaterial(k);
996
+ const stock = mat ? mat.stock : 0;
997
+ const pos = PURCHASE_ORDERS.filter((o) => o.material === k && o.receivedQty < o.qty);
998
+ const inTransit = pos.reduce((s, o) => s + (o.qty - o.receivedQty), 0);
999
+ const eta = pos.length ? pos.map((o) => o.eta).sort()[0] : null;
1000
+ const net = +(need[k] - stock - inTransit).toFixed(3);
1001
+ return {
1002
+ material: k, name: mat ? mat.name : k, unit: mat ? mat.unit : '',
1003
+ grossNeed: need[k], stock, inTransit, eta,
1004
+ netGap: net > 0 ? net : 0,
1005
+ suggestQty: net > 0 ? Math.ceil(net) : 0,
1006
+ earliestNeedDate: earliest[k],
1007
+ inTransitLate: eta && daysBetween(eta, earliest[k]) > 0,
1008
+ };
1009
+ }).filter((x) => x.netGap > 0).sort((a, b) => b.netGap - a.netGap).slice(0, limit);
1010
+ return reply('suggest_purchase', p, `${items.length} 项采购建议`, {
1011
+ horizonDays: horizon, total: items.length, items,
1012
+ note: '只建议不下单;结果不含供应商提前期与最小起订量,不含制造费用',
1013
+ }, `已按 horizon_days=${horizon}、limit=${limit} 计算:${items.length} 项需采购,${items.slice(0, 3).map((x) => x.material + ' 缺 ' + x.netGap).join(';')}。`);
1014
+ },
1015
+
1016
+ suggest_routing(p) {
1017
+ const pr = getProduct(p.product);
1018
+ if (!pr) return errReply('suggest_routing', p, `未找到产品 ${p.product}`);
1019
+ const limit = Math.min(30, Math.max(1, p.limit || 15));
1020
+ const base = PRODUCTS.filter((x) => x.code !== pr.code && x.flowType === pr.flowType);
1021
+ const drafts = (pr.routing || []).slice(0, limit).map((r, i) => ({
1022
+ sequence: r.sequence, name: r.name, workCenter: r.workCenter,
1023
+ unitMinutes: r.minutes, setupMinutes: r.setupMinutes,
1024
+ confidence: +(0.85 - i * 0.05).toFixed(2),
1025
+ basis: `参考同类产品 ${base.map((x) => x.code).join('、') || '本厂工序字典'}`,
1026
+ }));
1027
+ return reply('suggest_routing', p, `${pr.code} 工艺路线草稿`, {
1028
+ product: pr.code, productName: pr.name,
1029
+ existingProcessCount: (pr.routing || []).length,
1030
+ matchedCategories: [pr.category],
1031
+ draftProcesses: drafts,
1032
+ dictionarySize: PRODUCTS.reduce((s, x) => s + (x.routing || []).length, 0),
1033
+ note: '这是草稿,需人工在软件「BOM → 工艺路线」核对保存才生效;已有工艺路线时仅作对照',
1034
+ }, `已按 product=${pr.code} 生成 ${drafts.length} 道候选工序(草稿)。`);
1035
+ },
1036
+
1037
+ check_change_impact(p) {
1038
+ const pr = getProduct(p.product);
1039
+ if (!pr) return errReply('check_change_impact', p, `未找到产品 ${p.product}`);
1040
+ if (!Array.isArray(p.changes) || !p.changes.length) return errReply('check_change_impact', p, 'changes 必填且至少一条');
1041
+ const active = WORK_ORDERS.filter((w) => w.product === pr.code && (w.status === '进行中' || w.status === '待排产'));
1042
+ const remaining = active.reduce((s, w) => s + Math.max(w.qty - (w.actualQty || 0), 0), 0);
1043
+ const oldBom = bomExplode(pr.code, 1, 10);
1044
+ const oldCost = +oldBom.reduce((s, r) => s + r.grossQty * ((getMaterial(r.material) || {}).price || 0), 0).toFixed(2);
1045
+ const changeRows = p.changes.map((c) => {
1046
+ const before = oldBom.find((b) => b.material === c.material);
1047
+ return {
1048
+ op: c.op, material: c.material,
1049
+ before: before ? { qtyPerUnit: before.qtyPerUnit, lossRate: before.lossRate } : null,
1050
+ after: { qtyPerUnit: c.quantity != null ? c.quantity : (before ? before.qtyPerUnit : null), lossRate: c.lossRate != null ? c.lossRate : (before ? before.lossRate : 0) },
1051
+ alternates: c.alternates || [],
1052
+ };
1053
+ });
1054
+ const deltaQty = changeRows.reduce((s, c) => s + (((c.after.qtyPerUnit || 0) - (c.before ? c.before.qtyPerUnit : 0))), 0);
1055
+ const newCost = +(oldCost + deltaQty * (getMaterial(changeRows[0].material) || {}).price * (1 + (changeRows[0].after.lossRate || 0))).toFixed(2);
1056
+ const picked = active.filter((w) => (PROCESS_PROGRESS[w.code] || []).some((x) => x.actualQty > 0));
1057
+ return reply('check_change_impact', p, `${pr.code} 变更影响`, {
1058
+ product: pr.code, productName: pr.name,
1059
+ activeWorkOrders: active.length, remainingQty: remaining,
1060
+ pickedWorkOrders: picked.length,
1061
+ changes: changeRows,
1062
+ 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) })),
1063
+ cost: { before: oldCost, after: newCost, delta: +(newCost - oldCost).toFixed(2), unit: '元/件', basis: '仅材料成本,不含人工与制造费用' },
1064
+ purchaseImpact: { inTransitOrders: PURCHASE_ORDERS.filter((o) => changeRows.some((c) => c.material === o.material)).map((o) => ({ code: o.code, action: '复核数量' })) },
1065
+ summary: `影响 ${active.length} 张在产工单、剩余 ${remaining} 件;单件材料成本 ${oldCost} → ${newCost} 元`,
1066
+ warnings: picked.length ? [`${picked.length} 张工单已领料,按旧 BOM 执行,需补料/退料`] : [],
1067
+ }, `已按 product=${pr.code}、${p.changes.length} 项变更评估:影响 ${active.length} 张工单,成本 ${oldCost} → ${newCost} 元/件。`);
1068
+ },
1069
+
1070
+ daily_brief(p) {
1071
+ const horizon = Math.min(60, Math.max(1, p.horizon_days || 7));
1072
+ const todayPlan = WORK_ORDERS.filter((w) => w.status === '进行中' || (w.planStart && daysBetween(w.planStart, TODAY) >= 0 && w.status === '待排产'));
1073
+ const overdue = WORK_ORDERS.filter((w) => w.status !== '已完成' && w.status !== '已取消' && w.planEnd && daysBetween(w.planEnd, TODAY) > 0);
1074
+ const arrivals = PURCHASE_ORDERS.filter((o) => daysBetween(TODAY, o.eta) <= horizon && o.receivedQty < o.qty);
1075
+ const todayIncidents = INCIDENTS.filter((i) => i.date === TODAY);
1076
+ const shortages = [];
1077
+ for (const w of WORK_ORDERS.filter((x) => x.status === '进行中' || x.status === '待排产')) {
1078
+ const rd = readinessOf(w);
1079
+ 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 });
1080
+ }
1081
+ 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);
1082
+ const md = [
1083
+ `# 生产日报 ${TODAY}`,
1084
+ '',
1085
+ `今日计划 ${todayPlan.length} 张,在产 ${WORK_ORDERS.filter((w) => w.status === '进行中').length} 张,超期 ${overdue.length} 张,缺料 ${shortages.length} 项。`,
1086
+ '',
1087
+ '## 今日计划',
1088
+ ...todayPlan.map((w) => `- ${w.code} ${w.product} ×${w.qty} 剩余 ${Math.max(w.qty - (w.actualQty || 0), 0)} ${w.line || '待排产'}`),
1089
+ '',
1090
+ '## 超期工单',
1091
+ ...overdue.map((w) => `- ${w.code} 晚 ${daysBetween(w.planEnd, TODAY)} 天`),
1092
+ '',
1093
+ '## 需拍板',
1094
+ `- 催料:${inTransitShort.map((s) => s.material).join('、') || '无'}`,
1095
+ `- 今日异常 ${todayIncidents.length} 条:${todayIncidents.map((i) => i.type).join('、') || '无'}`,
1096
+ ].join('\n');
1097
+ return reply('daily_brief', p, `日报 ${TODAY}`, {
1098
+ date: TODAY, horizonDays: horizon,
1099
+ todayPlanCount: todayPlan.length,
1100
+ inProgress: WORK_ORDERS.filter((w) => w.status === '进行中').length,
1101
+ overdueCount: overdue.length,
1102
+ arrivalsCount: arrivals.length,
1103
+ shortageCount: shortages.length,
1104
+ incidentCount: todayIncidents.length,
1105
+ changesThisWeek: 2,
1106
+ markdown: md,
1107
+ }, `已按 horizon_days=${horizon} 生成日报:今日 ${todayPlan.length} 张、超期 ${overdue.length} 张、缺料 ${shortages.length} 项。`);
1108
+ },
1109
+
1110
+ shortage_forecast(p) {
1111
+ const horizon = Math.min(180, Math.max(1, p.horizon_days || 14));
1112
+ const lead = Math.max(1, p.lead_time_days || 3);
1113
+ const limit = Math.min(20, Math.max(1, p.limit || 20));
1114
+ let targets = WORK_ORDERS.filter((w) => w.status === '进行中' || w.status === '待排产');
1115
+ if (p.work_order) {
1116
+ const wo = getWO(p.work_order);
1117
+ if (!wo) return errReply('shortage_forecast', p, `未找到工单 ${p.work_order}`);
1118
+ targets = [wo];
1119
+ }
1120
+ const stopLines = [];
1121
+ const chase = [];
1122
+ for (const w of targets) {
1123
+ const rd = readinessOf(w);
1124
+ const realShort = rd.materials.filter((m) => m.gap > 0 && m.inTransit < m.gap);
1125
+ if (realShort.length) {
1126
+ const stopDate = w.planStart || TODAY;
1127
+ if (daysBetween(TODAY, stopDate) <= horizon) {
1128
+ stopLines.push({
1129
+ date: stopDate, work_order: w.code,
1130
+ shortages: realShort.map((m) => ({ material: m.material, name: m.name, gap: m.gap, unit: m.unit })),
1131
+ inTransitCanSave: false,
1132
+ });
1133
+ for (const m of realShort) {
1134
+ const po = PURCHASE_ORDERS.find((o) => o.material === m.material && o.receivedQty < o.qty);
1135
+ chase.push({
1136
+ material: m.material, name: m.name,
1137
+ purchaseOrder: po ? po.code : '需新下单',
1138
+ supplier: po ? po.supplier : null,
1139
+ mustArriveBy: stopDate,
1140
+ daysAhead: daysBetween(TODAY, stopDate),
1141
+ leadTimeDays: lead,
1142
+ earliestArrival: dayOffset(lead),
1143
+ shortByDays: Math.max(0, daysBetween(dayOffset(lead), stopDate)),
1144
+ });
1145
+ }
1146
+ }
1147
+ }
1148
+ }
1149
+ return reply('shortage_forecast', p, `${stopLines.length} 天停工风险`, {
1150
+ horizonDays: horizon, leadTimeDays: lead,
1151
+ stopLineCount: stopLines.length,
1152
+ stopLines: stopLines.slice(0, limit),
1153
+ chaseList: chase.slice(0, limit),
1154
+ newOrders: chase.filter((c) => !c.purchaseOrder || c.purchaseOrder === '需新下单').slice(0, limit),
1155
+ maturityNote: '只算料,不算人/设备;演示数据成熟度中等',
1156
+ note: '先卡料:' + (chase.length ? chase.slice(0, 3).map((c) => `${c.name} 补 ${c.material}`).join(';') : '无'),
1157
+ }, `已按 horizon_days=${horizon}${p.work_order ? '、work_order=' + p.work_order : ''} 预测:${stopLines.length} 天停工风险,需催 ${chase.length} 项。`);
1158
+ },
1159
+
1160
+ // 阶段4:自适应推荐(演示模式不判定真实门禁,因此只保留标准排程)
1161
+ recommend_schedule_strategy(p) {
1162
+ const pending = WORK_ORDERS.filter((w) => w.status === '待排产');
1163
+ if (!pending.length) {
1164
+ return reply('recommend_schedule_strategy', p, '没有待排产工单,维持标准排程', {
1165
+ woCount: 0,
1166
+ recommendation: { engine: 'baseline', strategy: 'current', title: '标准排程(贪心基线)',
1167
+ action: 'keep', confidence: 'low', score: 0, deltaScore: 0,
1168
+ reasons: ['没有待排产工单'], tradeoffs: [], risks: [], gatesPassed: false,
1169
+ note: '演示模式不自动落库。' },
1170
+ features: {}, history: { records: [], summary: [] },
1171
+ });
1172
+ }
1173
+ const base = sortPending(pending, 'current');
1174
+ const evaluate = (list) => computeComparePlans(pending, [{ id: 'x', label: '', ordered: list }]).strategies[0];
1175
+ const baseEval = evaluate(base);
1176
+ const candidates = ['edd', 'changeover_cluster', 'spt'].map((id) => ({
1177
+ id, score: evaluate(sortPending(pending, id)).score,
1178
+ }));
1179
+ const best = candidates.reduce((a, b) => (b.score < a.score ? b : a), candidates[0]);
1180
+ const lineLoad = {};
1181
+ for (const w of pending) {
1182
+ const ln = w.line || LINES[0];
1183
+ lineLoad[ln] = (lineLoad[ln] || 0) + orderHours(w);
1184
+ }
1185
+ const loads = Object.values(lineLoad);
1186
+ const avg = loads.length ? loads.reduce((a, b) => a + b, 0) / loads.length : 0;
1187
+ const max = loads.length ? Math.max(...loads) : 0;
1188
+ const withDue = pending.filter((w) => w.dueDate);
1189
+ const urgent = withDue.filter((w) => {
1190
+ const d = daysBetween(w.dueDate, TODAY);
1191
+ return d >= 0 && d <= 7;
1192
+ }).length;
1193
+ const features = {
1194
+ woCount: pending.length,
1195
+ dueCoverage: pending.length ? +((withDue.length / pending.length) * 100).toFixed(1) / 100 : 0,
1196
+ urgent7Ratio: withDue.length ? +((urgent / withDue.length) * 100).toFixed(1) / 100 : 0,
1197
+ changeoverPairs: Math.max(0, new Set(pending.map((w) => w.product)).size - 1),
1198
+ bottleneckIndex: avg ? +(max / avg).toFixed(1) : 0,
1199
+ };
1200
+ const reasons = ['演示模式无法判定真实应用硬门禁,只推荐标准排程。'];
1201
+ if (features.urgent7Ratio >= 0.4) reasons.push('示例工单存在交期压力,可在桌面版看 EDD 比选。');
1202
+ if (features.bottleneckIndex >= 1.5) reasons.push('示例产线负荷不均,可在桌面版看瓶颈优先。');
1203
+ return reply('recommend_schedule_strategy', p, '推荐标准排程(演示模式)', {
1204
+ woCount: pending.length,
1205
+ recommendation: {
1206
+ engine: 'baseline', strategy: 'current', title: '标准排程(贪心基线)',
1207
+ action: 'keep', confidence: 'medium', score: baseEval.score,
1208
+ baselineScore: baseEval.score, deltaScore: 0,
1209
+ reasons,
1210
+ tradeoffs: ['不强求极限 KPI,先保证口径稳定。'],
1211
+ risks: ['演示数据不判定真实硬门禁与跨周期审计,不能作为应用依据。'],
1212
+ evidence: { features, shadowRows: [], bestStrategy: best.id,
1213
+ strategyGain: +(baseEval.score - best.score).toFixed(1), historyConsecutiveStable: 0 },
1214
+ gatesPassed: false,
1215
+ note: '演示模式只读;不自动切换默认、不自动落库。',
1216
+ },
1217
+ features,
1218
+ history: { records: [], summary: [], note: '演示模式不持久化审计。' },
1219
+ unlock: { gates: [], gatesPassed: false, advancedPreviewScore: 60, advancedApplyScore: 80 },
1220
+ scoreFormula: '综合分 = 逾期单数×100 + 逾期总天数×5 + 完工跨度天×10 + 换型小时×2 + 负荷σ×3 + 排不上单数×150(越低越好)',
1221
+ }, `已按示例工单生成推荐:维持标准排程;排序策略里综合分最低的是 ${best.id}(${best.score})。`);
1222
+ },
1223
+
1224
+ // 阶段4:审计写入(演示模式模拟返回,不持久化)
1225
+ record_schedule_decision(p) {
1226
+ return reply('record_schedule_decision', p, '演示模式不持久化审计', {
1227
+ id: 'demo-audit-not-persisted', recorded: false, simulated: true,
1228
+ kind: p.kind || 'decision', engine: p.engine || 'baseline', strategy: p.strategy || 'current',
1229
+ decision: p.decision || 'observe', stable: !!p.stable,
1230
+ note: '演示模式只返回结构化示例;桌面版会写入本机 schedule_audit。',
1231
+ });
1232
+ },
1233
+
1234
+ // 阶段4:审计查询(演示模式返回空集)
1235
+ query_schedule_audit(p) {
1236
+ return reply('query_schedule_audit', p, '演示模式暂无审计记录', {
1237
+ count: 0, records: [], summary: [],
1238
+ note: '演示模式不持久化;桌面版按 created_at 倒序返回,并统计连续稳定周期。',
1239
+ });
1240
+ },
1241
+ };
1242
+
1243
+ // 引擎入口
1244
+ function callTool(name, params) {
1245
+ const fn = TOOLS[name];
1246
+ if (!fn) {
1247
+ return {
1248
+ content: [{ type: 'text', text: MODE_NOTICE + `\n\n【轻排 · 演示模式】未知工具 ${name}。` }],
1249
+ isError: true,
1250
+ };
1251
+ }
1252
+ try {
1253
+ return fn(params || {});
1254
+ } catch (e) {
1255
+ return {
1256
+ content: [{ type: 'text', text: MODE_NOTICE + `\n\n【轻排 · 演示模式】工具 ${name} 执行出错:${e.message}\n${e.stack || ''}` }],
1257
+ isError: true,
1258
+ };
1259
+ }
1260
+ }
1261
+
1262
+ const TOOL_NAMES = Object.keys(TOOLS);
1263
+
1264
+ module.exports = { callTool, TOOL_NAMES, TOOLS, MODE_NOTICE };