weaver-work-cli 0.1.60 → 0.1.62

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 (139) hide show
  1. package/dist/chunks/{archive-4SQAVTIB.js → archive-S2VKZWQ3.js} +2 -2
  2. package/dist/chunks/{archive-oa-W2UEJ67L.js → archive-oa-HEDSIUUY.js} +2 -2
  3. package/dist/chunks/{asset-EGZEABBI.js → asset-HYH4W357.js} +2 -2
  4. package/dist/chunks/{asset-idle-EBUZBB6M.js → asset-idle-N7REBNGL.js} +2 -2
  5. package/dist/chunks/{attachment-content-I6WHKGR2.js → attachment-content-VYYA75FR.js} +3 -3
  6. package/dist/chunks/{blog-2YKMWOWI.js → blog-SLMZZICV.js} +2 -2
  7. package/dist/chunks/{caizhilian-5NM4X5HG.js → caizhilian-RV43KKBT.js} +4 -4
  8. package/dist/chunks/{calendar-H4QTJCUY.js → calendar-DMVZ4OLY.js} +2 -2
  9. package/dist/chunks/{chunk-VLL6JOB4.js → chunk-6XSSAUNW.js} +4 -4
  10. package/dist/chunks/{chunk-VQWPQTEY.js → chunk-BIA2NKUG.js} +4 -4
  11. package/dist/chunks/{chunk-VMCCRWFO.js → chunk-BQYX2UX5.js} +2 -2
  12. package/dist/chunks/{chunk-XF7S6FQW.js → chunk-DTCQFTHW.js} +1 -1
  13. package/dist/chunks/{chunk-CPG6NLN4.js → chunk-E5YD5JWR.js} +1 -1
  14. package/dist/chunks/{chunk-PH7N4UFT.js → chunk-EGANE35F.js} +1 -1
  15. package/dist/chunks/{chunk-Z4IPY5GV.js → chunk-H6YOMI3U.js} +2 -2
  16. package/dist/chunks/{chunk-HHH4K3YY.js → chunk-ILALC2N6.js} +1 -1
  17. package/dist/chunks/{chunk-WINR2Q6K.js → chunk-KXJA42EA.js} +86 -19
  18. package/dist/chunks/{chunk-CQ4OVCKG.js → chunk-KY3R42RS.js} +2 -2
  19. package/dist/chunks/{chunk-WVH5ESDA.js → chunk-NRYDJN4J.js} +1 -1
  20. package/dist/chunks/{chunk-TGM7BWEH.js → chunk-P6TXQK75.js} +2 -2
  21. package/dist/chunks/{chunk-6YWHRXEQ.js → chunk-QBDXJS2W.js} +119 -9
  22. package/dist/chunks/{chunk-2IGZUMNG.js → chunk-SHX7XBYR.js} +180 -18
  23. package/dist/chunks/{chunk-P7RXQDCA.js → chunk-T2KVJFWJ.js} +4 -4
  24. package/dist/chunks/{chunk-FMNCSYIG.js → chunk-TEZHIB6T.js} +2 -2
  25. package/dist/chunks/{chunk-HMIIVM2L.js → chunk-UBGWIXU3.js} +97 -45
  26. package/dist/chunks/{chunk-5N222HK6.js → chunk-UBRWONP4.js} +2 -2
  27. package/dist/chunks/{chunk-7U5YHCW7.js → chunk-UQFPF4EX.js} +2 -2
  28. package/dist/chunks/{chunk-4GG72JAT.js → chunk-V2LASYKO.js} +2 -2
  29. package/dist/chunks/{chunk-BDBTZVYA.js → chunk-VBFBMM7G.js} +55 -55
  30. package/dist/chunks/{chunk-YHSOCGKO.js → chunk-VNYOUAWV.js} +11 -11
  31. package/dist/chunks/{chunk-SFM3M2L3.js → chunk-WIWDVETN.js} +19 -3
  32. package/dist/chunks/{chunk-44KJ7WFA.js → chunk-XT77MP54.js} +2 -2
  33. package/dist/chunks/{chunk-JFKMPRZB.js → chunk-YI2YMW5N.js} +50 -3
  34. package/dist/chunks/{conflict-QMDLS2EW.js → conflict-GFJRS6I7.js} +2 -2
  35. package/dist/chunks/{contract-LLRKMLQQ.js → contract-U3ZGNRWB.js} +2 -2
  36. package/dist/chunks/{cowork-2RDFBZWB.js → cowork-EX7PKIDK.js} +2 -2
  37. package/dist/chunks/{create-flow-5ODJ7WJO.js → create-flow-EJZD434E.js} +6 -6
  38. package/dist/chunks/{data-LVDFIRNG.js → data-FOODGAMF.js} +278 -121
  39. package/dist/chunks/{ebuilder-form-7WA6X6ZI.js → ebuilder-form-I2EOKODG.js} +3 -3
  40. package/dist/chunks/{ehr-52GBKNJR.js → ehr-TE4RFNID.js} +2 -2
  41. package/dist/chunks/{entry-mode-73BJML22.js → entry-mode-ZOLSXEGX.js} +9 -5
  42. package/dist/chunks/{env-OHFS76HV.js → env-TID5NFR6.js} +2 -2
  43. package/dist/chunks/{esb-HJSXCEOM.js → esb-7L6MHYLB.js} +4 -4
  44. package/dist/chunks/{factory-FRTA2LP4.js → factory-OG7BPMH5.js} +1 -1
  45. package/dist/chunks/{fna-OBACRT3J.js → fna-6V2ENR3Y.js} +2 -2
  46. package/dist/chunks/{group-chat-KBFRPCR2.js → group-chat-5DKPWIHL.js} +3 -3
  47. package/dist/chunks/{host-TTSGY5NZ.js → host-3DLYA54R.js} +3 -3
  48. package/dist/chunks/{host-KJT3G5D2.js → host-GOJHHTPY.js} +3 -3
  49. package/dist/chunks/{host-KOWUMNAY.js → host-OGBHL75G.js} +3 -3
  50. package/dist/chunks/{host-MFXRA2MY.js → host-ONZC6AE7.js} +3 -3
  51. package/dist/chunks/{host-W4JCNRFS.js → host-TJ5VVHM7.js} +3 -3
  52. package/dist/chunks/{host-2BKMPWDH.js → host-VTPAWDZV.js} +3 -3
  53. package/dist/chunks/{hrm-AK3WGBMN.js → hrm-2N7NFQDZ.js} +3 -3
  54. package/dist/chunks/{im-JZSBPO4Z.js → im-XCH47ZBN.js} +3 -3
  55. package/dist/chunks/{invoice-6XDMPCWB.js → invoice-5KJ7T774.js} +198 -331
  56. package/dist/chunks/{jiuchuanhui-K4EQU6GK.js → jiuchuanhui-PL6DRPBM.js} +2 -2
  57. package/dist/chunks/{lazy-dispatch-GCA6HDOB.js → lazy-dispatch-UATEN7H7.js} +5 -5
  58. package/dist/chunks/{mail-IKVCQCVZ.js → mail-Q7Z4CQ4D.js} +2 -2
  59. package/dist/chunks/{meeting-ARHVWK7G.js → meeting-5E3BNARL.js} +13 -13
  60. package/dist/chunks/{minute-doc-547KSYKR.js → minute-doc-NXRE5C77.js} +4 -4
  61. package/dist/chunks/{okr-KV43FPPX.js → okr-3O3XNYOK.js} +2 -2
  62. package/dist/chunks/{operations-6NXJ7RTE.js → operations-EZWG72FH.js} +4 -4
  63. package/dist/chunks/performance-Y7CPNSOR.js +1295 -0
  64. package/dist/chunks/{plan-WOYR4WEG.js → plan-BLGPZF5M.js} +2 -2
  65. package/dist/chunks/{project-CQJKBUIL.js → project-6MZMLJMP.js} +2 -2
  66. package/dist/chunks/{reception-MPBU3JXC.js → reception-F2VT2X52.js} +2 -2
  67. package/dist/chunks/{recruit-stage-USTTRHOX.js → recruit-stage-4ETIBMIW.js} +2 -2
  68. package/dist/chunks/{registry-GURQG4ZV.js → registry-3FYSWV3U.js} +3 -3
  69. package/dist/chunks/{registry-SS5J2FZQ.js → registry-7RS74TCK.js} +4 -4
  70. package/dist/chunks/{registry-H5HQ5QNH.js → registry-I4DVPDMU.js} +11 -11
  71. package/dist/chunks/{room-recommend-3UBROMZE.js → room-recommend-GWCVKCXW.js} +4 -4
  72. package/dist/chunks/{schedule-FTUQML6O.js → schedule-6AN63MJQ.js} +4 -4
  73. package/dist/chunks/{smart-extract-APX2PNIN.js → smart-extract-SR4SJJKN.js} +3 -3
  74. package/dist/chunks/{workflow-WMPW3WSB.js → workflow-KF7FA2UQ.js} +7 -7
  75. package/dist/cmd/refs/index.js +124 -4
  76. package/dist/core/output.js +199 -26
  77. package/dist/core/refs.js +36 -0
  78. package/dist/index.js +38 -33
  79. package/dist/internal/e10/auth/xiaoe.js +25 -3
  80. package/dist/shortcuts/caizhilian/operations/files.js +86 -15
  81. package/dist/shortcuts/data/index.js +12 -2
  82. package/dist/shortcuts/data/manifest.js +4 -2
  83. package/dist/shortcuts/data/operations/attribution.js +229 -0
  84. package/dist/shortcuts/data/operations/ds.js +87 -90
  85. package/dist/shortcuts/data/operations/index.js +3 -1
  86. package/dist/shortcuts/index.js +5 -0
  87. package/dist/shortcuts/invoice/manifest.js +30 -62
  88. package/dist/shortcuts/invoice/operations/registry.js +2 -2
  89. package/dist/shortcuts/invoice/operations/reim-customer.js +111 -0
  90. package/dist/shortcuts/invoice/operations/shared.js +0 -204
  91. package/dist/shortcuts/meeting/operations/eb/create-flow.js +84 -16
  92. package/dist/shortcuts/meeting/operations/eb/entry-mode.js +61 -7
  93. package/dist/shortcuts/performance/continuation.js +74 -0
  94. package/dist/shortcuts/performance/errors.js +65 -0
  95. package/dist/shortcuts/performance/host.js +105 -0
  96. package/dist/shortcuts/performance/index.js +109 -0
  97. package/dist/shortcuts/performance/manifest.js +30 -0
  98. package/dist/shortcuts/performance/operations/hrm-resolve.js +114 -0
  99. package/dist/shortcuts/performance/operations/registry.js +44 -0
  100. package/dist/shortcuts/performance/operations/scheme-detail.js +70 -0
  101. package/dist/shortcuts/performance/operations/scheme-draft.js +116 -0
  102. package/dist/shortcuts/performance/operations/scheme-publish.js +158 -0
  103. package/dist/shortcuts/performance/operations/types.js +32 -0
  104. package/dist/shortcuts/performance/scheme-validate.js +307 -0
  105. package/dist/shortcuts/performance/shared.js +158 -0
  106. package/docs/agent-invoice.md +1 -1
  107. package/docs/agent-io-channel-design.md +67 -3
  108. package/docs/data.md +2 -1
  109. package/docs/invoice.md +0 -2
  110. package/package.json +1 -1
  111. package/scripts/xiaoe_env.py +6 -1
  112. package/skill-template/business-info.json +19 -0
  113. package/skill-template/domains/performance.md +18 -0
  114. package/skill-template/domains/yepiaotong.md +0 -1
  115. package/skills/weaver-e10-caizhilian/SKILL.md +1 -1
  116. package/skills/weaver-e10-data/references/datasource.md +2 -1
  117. package/skills/weaver-e10-meeting/SKILL.md +5 -3
  118. package/skills/weaver-e10-performance/SKILL.md +202 -0
  119. package/skills/weaver-e10-performance/agents/openai.yaml +74 -0
  120. package/skills/weaver-e10-performance/references/default-assembly.md +108 -0
  121. package/skills/weaver-e10-performance/references/entity-resolution.md +69 -0
  122. package/skills/weaver-e10-performance/references/enums-and-normalization.md +80 -0
  123. package/skills/weaver-e10-performance/references/examples.md +146 -0
  124. package/skills/weaver-e10-performance/references/extraction-guide.md +144 -0
  125. package/skills/weaver-e10-performance/references/scheme-edit-req-fields.md +185 -0
  126. package/skills/weaver-e10-performance/references/scheme-setting-page.md +62 -0
  127. package/skills/weaver-e10-performance/scripts/parse_appraisal_doc.py +483 -0
  128. package/skills/weaver-e10-shared/references/json-output-contract.md +5 -0
  129. package/skills/weaver-e10-yepiaotong/SKILL.md +16 -9
  130. package/skills/weaver-e10-yepiaotong/references/invoice-reim-relation.md +9 -7
  131. package/skills/weaver-e10-yepiaotong/references/invoice-reim.md +15 -11
  132. package/skills/weaver-e10-yepiaotong/references/reim-api-reference.md +29 -25
  133. package/skills/weaver-e10-yepiaotong/references/reim-customer-search.md +89 -0
  134. package/skills/weaver-e10-yepiaotong/references/reim-examples.md +35 -37
  135. package/skills/weaver-e10-yepiaotong/references/reim-form-fill-rules.md +66 -63
  136. package/skills/weaver-e10-yepiaotong/references/reim-workflow.md +50 -71
  137. package/skills/weaver-e10-yepiaotong/references/source-manifest.json +34 -95
  138. package/dist/shortcuts/invoice/operations/browse-field.js +0 -17
  139. package/skills/weaver-e10-yepiaotong/references/invoice-browse-field-data.md +0 -204
@@ -0,0 +1,158 @@
1
+ import { pfConfirmationError, pfFail, pfValidationError } from '../errors.js';
2
+ import { assertWeaResult, normalizeId, schemeEditReqSchema } from '../shared.js';
3
+ import { assertNoErrors, describeTargets, schemeFingerprint, summarizeScheme, validateScheme } from '../scheme-validate.js';
4
+ import { pfSuccess, schemaOf } from './types.js';
5
+ const APPLY_PATH = '/api/workrelate/performance/scheme/applyScheme';
6
+ const DETAIL_PATH = '/api/workrelate/performance/scheme/detail';
7
+ const REQ_FIELDS = [...Object.keys(schemeEditReqSchema)];
8
+ function pickRequestBody(args) {
9
+ const body = {};
10
+ for (const field of REQ_FIELDS) {
11
+ if (args[field] !== undefined)
12
+ body[field] = args[field];
13
+ }
14
+ return body;
15
+ }
16
+ function requireId(args) {
17
+ if (args.id === undefined || args.id === null || args.id === '') {
18
+ throw pfValidationError('id_missing', '发布已有方案必须传 id(不带 id 会直接创建并发布新方案)');
19
+ }
20
+ return normalizeId(args.id, 'id');
21
+ }
22
+ /** detail 回读中属于 SchemeEditReq 的字段(发布参数基于 detail 回读组装)。 */
23
+ const DETAIL_REQ_FIELDS = REQ_FIELDS;
24
+ function readBackScheme(detailData) {
25
+ const body = {};
26
+ for (const field of DETAIL_REQ_FIELDS) {
27
+ if (detailData[field] !== undefined && detailData[field] !== null)
28
+ body[field] = detailData[field];
29
+ }
30
+ // id / detailId 必须保留(detailId 丢失 = hr_kpi_details 重复插入,detail 永久 500,无法自愈)。
31
+ body.id = normalizeId(detailData.id, 'detail.id');
32
+ body.detailId = normalizeId(detailData.detailId, 'detail.detailId');
33
+ return body;
34
+ }
35
+ /**
36
+ * publish.prepare:发布前组装与确认(不落库)。
37
+ * 两种入参形态:
38
+ * A. 只传 id —— 自动 detail 回读组装完整发布参数(推荐,detailId 不会丢);
39
+ * B. 传完整 SchemeEditReq(可覆盖个别字段)—— 以入参为准,但 id/detailId 仍强制回读对齐。
40
+ * 返回发布摘要(含方案当前状态、发布语义提示)+ continuation。
41
+ */
42
+ async function prepare(args, env) {
43
+ const id = requireId(args);
44
+ const detailResponse = await env.host.request({
45
+ path: `${DETAIL_PATH}/${encodeURIComponent(String(id))}`,
46
+ method: 'GET',
47
+ operation: 'performance.scheme.publish.prepare',
48
+ });
49
+ const detailData = assertWeaResult(detailResponse, '读取方案详情');
50
+ if (!detailData || typeof detailData !== 'object') {
51
+ throw pfFail('读取方案详情:返回 data 不是对象', { id });
52
+ }
53
+ if (detailData.detailId === undefined || detailData.detailId === null || detailData.detailId === '') {
54
+ // 已知故障特征:发布不带 detailId 会导致 hr_kpi_details 重复插入、detail 永久 500。
55
+ throw pfValidationError('detail_id_missing', '方案详情回读不到 detailId——为防重复明细事故,禁止发布;请在方案编辑页核对该方案', { id });
56
+ }
57
+ // 以 detail 回读为底,叠加调用方显式传入的覆盖字段(不含 confirm/continuation)。
58
+ const overrides = pickRequestBody(args);
59
+ delete overrides.confirm;
60
+ const detailId = normalizeId(detailData.detailId, 'detail.detailId');
61
+ const body = { ...readBackScheme(detailData), ...overrides, id: String(id), detailId };
62
+ const issues = assertNoErrors(validateScheme(body));
63
+ const summary = summarizeScheme(body);
64
+ const fingerprint = schemeFingerprint(body);
65
+ const continuation = await env.continuation.issue({
66
+ operation: 'performance.scheme.publish.apply',
67
+ fingerprint,
68
+ });
69
+ const preview = {
70
+ action: '发布方案(POST /scheme/applyScheme)——正式动作:触发版本管理、ESB 动作流、提醒,方案立即生效',
71
+ currentStatus: detailData.status ?? null,
72
+ scheme: summary,
73
+ targets: describeTargets(body),
74
+ issues: issues.map((issue) => `[${issue.level === 'warn' ? 'WARN' : 'ERROR'}] ${issue.message}`),
75
+ fatalNote: 'id 与 detailId 已从 detail 回读并强制带上(detailId 丢失会导致方案数据损坏,禁止剔除)',
76
+ };
77
+ return pfSuccess('performance.scheme.publish.prepare', { continuation, fingerprint, preview }, {
78
+ continuation,
79
+ fingerprint,
80
+ confirmHint: '发布必须用户明确同意。展示 preview(含发布语义提示)确认后,携带 confirm=true 与 continuation 调用 performance.scheme.publish.apply',
81
+ });
82
+ }
83
+ /** publish.apply:确认后发布,返回方案 id。 */
84
+ async function apply(args, env) {
85
+ if (args.confirm !== true) {
86
+ throw pfConfirmationError('performance.scheme.publish.apply', { hint: '发布是正式动作,必须用户明确同意' });
87
+ }
88
+ if (typeof args.continuation !== 'string' || !args.continuation) {
89
+ throw pfValidationError('continuation_missing', '缺少 continuation(先运行 performance.scheme.publish.prepare)');
90
+ }
91
+ const verified = await env.continuation.verify(args.continuation, 'performance.scheme.publish.apply');
92
+ const id = requireId(args);
93
+ const detailResponse = await env.host.request({
94
+ path: `${DETAIL_PATH}/${encodeURIComponent(String(id))}`,
95
+ method: 'GET',
96
+ operation: 'performance.scheme.publish.apply',
97
+ });
98
+ const detailData = assertWeaResult(detailResponse, '读取方案详情');
99
+ if (detailData?.detailId === undefined || detailData?.detailId === null || detailData?.detailId === '') {
100
+ throw pfValidationError('detail_id_missing', '方案详情回读不到 detailId——为防重复明细事故,禁止发布', { id });
101
+ }
102
+ const overrides = pickRequestBody(args);
103
+ delete overrides.confirm;
104
+ const detailId = normalizeId(detailData.detailId, 'detail.detailId');
105
+ const body = { ...readBackScheme(detailData), ...overrides, id: String(id), detailId };
106
+ assertNoErrors(validateScheme(body));
107
+ const fingerprint = schemeFingerprint(body);
108
+ if (String(verified.fingerprint) !== fingerprint) {
109
+ throw pfValidationError('fingerprint_mismatch', '提交内容与确认摘要不一致(方案数据或参数在 prepare 之后发生变化),请重新 prepare 并再次确认', {
110
+ expected: verified.fingerprint,
111
+ actual: fingerprint,
112
+ });
113
+ }
114
+ const response = await env.host.request({
115
+ path: APPLY_PATH,
116
+ body,
117
+ operation: 'performance.scheme.publish.apply',
118
+ });
119
+ const schemeId = assertWeaResult(response, '发布方案');
120
+ return pfSuccess('performance.scheme.publish.apply', {
121
+ schemeId,
122
+ status: 'published',
123
+ next: '用 performance.scheme.detail 核对 status=finished / applyStatus;方案设置页可在 E10 前端继续完善',
124
+ });
125
+ }
126
+ export const schemePublishOperations = [
127
+ {
128
+ name: 'performance.scheme.publish.prepare',
129
+ resource: 'performance.scheme',
130
+ method: 'prepare',
131
+ action: 'scheme.publish',
132
+ summary: '发布前自动 detail 回读组装完整参数(强制带 id+detailId)并生成确认摘要;不落库',
133
+ capability: 'performance.scheme.publish',
134
+ risk: 'write',
135
+ requiresConfirmation: true,
136
+ inputSchema: schemaOf({
137
+ ...schemeEditReqSchema,
138
+ // 发布推荐只传 id(其余参数自动回读);显式传入的字段会覆盖回读值。
139
+ }, { required: ['id'], description: '推荐只传 id:参数自动从 detail 回读组装(detailId 防丢);也可显式覆盖个别字段' }),
140
+ handler: prepare,
141
+ },
142
+ {
143
+ name: 'performance.scheme.publish.apply',
144
+ resource: 'performance.scheme',
145
+ method: 'apply',
146
+ action: 'scheme.publish',
147
+ summary: '确认后发布方案(POST /scheme/applyScheme;正式动作,触发版本/ESB/提醒)',
148
+ capability: 'performance.scheme.publish',
149
+ risk: 'write',
150
+ requiresConfirmation: true,
151
+ inputSchema: schemaOf({
152
+ ...schemeEditReqSchema,
153
+ confirm: { type: 'boolean', description: '必须 true(用户已明确同意发布)' },
154
+ continuation: { type: 'string', description: 'prepare 返回的 continuation' },
155
+ }, { required: ['id', 'confirm', 'continuation'] }),
156
+ handler: apply,
157
+ },
158
+ ];
@@ -0,0 +1,32 @@
1
+ import { pfValidationError } from '../errors.js';
2
+ export const READ = 'read';
3
+ export const WRITE = 'write';
4
+ export function pfSuccess(action, data, meta) {
5
+ const payload = { ok: true, action, data };
6
+ if (meta && Object.keys(meta).length > 0)
7
+ payload.meta = meta;
8
+ // 把 meta.continuation 镜像到 data,使「读 data.continuation」与「读 meta.continuation」都能取到同一个值。
9
+ const cont = meta?.continuation;
10
+ if (typeof cont === 'string' && data && typeof data === 'object' && !Array.isArray(data)) {
11
+ const obj = data;
12
+ if (!(typeof obj.continuation === 'string' && obj.continuation))
13
+ obj.continuation = cont;
14
+ }
15
+ return payload;
16
+ }
17
+ /** 构造「对象类型 + 严格禁止额外字段」的 JSON Schema。 */
18
+ export function schemaOf(properties, options = {}) {
19
+ return {
20
+ type: 'object',
21
+ additionalProperties: false,
22
+ properties,
23
+ ...(options.required?.length ? { required: options.required } : {}),
24
+ ...(options.description ? { description: options.description } : {}),
25
+ };
26
+ }
27
+ export function asObject(value) {
28
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
29
+ throw pfValidationError('input_not_object', '输入必须是 JSON 对象');
30
+ }
31
+ return value;
32
+ }
@@ -0,0 +1,307 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { pfValidationError } from './errors.js';
3
+ const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
4
+ /** targetType → 中文名(SchemeServiceImpl:2165 方案对象浏览器类型表)。 */
5
+ export const TARGET_TYPE_LABELS = {
6
+ 1: '人员',
7
+ 2: '部门',
8
+ 3: '部门(含下级)',
9
+ 5: '分部',
10
+ 6: '分部(含下级)',
11
+ 10: '角色',
12
+ 11: '所有人',
13
+ 12: '岗位+指定部门',
14
+ 13: '岗位+指定分部',
15
+ 1311: '岗位+总部',
16
+ 14: '群组+安全级别',
17
+ 1411: '群组',
18
+ };
19
+ const OPERATE_TYPE_LABELS = {
20
+ fixedMan: '指定人',
21
+ directSuperior: '直接上级',
22
+ indirectSuperior: '间接上级',
23
+ otherSuperior: '其他上级',
24
+ assessmentMan: '被考核人',
25
+ subordinates: '下级',
26
+ samePositionMan: '同岗位人员',
27
+ sameGradeMan: '同职级人员',
28
+ sameDepartmentMan: '同部门人员',
29
+ };
30
+ const STEP_TYPE_LABELS = {
31
+ kpsStepList: '评分',
32
+ plusStepList: '加分评分',
33
+ minusStepList: '减分评分',
34
+ flowStepList: '审批',
35
+ interviewStepList: '面谈',
36
+ };
37
+ function num(v) {
38
+ if (v === null || v === undefined)
39
+ return null;
40
+ const parsed = parseFloat(String(v).replace('%', '').trim());
41
+ return Number.isFinite(parsed) ? parsed : null;
42
+ }
43
+ function stepsOf(req) {
44
+ const steps = [];
45
+ for (const [key, label] of Object.entries(STEP_TYPE_LABELS)) {
46
+ const list = req[key];
47
+ if (!Array.isArray(list))
48
+ continue;
49
+ for (const step of list) {
50
+ const operators = Array.isArray(step?.stepOperators) ? step.stepOperators : [];
51
+ const who = operators
52
+ .map((op) => OPERATE_TYPE_LABELS[String(op?.operateType)] || String(op?.operateType || '?'))
53
+ .join('/');
54
+ steps.push(`${label}${who ? `(${who})` : ''}`);
55
+ }
56
+ }
57
+ return steps;
58
+ }
59
+ export function summarizeScheme(req) {
60
+ const basicData = Array.isArray(req.basicData) ? req.basicData : [];
61
+ const weights = basicData
62
+ .map((row) => num(row?.weight))
63
+ .filter((w) => w !== null);
64
+ return {
65
+ name: typeof req.name === 'string' && req.name ? req.name : null,
66
+ dateType: req.dateType ?? null,
67
+ total: req.total ?? null,
68
+ targetCount: Array.isArray(req.schemeLinkList) ? req.schemeLinkList.length : 0,
69
+ indicatorCount: basicData.length,
70
+ weightSum: weights.length ? weights.reduce((a, b) => a + b, 0) : null,
71
+ plusCount: Array.isArray(req.plusList) ? req.plusList.length : 0,
72
+ minusCount: Array.isArray(req.minusList) ? req.minusList.length : 0,
73
+ steps: stepsOf(req),
74
+ teffectTime: req.teffectTime ?? null,
75
+ failureTime: req.failureTime ?? null,
76
+ };
77
+ }
78
+ export function describeTargets(req) {
79
+ const links = Array.isArray(req.schemeLinkList) ? req.schemeLinkList : [];
80
+ return links.map((link) => {
81
+ const label = TARGET_TYPE_LABELS[Number(link?.targetType)] || `targetType=${link?.targetType}`;
82
+ return `${link?.name || '(未命名)'}[${label}]`;
83
+ });
84
+ }
85
+ /** 校验 SchemeEditReq;返回问题列表(error 必须修复,warn 需向用户说明)。 */
86
+ export function validateScheme(req) {
87
+ const issues = [];
88
+ if (!req.name || typeof req.name !== 'string' || !req.name.trim()) {
89
+ issues.push({ level: 'error', message: 'name(方案名称)缺失或为空' });
90
+ }
91
+ if (!Array.isArray(req.schemeLinkList) || req.schemeLinkList.length === 0) {
92
+ issues.push({ level: 'error', message: 'schemeLinkList(考核对象)为空——考核对象没有默认值,必须由用户提供' });
93
+ }
94
+ if (!Array.isArray(req.basicData) || req.basicData.length === 0) {
95
+ issues.push({ level: 'warn', message: 'basicData(指标)为空,将创建无指标方案' });
96
+ }
97
+ if (!Array.isArray(req.flowStepList) || req.flowStepList.length === 0) {
98
+ issues.push({ level: 'warn', message: 'flowStepList(审批节点)为空:方案将没有审批环节,确认是否符合文档' });
99
+ }
100
+ // 布尔字段必须输出真布尔(文档中文「是/否」直接传入是常见错误)。
101
+ for (const field of ['includePlusItem', 'includeMinusItem', 'includeInterviewItem']) {
102
+ if (req[field] !== undefined && typeof req[field] !== 'boolean') {
103
+ issues.push({ level: 'error', message: `${field} 必须是布尔 true/false,得到 ${JSON.stringify(req[field])}` });
104
+ }
105
+ }
106
+ // 加减分项开关联动。
107
+ if (Array.isArray(req.plusList) && req.plusList.length > 0 && req.includePlusItem !== true) {
108
+ issues.push({ level: 'error', message: 'plusList 非空时必须 includePlusItem=true' });
109
+ }
110
+ if (Array.isArray(req.minusList) && req.minusList.length > 0 && req.includeMinusItem !== true) {
111
+ issues.push({ level: 'error', message: 'minusList 非空时必须 includeMinusItem=true' });
112
+ }
113
+ if (req.includeInterviewItem === true && (!Array.isArray(req.interviewStepList) || req.interviewStepList.length === 0)) {
114
+ issues.push({ level: 'error', message: 'includeInterviewItem=true 时 interviewStepList 至少一个节点' });
115
+ }
116
+ const basicData = Array.isArray(req.basicData) ? req.basicData : [];
117
+ const weights = basicData
118
+ .map((row) => num(row?.weight))
119
+ .filter((w) => w !== null);
120
+ if (basicData.length && weights.length === basicData.length) {
121
+ const sum = weights.reduce((a, b) => a + b, 0);
122
+ if (Math.abs(sum - 100) > 0.01) {
123
+ issues.push({ level: 'warn', message: `常规指标权重合计 ${sum} ≠ 100(差额 ${100 - sum}),由用户决定是否接受。注意:权重按百分比口径,与分制(total)相互独立,不因分制换算` });
124
+ }
125
+ }
126
+ for (const field of ['teffectTime', 'failureTime']) {
127
+ if (req[field] !== undefined && req[field] !== null && !DATE_RE.test(String(req[field]))) {
128
+ issues.push({ level: 'error', message: `${field} 格式应为 yyyy-MM-dd,得到 ${JSON.stringify(req[field])}` });
129
+ }
130
+ }
131
+ if (req.teffectTime && req.failureTime && String(req.teffectTime) >= String(req.failureTime)) {
132
+ issues.push({ level: 'error', message: `生效日期(${req.teffectTime})必须早于失效日期(${req.failureTime})` });
133
+ }
134
+ if (req.failureTime && DATE_RE.test(String(req.failureTime)) && String(req.failureTime) < new Date().toISOString().slice(0, 10)) {
135
+ issues.push({ level: 'warn', message: `失效日期(${req.failureTime})已早于当前日期:发布后方案会被自动置为「已失效」,请确认是否改为未来日期` });
136
+ }
137
+ if (req.teffectTime && DATE_RE.test(String(req.teffectTime))) {
138
+ const twoYearsLater = new Date();
139
+ twoYearsLater.setFullYear(twoYearsLater.getFullYear() + 2);
140
+ if (String(req.teffectTime) > twoYearsLater.toISOString().slice(0, 10)) {
141
+ issues.push({ level: 'warn', message: `生效日期(${req.teffectTime})距今超过两年,请确认年份是否抽取错误` });
142
+ }
143
+ }
144
+ // schemeLinkList 的 id 规则:targetType=11(所有人)固定 0,其余必须有 id。
145
+ const links = Array.isArray(req.schemeLinkList) ? req.schemeLinkList : [];
146
+ for (const link of links) {
147
+ if (Number(link?.targetType) === 11)
148
+ continue;
149
+ if (link?.id === undefined || link?.id === null || link?.id === '') {
150
+ issues.push({ level: 'error', message: `考核对象「${link?.name || '(未命名)'}」缺 id(targetType=${link?.targetType})——先用 hrm.resolve 解析真实 id` });
151
+ }
152
+ }
153
+ return issues;
154
+ }
155
+ export function assertNoErrors(issues) {
156
+ const errors = issues.filter((issue) => issue.level === 'error');
157
+ if (errors.length > 0) {
158
+ throw pfValidationError('scheme_validation_failed', '方案参数校验未通过', {
159
+ errors: errors.map((issue) => issue.message),
160
+ });
161
+ }
162
+ return issues;
163
+ }
164
+ /** 提交内容的稳定指纹:prepare 与 apply 各算一次,不一致即 fingerprint_mismatch。 */
165
+ export function schemeFingerprint(req) {
166
+ return createHash('sha256').update(JSON.stringify(req)).digest('hex');
167
+ }
168
+ /** 业务口径类型名(禁止把 qualitative/quantify 直接给用户)。 */
169
+ const MODE_LABELS = { qualitative: '定性', quantify: '定量' };
170
+ const STEP_ORDER_LABELS = {
171
+ kpsStepList: '评分',
172
+ plusStepList: '加分评定',
173
+ minusStepList: '减分评定',
174
+ flowStepList: '审批',
175
+ interviewStepList: '面谈',
176
+ };
177
+ /** checkType id → 分类名(服务端可能返回数组或对象,兼容两种)。 */
178
+ function categoryNameMap(req) {
179
+ const map = {};
180
+ const list = Array.isArray(req.checkType) ? req.checkType : [];
181
+ for (const item of list) {
182
+ if (item && item.id !== undefined && item.typeName)
183
+ map[String(item.id)] = String(item.typeName);
184
+ }
185
+ return map;
186
+ }
187
+ /** 常规指标 → 可直接渲染成表格的业务行(不含任何英文字段名/枚举值)。 */
188
+ export function buildIndicatorRows(req) {
189
+ const rows = Array.isArray(req.basicData) ? req.basicData : [];
190
+ const categories = categoryNameMap(req);
191
+ return rows.map((row, index) => {
192
+ const weight = num(row?.weight);
193
+ return {
194
+ index: index + 1,
195
+ name: row?.indicatorType ?? null,
196
+ mode: row?.indicatorMode ? (MODE_LABELS[String(row.indicatorMode)] ?? null) : null,
197
+ weight: weight === null ? '未填' : `${weight}%`,
198
+ target: row?.defaultTarget ? String(row.defaultTarget) : null,
199
+ category: row?.checkType ? (categories[String(row.checkType)] ?? null) : null,
200
+ description: row?.indicatorDescription ? String(row.indicatorDescription) : null,
201
+ };
202
+ });
203
+ }
204
+ /** 加分项/减分项 → 可直接渲染成表格的业务行。 */
205
+ export function buildBonusPenaltyRows(req, kind) {
206
+ const rows = Array.isArray(kind === 'plus' ? req.plusList : req.minusList)
207
+ ? (kind === 'plus' ? req.plusList : req.minusList)
208
+ : [];
209
+ const stepList = kind === 'plus' ? req.plusStepList : req.minusStepList;
210
+ const raters = Array.isArray(stepList)
211
+ ? stepList.flatMap((step) => (Array.isArray(step?.stepOperators) ? step.stepOperators : []))
212
+ .map((op) => OPERATE_TYPE_LABELS[String(op?.operateType)] || null)
213
+ .filter((x) => Boolean(x))
214
+ : [];
215
+ const rater = raters.length ? [...new Set(raters)].join('/') : null;
216
+ return rows.map((row, index) => {
217
+ const max = num(row?.maxScore);
218
+ return {
219
+ index: index + 1,
220
+ name: row?.name ?? null,
221
+ rule: row?.description ? String(row.description) : null,
222
+ limit: max === null ? null : `${max} 分`,
223
+ rater,
224
+ note: null,
225
+ };
226
+ });
227
+ }
228
+ /** 方案展示所需的结构化业务数据(Agent 直接按此渲染四段内容,不必解析原始 JSON)。 */
229
+ export function buildSchemeView(req) {
230
+ const summary = summarizeScheme(req);
231
+ return {
232
+ summary: {
233
+ ...summary,
234
+ dateTypeLabel: DATE_TYPE_LABELS[String(summary.dateType)] ?? null,
235
+ weightSumText: summary.weightSum === null ? null : `${summary.weightSum}%`,
236
+ stepLabels: stepsOf(req),
237
+ },
238
+ targets: describeTargets(req),
239
+ indicatorRows: buildIndicatorRows(req),
240
+ plusRows: buildBonusPenaltyRows(req, 'plus'),
241
+ minusRows: buildBonusPenaltyRows(req, 'minus'),
242
+ };
243
+ }
244
+ const DATE_TYPE_LABELS = { year: '年度', halfyear: '半年度', quarter: '季度', month: '月度' };
245
+ /**
246
+ * 提交前的规范化(防止服务端静默丢数据 / 静默漏评分人)。
247
+ *
248
+ * 三个已知坑(2026-11 实测 + 服务端源码确认):
249
+ * 1. `basicData[].defaultTarget` 是 Float/Double(SchemeIndicator.defaultTarget)——
250
+ * 文字目标("当月验收12万或回款7万")塞进去会被服务端丢成 null,只能写入 indicatorDescription。
251
+ * 2. `plusList`/`minusList` 非空但 `plusStepList`/`minusStepList` 为空时,评分人不会落库
252
+ * (节点 stepType 分别是 kpiplus / kpiminus,见 PerformanceSchemCreateAIFunction)。
253
+ * 3. 覆盖式暂存(带 id)必须带 detailId,否则服务端重复插入明细行、detail 永久 500。
254
+ */
255
+ export function normalizeSchemeBody(input) {
256
+ const body = JSON.parse(JSON.stringify(input));
257
+ const issues = [];
258
+ // ① 目标值:数字才进 defaultTarget,文字挪进描述
259
+ if (Array.isArray(body.basicData)) {
260
+ body.basicData = body.basicData.map((row, index) => {
261
+ if (!row || typeof row !== 'object')
262
+ return row;
263
+ const raw = row.defaultTarget;
264
+ if (typeof raw !== 'string' || !raw.trim())
265
+ return row;
266
+ const text = raw.trim();
267
+ const numeric = num(text);
268
+ if (numeric !== null) {
269
+ return { ...row, defaultTarget: numeric };
270
+ }
271
+ const prefix = `目标:${text}`;
272
+ const desc = typeof row.indicatorDescription === 'string' ? row.indicatorDescription.trim() : '';
273
+ issues.push({
274
+ level: 'warn',
275
+ message: `第 ${index + 1} 行「${row.indicatorType || '未命名'}」的目标值是文字(${text}),系统目标值字段只接受数字,已改写进指标描述`,
276
+ });
277
+ return {
278
+ ...row,
279
+ defaultTarget: undefined,
280
+ indicatorDescription: desc ? `${desc};${prefix}` : prefix,
281
+ };
282
+ });
283
+ // 去掉 undefined 键,避免提交 null 语义歧义
284
+ body.basicData = body.basicData.map((row) => {
285
+ if (row && typeof row === 'object' && 'defaultTarget' in row && row.defaultTarget === undefined) {
286
+ const { defaultTarget: _drop, ...rest } = row;
287
+ return rest;
288
+ }
289
+ return row;
290
+ });
291
+ }
292
+ // ② 加减分项评分人节点缺失时补默认(直接上级),并提示
293
+ const fillStep = (listKey, stepKey, stepType) => {
294
+ const list = Array.isArray(body[listKey]) ? body[listKey] : [];
295
+ const steps = Array.isArray(body[stepKey]) ? body[stepKey] : [];
296
+ if (list.length === 0 || steps.length > 0)
297
+ return;
298
+ body[stepKey] = [{ stepType, stepOperators: [{ operateType: 'directSuperior' }] }];
299
+ issues.push({
300
+ level: 'warn',
301
+ message: `${listKey} 有 ${list.length} 项但未提供 ${stepKey},已按默认「直接上级」补齐评分人(否则评分人不会落库)`,
302
+ });
303
+ };
304
+ fillStep('plusList', 'plusStepList', 'kpiplus');
305
+ fillStep('minusList', 'minusStepList', 'kpiminus');
306
+ return { body, issues };
307
+ }
@@ -0,0 +1,158 @@
1
+ import { pfFail, pfValidationError } from './errors.js';
2
+ /** WeaResult 业务成功判定(绩效模块接口统一返回 {code,msg,status,fail,data})。 */
3
+ export function assertWeaResult(response, context) {
4
+ if (!response || typeof response !== 'object') {
5
+ throw pfFail(`${context}:接口返回不是对象`, { response });
6
+ }
7
+ const failed = response.fail === true || (response.status !== undefined && response.status !== true) || (response.code !== undefined && response.code !== 200);
8
+ if (failed) {
9
+ throw pfFail(`${context}:${response.msg || '接口返回失败'}`, {
10
+ code: response.code,
11
+ msg: response.msg,
12
+ });
13
+ }
14
+ return response.data;
15
+ }
16
+ /**
17
+ * SchemeEditReq 的 inputSchema(逐字段,manual 红线:不能只转到 payload 这一层)。
18
+ * 完整字段语义见 skills/weaver-e10-performance/references/scheme-edit-req-fields.md。
19
+ */
20
+ const stringField = { type: 'string' };
21
+ const numberField = { type: 'number' };
22
+ const booleanField = { type: 'boolean' };
23
+ const nullableNumber = { type: ['number', 'null'] };
24
+ const objectItems = (properties) => ({ type: 'array', items: { type: 'object', properties, additionalProperties: true } });
25
+ const indicatorFields = {
26
+ dataRow: { type: 'integer' }, indicatorMode: { type: 'string', enum: ['qualitative', 'quantify'] },
27
+ indicatorType: stringField, indicatorDescription: stringField, weight: stringField,
28
+ defaultTarget: stringField, scoreScope: stringField, checkType: stringField,
29
+ customInputScope: stringField, appointScoreData: stringField, targetId: nullableNumber,
30
+ targetHasEdit: booleanField, dataSource: stringField, dataSourceMode: stringField,
31
+ scoreFormula: stringField, unit: stringField,
32
+ };
33
+ const itemFields = { name: stringField, description: stringField, maxScore: numberField,
34
+ sort: { type: 'integer' }, scoreScope: stringField, lockTarget: booleanField,
35
+ newTarget: booleanField, targetId: nullableNumber, targetHasEdit: booleanField };
36
+ const stepFields = { sort: { type: 'integer' }, stepType: stringField, raterType: stringField,
37
+ checkKps: booleanField, checkSignature: booleanField, stepWeight: numberField,
38
+ scoreMinNum: nullableNumber, scoreMaxNum: nullableNumber, interviewOrder: { type: ['string', 'null'] },
39
+ stepOperators: objectItems({ operateType: stringField, operater: { type: ['integer', 'string', 'null'] } }) };
40
+ export const schemeEditReqSchema = {
41
+ id: { type: 'string', description: '方案 id,字符串形式(18 位 Long 转 JSON 数字会丢精度)。首次暂存不传;再次暂存/发布必传(覆盖式更新)' },
42
+ detailId: { type: 'string', description: '指标明细 id,字符串形式(发布时必传;缺失会导致 hr_kpi_details 重复插入、detail 永久 500)' },
43
+ name: { type: 'string', description: '方案名称(必填)' },
44
+ dateType: { type: 'string', enum: ['year', 'halfyear', 'quarter', 'month'], description: '考核周期' },
45
+ total: { type: ['number', 'string'], description: '总分制(如 100)' },
46
+ type: { type: 'integer', description: '方案类型(工作考核=1)' },
47
+ weightMode: { type: 'string', enum: ['simple', 'advanced'], description: '权重模式,默认 simple' },
48
+ schemeLinkList: {
49
+ type: 'array',
50
+ description: '考核对象(必填,多条按并集处理)。targetType:1人员/2,3部门/5,6分部/10角色/11所有人(id=0)/12,13,1311岗位',
51
+ items: {
52
+ type: 'object',
53
+ additionalProperties: false,
54
+ properties: {
55
+ id: { type: 'string', description: '实体 id,字符串形式,原样透传 hrm.resolve 返回值(targetType=11 时固定 "0")' },
56
+ targetType: { type: 'integer', description: '对象类型(见 entity-resolution.md)' },
57
+ name: { type: 'string', description: '名称(仅展示用,可选)' },
58
+ role_level: { type: 'integer', description: '角色级别(targetType=10 时需确认)' },
59
+ position_level: { type: 'integer', description: '岗位级别(targetType=12/13/1311 可选)' },
60
+ seclevel: { type: 'object', description: '安全级别区间 {max,min},一般不填' },
61
+ },
62
+ required: ['id', 'targetType'],
63
+ },
64
+ },
65
+ basicData: objectItems(indicatorFields),
66
+ includePlusItem: booleanField,
67
+ includeMinusItem: booleanField,
68
+ includeInterviewItem: booleanField,
69
+ plusList: objectItems(itemFields),
70
+ minusList: objectItems(itemFields),
71
+ kpsStepList: objectItems(stepFields),
72
+ plusStepList: objectItems(stepFields),
73
+ minusStepList: objectItems(stepFields),
74
+ flowStepList: objectItems(stepFields),
75
+ interviewStepList: objectItems(stepFields),
76
+ stepWeightList: objectItems({ indicatorMode: stringField, indicatorRow: { type: 'integer' }, stepIndex: { type: 'integer' }, weight: numberField }),
77
+ checkType: objectItems({ id: stringField, typeName: stringField, weight: numberField, rowLine: stringField, scoreLimit: nullableNumber }),
78
+ basicHeader: objectItems({ title: stringField, dataIndex: stringField, comKey: stringField, width: stringField }),
79
+ countType: { type: 'integer', description: '计分方式' },
80
+ assessmentDescription: stringField, assessmentStatus: booleanField,
81
+ forbidApproveTime: { type: 'integer' },
82
+ remark: booleanField, reward: booleanField, rewardName: stringField,
83
+ showTargetColumn: booleanField, openCheckType: booleanField,
84
+ weightSum: booleanField, typeWeightSum: booleanField, eachWeightSum: booleanField,
85
+ openNextTarget: booleanField, openCorrection: booleanField,
86
+ openCorrectionScope: { type: 'object', properties: { min: numberField, max: numberField }, additionalProperties: true },
87
+ scoreLimit: booleanField, priority: booleanField,
88
+ seeTotal: booleanField, seeScoreDetail: booleanField, seePlusItem: booleanField,
89
+ seeMinusItem: booleanField, seeDistributionAdjust: booleanField, seeAfterFinish: booleanField,
90
+ commitContent: stringField, commitDay: { type: 'integer' }, commitRemindTime: stringField,
91
+ overtimeContent: stringField, overtimeDay: { type: 'integer' }, overRemindTime: stringField,
92
+ kpsDistributeType: stringField, flowDistributeType: stringField, createMode: stringField,
93
+ fieldFilters: { type: 'array', items: { type: 'object', additionalProperties: true } },
94
+ operatingTargetList: { type: 'array', items: { type: 'object', additionalProperties: true } },
95
+ remindOrdinaryData: { description: '自定义提醒配置,结构以接口为准' },
96
+ remindTimeData: { description: '自定义提醒时间配置,结构以接口为准' },
97
+ teffectTime: { type: 'string', description: '生效日期 yyyy-MM-dd(文档未提及时默认当天)' },
98
+ failureTime: { type: 'string', description: '失效日期 yyyy-MM-dd(可选)' },
99
+ dateTypeSet: { type: 'string', enum: ['setting', 'custom'], description: '自动时间项模式;填 distributeTime/forbidTime 时应为 custom' },
100
+ distributeTime: { type: 'integer', description: '下发时间(毫秒时间戳,可选)' },
101
+ forbidTime: { type: 'integer', description: '截止时间(毫秒时间戳,可选)' },
102
+ seeSetting: { type: 'string', enum: ['default', 'custom'], description: '可见性设置,默认 default' },
103
+ remindSetting: { type: 'string', enum: ['default', 'custom'], description: '提醒设置,默认 default' },
104
+ };
105
+ /**
106
+ * id 精度保护:服务端 id 是 18 位 Long,JS number 只有 53 位精度。
107
+ * - 字符串:原样返回(推荐路径)
108
+ * - 安全整数 number:转字符串
109
+ * - 超出安全范围的 number:直接拒绝(此时数值已丢精度,无法还原真实 id)
110
+ */
111
+ export function normalizeId(value, field) {
112
+ if (typeof value === 'string') {
113
+ const trimmed = value.trim();
114
+ if (!trimmed)
115
+ throw pfFail(`${field} 不能为空字符串`);
116
+ return trimmed;
117
+ }
118
+ if (typeof value === 'number' && Number.isFinite(value)) {
119
+ if (!Number.isSafeInteger(value)) {
120
+ throw pfValidationError('id_precision_loss', `${field} 传了数字 ${value},已超出 JS 安全整数范围(18 位 id 会丢精度、指向错误记录)。请改写为字符串形式传入。`);
121
+ }
122
+ return String(value);
123
+ }
124
+ throw pfValidationError('id_invalid', `${field} 必须是字符串(当前 ${typeof value})`);
125
+ }
126
+ const DETAIL_PATH = '/api/workrelate/performance/scheme/detail';
127
+ /**
128
+ * 覆盖式暂存的 detailId 兜底(2026-11 实测事故:重新暂存漏带 detailId →
129
+ * hr_kpi_details 重复插入 → 该方案 detail 永久 500、无法自愈)。
130
+ *
131
+ * 规则:
132
+ * - 新建(无 id):原样返回。
133
+ * - 覆盖(有 id)且已带 detailId:原样返回。
134
+ * - 覆盖(有 id)但缺 detailId:先 detail 回读补上;回读失败(方案明细已损坏或不存在)→ 直接拒绝,不再写入。
135
+ */
136
+ export async function ensureDetailIdForUpdate(host, body, operation) {
137
+ if (body.id === undefined || body.id === null || body.id === '')
138
+ return body;
139
+ if (body.detailId !== undefined && body.detailId !== null && body.detailId !== '')
140
+ return body;
141
+ const id = normalizeId(body.id, 'id');
142
+ let detailData;
143
+ try {
144
+ const response = await host.request({
145
+ path: `${DETAIL_PATH}/${encodeURIComponent(id)}`,
146
+ method: 'GET',
147
+ operation,
148
+ });
149
+ detailData = assertWeaResult(response, '读取方案详情(补 detailId)');
150
+ }
151
+ catch (error) {
152
+ throw pfValidationError('detail_unreadable', `方案 ${id} 的详情无法回读(可能明细已损坏):不能覆盖暂存,否则会继续写入重复明细。请新建方案,或先在方案设置页核对该方案。`, { id });
153
+ }
154
+ if (!detailData || detailData.detailId === undefined || detailData.detailId === null || detailData.detailId === '') {
155
+ throw pfValidationError('detail_id_missing', `方案 ${id} 回读不到 detailId:覆盖暂存会导致重复明细,已拒绝写入。请新建方案或先在方案设置页核查。`, { id });
156
+ }
157
+ return { ...body, id, detailId: normalizeId(detailData.detailId, 'detailId') };
158
+ }