@teamdream/sems-mcp 0.0.0-stage → 1.0.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.
@@ -0,0 +1,1546 @@
1
+ /**
2
+ * P2 写入工具:三张单据的两阶段起草/提交 + 合同 + 附件。
3
+ *
4
+ * ## 为什么必须是两阶段
5
+ *
6
+ * SEMS 的建单接口没有幂等键,一旦重复提交就会多出一张真单据。而 AI 在对话里
7
+ * 「理解偏了一点」是常态(客户选错、数量多一个零、单价把含税当不含税)。
8
+ * 所以写操作拆成两个工具:
9
+ *
10
+ * `prepare_*` → 不发任何 POST,只把**将要提交的完整 body** 和摘要交给人看
11
+ * `commit_*` → 只认 `draftId + digest`,两者对不上就拒绝
12
+ *
13
+ * 🔴 commit **不接受任何业务参数覆盖**。想改就重新 prepare。
14
+ * 这是防「用户确认的是 A,提交的是 A′」的唯一可靠手段 —— 一旦允许「带修改提交」,
15
+ * 校验就退化成「AI 说它没改」。
16
+ *
17
+ * ## 草稿里必须显式警告的三件事
18
+ *
19
+ * 1. 明细缺 `storageManageRecordId` ⇒ 后端视为定制产品,**库存不扣减、不报错**
20
+ * (`SaleController#needUpdateStorage` 用非空判断,静默跳过);
21
+ * 2. 只给客户名不给 `customerId` ⇒ 后端会**自动新建一个客户**(`SaleController#save`)。
22
+ */
23
+ import { randomBytes } from "node:crypto";
24
+ import { readFileSync, statSync } from "node:fs";
25
+ import { basename, extname } from "node:path";
26
+ import { z } from "zod";
27
+ import { ProxyError, localError } from "../client/errors.js";
28
+ import { MULTIPART_BODY_HASH } from "../client/proxy.js";
29
+ import { digestOf } from "../drafts/digest.js";
30
+ import { unwrapSems } from "./payload.js";
31
+ import { wrap } from "./runner.js";
32
+ // ── 取值工具 ────────────────────────────────────────────────
33
+ export function asRecord(value) {
34
+ return typeof value === "object" && value !== null && !Array.isArray(value)
35
+ ? value
36
+ : {};
37
+ }
38
+ export function asArray(value) {
39
+ return Array.isArray(value) ? value : [];
40
+ }
41
+ function text(value) {
42
+ return typeof value === "string" ? value.trim() : "";
43
+ }
44
+ function numeric(value) {
45
+ if (typeof value === "number" && Number.isFinite(value))
46
+ return value;
47
+ if (typeof value === "string" && value.trim() !== "") {
48
+ const parsed = Number(value);
49
+ if (Number.isFinite(parsed))
50
+ return parsed;
51
+ }
52
+ return undefined;
53
+ }
54
+ /** si_sale.sold_time 是 NOT NULL 且后端不兜底,未指定时必须补当前时间(本地时区,秒级)。 */
55
+ function nowText() {
56
+ const d = new Date();
57
+ const p = (n) => String(n).padStart(2, "0");
58
+ return (`${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} `
59
+ + `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`);
60
+ }
61
+ /** 后端 LocalDateTime 只认 `yyyy-MM-dd HH:mm:ss`,纯日期会反序列化失败,这里补零时刻。 */
62
+ function normalizeDateTime(value) {
63
+ return /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value} 00:00:00` : value;
64
+ }
65
+ /** ID 统一走字符串:19 位雪花超 `2^53`,转成 number 会静默变成另一个 ID。 */
66
+ export function idText(value) {
67
+ const v = text(value);
68
+ if (v)
69
+ return v;
70
+ const n = numeric(value);
71
+ return n === undefined ? "" : String(n);
72
+ }
73
+ function needText(value, label) {
74
+ const v = text(value);
75
+ if (!v)
76
+ throw localError("PARAM_INVALID", `缺少必填参数:${label}`);
77
+ return v;
78
+ }
79
+ function needNumber(value, label) {
80
+ const v = numeric(value);
81
+ if (v === undefined)
82
+ throw localError("PARAM_INVALID", `缺少必填参数:${label}`);
83
+ return v;
84
+ }
85
+ /** 金额保留两位。先转整数分再算,避免 `0.1*3=0.30000000000000004` 落库。 */
86
+ function money(value) {
87
+ return Math.round(value * 100) / 100;
88
+ }
89
+ function moneyText(value) {
90
+ return value.toFixed(2);
91
+ }
92
+ /** 去掉 undefined 的键。`exactOptionalPropertyTypes` 下不能直接给可选字段赋 undefined。 */
93
+ function compact(source) {
94
+ const out = {};
95
+ for (const [key, value] of Object.entries(source)) {
96
+ if (value !== undefined && value !== null && value !== "")
97
+ out[key] = value;
98
+ }
99
+ return out;
100
+ }
101
+ function replyOf(draft, commitTool) {
102
+ return {
103
+ draftId: draft.id,
104
+ digest: draft.digest,
105
+ summary: draft.summary,
106
+ warnings: draft.warnings,
107
+ payload: draft.call.body,
108
+ next: `以上内容**尚未写入海竣信息系统**。请把 summary 完整念给用户,并说明 warnings;`
109
+ + `用户明确同意后再调用 ${commitTool}(draftId=${draft.id},digest=${draft.digest})。`
110
+ + "用户要求任何修改时,重新调用对应的 prepare 工具,不要试图改这份草稿。",
111
+ };
112
+ }
113
+ /** 上游响应里挑出「用户真正关心的那几个字段」,而不是整坨回传。 */
114
+ function pickCreated(data) {
115
+ const root = asRecord(data);
116
+ // 销售/报价返回的是 Dto 外壳,真正的单据在内层
117
+ const inner = ["sale", "preSale", "orderForm", "contract"]
118
+ .map((key) => asRecord(root[key]))
119
+ .find((candidate) => Object.keys(candidate).length > 0) ?? root;
120
+ const out = {};
121
+ for (const key of ["id", "saleNo", "orderNumber", "preSaleNo", "contractNo", "name", "amount"]) {
122
+ const value = inner[key];
123
+ if (value !== undefined && value !== null && value !== "")
124
+ out[key] = value;
125
+ }
126
+ return Object.keys(out).length > 0 ? out : root;
127
+ }
128
+ /**
129
+ * 写接口的 `data` 就是布尔值(`R.ok(contractService.save(contract))`)。
130
+ *
131
+ * `unwrapSems` 只在 `code !== 0` 时抛错,`false` 会原样返回——不单独判的话,
132
+ * 库里根本没这条记录,工具却回报「已创建」。`null` 不算失败(有些接口只回 code)。
133
+ */
134
+ export function ensureSaved(data, what) {
135
+ if (data === false) {
136
+ throw localError("UPSTREAM_ERROR", `海竣信息系统的${what}接口返回 false:这条记录没有写进库。`
137
+ + "请让用户到海竣信息系统里确认,不要当作已成功回报。");
138
+ }
139
+ }
140
+ /**
141
+ * 校验草稿 → 提交 → 记账。
142
+ *
143
+ * 提交失败时**不重试**:建单接口没有幂等键,超时既可能「没建成」也可能「建成了但没收到」。
144
+ * 自动重试会造出两张单,所以把草稿标成 failed 并要求用户先去核实。
145
+ */
146
+ async function commitDraft(ctx, tool, args, path, successText) {
147
+ const draftId = needText(args["draftId"], "draftId");
148
+ const digest = needText(args["digest"], "digest");
149
+ const taken = ctx.drafts.take(draftId, tool, digest);
150
+ if (!taken.ok)
151
+ throw localError("PARAM_INVALID", taken.reason);
152
+ const draft = taken.draft;
153
+ ctx.drafts.markSubmitting(draft);
154
+ try {
155
+ const response = await ctx.client.call({ method: "POST", path, body: draft.call.body });
156
+ const data = unwrapSems(response.data);
157
+ ctx.drafts.markCommitted(draft, data);
158
+ return {
159
+ created: true,
160
+ message: successText,
161
+ record: pickCreated(data),
162
+ note: "请把单据编号回报给用户,并提醒在海竣信息系统对应列表里核对一遍。",
163
+ };
164
+ }
165
+ catch (err) {
166
+ ctx.drafts.markFailed(draft);
167
+ const detail = err instanceof ProxyError
168
+ ? err.message
169
+ : err instanceof Error
170
+ ? err.message
171
+ : String(err);
172
+ throw new ProxyError("UPSTREAM_ERROR", 0, `提交未确认成功:${detail}`, false, "海竣信息系统的建单接口没有幂等键,所以不会自动重试。请先用查询工具核实这张单据是否已经创建;"
173
+ + "确认没有之后,重新 prepare 一份新草稿再提交。");
174
+ }
175
+ }
176
+ // ── 销售单 ──────────────────────────────────────────────────
177
+ const SALE_ITEM = z.object({
178
+ productId: z.coerce.number().int().positive().optional().describe("产品 ID;有就带上,便于对账"),
179
+ name: z.string().min(1).describe("产品名称"),
180
+ spec: z.string().optional().describe("规格型号(必填;缺省时按库存记录/产品档案补齐)"),
181
+ specDetail: z
182
+ .string()
183
+ .optional()
184
+ .describe("详细配置(必填;缺省时按库存记录补齐,产品档案无此列则用规格型号代之)"),
185
+ unit: z.string().optional().describe("单位,如「台」「套」(必填;缺省时按库存记录/产品档案补齐)"),
186
+ quantity: z.coerce.number().positive().describe("数量"),
187
+ unitPrice: z.coerce.number().min(0).describe("单价(元)"),
188
+ buyPrice: z.coerce
189
+ .number()
190
+ .min(0)
191
+ .optional()
192
+ .describe("成本单价(元)。定制产品没有库存档案时必须给,否则成本记 0、利润虚高;"
193
+ + "有库存记录时不传则按档案带出"),
194
+ storageManageRecordId: z.coerce
195
+ .number()
196
+ .int()
197
+ .positive()
198
+ .optional()
199
+ .describe("库存记录 ID。来自 sems_query_stock 的 id 字段。"
200
+ + "**不传则视为定制产品:库存不扣减,且不会报错**"),
201
+ remark: z.string().optional(),
202
+ });
203
+ export function registerWrites(server, ctx) {
204
+ registerSale(server, ctx);
205
+ registerPurchase(server, ctx);
206
+ registerQuotation(server, ctx);
207
+ registerContract(server, ctx);
208
+ registerUpload(server, ctx);
209
+ }
210
+ function registerSale(server, ctx) {
211
+ server.registerTool("sems_prepare_sale", {
212
+ title: "起草销售单(不写库)",
213
+ description: "把「客户 + 产品明细」整理成一份销售单草稿,**不写入海竣信息系统**。"
214
+ + "返回草稿摘要与将要提交的完整内容,供用户确认后再调用 sems_commit_sale。"
215
+ + "明细的名称/规格型号/详细配置/单位四项海竣信息系统逐行强制校验,缺了会被拒绝:"
216
+ + "带上 storageManageRecordId 或 productId 可自动带出规格与单位。"
217
+ + "明细里不给 storageManageRecordId 就是定制产品,库存不会扣减——若用户要的是现货销售,"
218
+ + "先调 sems_query_stock 拿到库存记录 ID。"
219
+ + "客户省份/城市/联系人/联系人电话要落进 NOT NULL 列:客户档案缺哪项就一次性列出来让用户补,"
220
+ + "不会拿当前登录账号的信息顶替。",
221
+ inputSchema: {
222
+ customerName: z.string().min(1).describe("客户名称。海竣信息系统里查不到时会**自动新建客户**"),
223
+ customerId: z.coerce
224
+ .number()
225
+ .int()
226
+ .positive()
227
+ .optional()
228
+ .describe("客户 ID。有就传,避免同名客户歧义或误建新客户"),
229
+ customerTel: z.string().optional(),
230
+ customerProvince: z
231
+ .string()
232
+ .optional()
233
+ .describe("客户所在省,如「广东省」。不传则取客户档案;档案里也没有会要求用户补,不拿当前账号顶替"),
234
+ customerCity: z
235
+ .string()
236
+ .optional()
237
+ .describe("客户所在市,如「广州市」。不传则取客户档案;档案里也没有会要求用户补"),
238
+ customerAddress: z.string().optional(),
239
+ contactName: z
240
+ .string()
241
+ .optional()
242
+ .describe("客户联系人。不传则取客户档案;档案里也没有会要求用户补,不拿当前账号顶替"),
243
+ contactTel: z
244
+ .string()
245
+ .optional()
246
+ .describe("客户联系人电话。不传则取客户档案;档案里也没有会要求用户补"),
247
+ items: z.array(SALE_ITEM).min(1).describe("产品明细,至少一条"),
248
+ soldTime: z.string().optional().describe("销售日期 YYYY-MM-DD 或 YYYY-MM-DD HH:mm:ss,默认现在"),
249
+ paymentRateTime: z
250
+ .string()
251
+ .optional()
252
+ .describe("约定收款日期 YYYY-MM-DD 或 YYYY-MM-DD HH:mm:ss,默认与销售日期同一天"),
253
+ saleMan: z
254
+ .string()
255
+ .optional()
256
+ .describe("销售员姓名。不传则用当前登录账号;传别人时会按姓名反查用户 ID,查不到会报错"),
257
+ saleManId: z
258
+ .union([z.string().min(1), z.number().int().positive()])
259
+ .optional()
260
+ .describe("销售员用户 ID(19 位雪花,建议按字符串传)。与 saleMan 必须指向同一个人:"
261
+ + "只传 ID 时要连姓名一起传"),
262
+ invoiceType: z
263
+ .string()
264
+ .optional()
265
+ .describe("发票类型:增值专用发票(默认)/ 增值普通发票 / 无"),
266
+ financeCost: z.coerce.number().min(0).optional().describe("财务费用,默认 0"),
267
+ otherCost: z.coerce.number().min(0).optional().describe("其他费用(运费、服务费等),默认 0"),
268
+ amountPaid: z.coerce.number().min(0).optional().describe("已收金额,默认 0(欠款 = 金额 − 已收)"),
269
+ contractId: z.coerce.number().int().positive().optional().describe("关联的合同 ID"),
270
+ remark: z.string().optional(),
271
+ },
272
+ annotations: { readOnlyHint: true },
273
+ }, wrap(ctx, "sems_prepare_sale", (args) => prepareSaleDraft(ctx, args)));
274
+ server.registerTool("sems_commit_sale", {
275
+ title: "提交销售单(写库)",
276
+ description: "把 sems_prepare_sale 产出的草稿真正写入海竣信息系统。必须传回 prepare 给出的 draftId 与 digest,"
277
+ + "两者不一致会被拒绝。调用前务必已获得用户的明确同意。",
278
+ inputSchema: {
279
+ draftId: z.string().min(1).describe("sems_prepare_sale 返回的 draftId"),
280
+ digest: z.string().min(1).describe("sems_prepare_sale 返回的 digest"),
281
+ },
282
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
283
+ }, wrap(ctx, "sems_commit_sale", async (args) => commitDraft(ctx, "sems_prepare_sale", args, "/invoicing/sale", "销售单已创建")));
284
+ }
285
+ // ── 采购单 ──────────────────────────────────────────────────
286
+ const PURCHASE_ITEM = z.object({
287
+ productId: z.coerce.number().int().positive().optional(),
288
+ name: z.string().min(1).describe("产品名称"),
289
+ spec: z.string().min(1).describe("规格型号(海竣信息系统必填)"),
290
+ specDetail: z.string().optional().describe("详细配置(选填,但同名产品靠它区分)"),
291
+ unit: z.string().min(1).describe("单位(海竣信息系统必填)"),
292
+ quantity: z.coerce.number().positive().describe("数量"),
293
+ unitPrice: z.coerce.number().min(0).describe("单价(元)"),
294
+ remark: z.string().optional(),
295
+ });
296
+ function registerPurchase(server, ctx) {
297
+ server.registerTool("sems_prepare_purchase", {
298
+ title: "起草采购单(不写库)",
299
+ description: "整理采购单草稿,**不写入海竣信息系统**。部门、经办人、供应商地址等由供应商档案与当前登录身份自动补全。"
300
+ + "供应商联系人只取供应商档案或入参——海竣信息系统后端不带 contactId 会**按名字新建一份重复供应商**,"
301
+ + "取不到就直接报错让用户补,不会拿当前登录账号冒充供应商联系人。",
302
+ inputSchema: {
303
+ supplierName: z.string().min(1).describe("供应商名称(海竣信息系统复用客户字段,参数名仍是 customerName)"),
304
+ supplierId: z.coerce.number().int().positive().optional().describe("供应商 ID"),
305
+ supplierAddress: z.string().optional().describe("供应商地址(不传取供应商档案)"),
306
+ contactName: z
307
+ .string()
308
+ .optional()
309
+ .describe("供应商联系人姓名(不传取供应商档案;两边都没有会要求用户补,不会用当前账号顶替)"),
310
+ contactTel: z
311
+ .string()
312
+ .optional()
313
+ .describe("供应商联系人手机(不传取供应商档案;两边都没有会要求用户补,不会用当前账号顶替)"),
314
+ name: z.string().min(1).describe("订单名称"),
315
+ items: z.array(PURCHASE_ITEM).min(1).describe("采购明细,至少一条"),
316
+ taxIncluded: z.boolean().optional().describe("是否含税,默认 true"),
317
+ priority: z.enum(["普通", "紧急", "特急"]).optional().describe("紧急程度,默认「普通」"),
318
+ orderTime: z.string().optional().describe("下单时间,默认现在"),
319
+ invoiceType: z.string().optional().describe("发票类型,默认「增值专用发票」(与界面一致)"),
320
+ remark: z.string().optional(),
321
+ },
322
+ annotations: { readOnlyHint: true },
323
+ }, wrap(ctx, "sems_prepare_purchase", (args) => preparePurchaseDraft(ctx, args)));
324
+ server.registerTool("sems_commit_purchase", {
325
+ title: "提交采购单(写库)",
326
+ description: "把 sems_prepare_purchase 产出的草稿写入海竣信息系统。必须传回 draftId 与 digest,不一致会被拒绝。",
327
+ inputSchema: {
328
+ draftId: z.string().min(1),
329
+ digest: z.string().min(1),
330
+ },
331
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
332
+ }, wrap(ctx, "sems_commit_purchase", async (args) => commitDraft(ctx, "sems_prepare_purchase", args, "/invoicing/order-form", "采购单已创建")));
333
+ }
334
+ // ── 报价单 ──────────────────────────────────────────────────
335
+ /** 报价明细的产品只允许来自这三处,按顺位取、命中即止,禁止用商品库或自拟产品。 */
336
+ export const QUOTE_SOURCE_RULE = "🔴 产品来源固定三处,按顺位取、命中即止:① sems_query_market_quotes(市场动态)"
337
+ + " → ② sems_query_stock(库存)→ ③ sems_query_vendor_prices(标准产品)。"
338
+ + "不要用 sems_query_products(商品库)取报价产品,也不要凭名称与价格自拟一条。"
339
+ + "「同配置」的判定口径=产品名称 + 规格型号 + 规格详情 三者都一致(unit 不同不算同配置)。"
340
+ + "三处都没有同配置时**必须做拆改配**:取同一整机里最接近的配置当整机行,"
341
+ + "多出来的配置写 parts[].action=remove(拆解,成本减),缺的配置写 parts[].action=add(加装,成本加),"
342
+ + "并在整机行 remark 里写明「原配置→改后配置」,让用户一眼看懂怎么改的。"
343
+ + "配件本身(名称/规格/成本)同样只能取自这三处;成本价一律取来源记录的 unitPrice"
344
+ + "(库存的 unitPrice 即页面「销售成本」)。";
345
+ /**
346
+ * 配件行(拆改配):`add` 加装、`remove` 拆解。
347
+ *
348
+ * 落库口径与界面一致(`add-quotation.vue#onProductSelect`):加装 `quantity` 为正、
349
+ * 拆解为负,`amount = quantity × price`(拆解项因此是负数)。
350
+ * 所以 quantity 恒传正数,正负由 action 决定 —— 让模型少一个「方向搞反」的机会。
351
+ */
352
+ const QUOTE_PART = z.object({
353
+ action: z
354
+ .enum(["add", "remove"])
355
+ .describe("add=加装配件(成本增加)· remove=拆解配件(成本减少);无同配置产品时用它补齐配置差异"),
356
+ name: z.string().min(1).describe("配件名称(只能取自市场动态/库存/标准产品的记录,原样照抄)"),
357
+ spec: z.string().optional().describe("规格型号(取来源记录的 spec)"),
358
+ specDetail: z.string().optional().describe("规格详情(取来源记录的 specDetail);加装配件会拼进整机行的「规格详情」用于打印"),
359
+ unit: z.string().optional(),
360
+ quantity: z.coerce.number().positive().optional().describe("数量(恒传正数,正负由 action 决定),默认 1"),
361
+ costPrice: z.coerce
362
+ .number()
363
+ .min(0)
364
+ .optional()
365
+ .describe("配件成本单价(元/台套),取来源记录的 unitPrice;确实取不到才传 0(整机成本会偏低)"),
366
+ remark: z.string().optional().describe("备注,写清拆改了什么,如「原装 512G SSD 换 1T」"),
367
+ });
368
+ const QUOTE_ITEM = z.object({
369
+ productId: z.union([z.string(), z.number()]).optional().describe("产品 ID / 行标识(优先传字符串:19 位 ID 走 number 会丢精度);可不传(自动分配),传了必须全单唯一"),
370
+ name: z
371
+ .string()
372
+ .min(1)
373
+ .describe("产品名称:原样取来源记录的 name(库存)或 productName(市场动态、标准产品),不要改写或简写"),
374
+ spec: z.string().optional().describe("规格型号:原样取来源记录的 spec"),
375
+ specDetail: z.string().optional().describe("详细配置:原样取来源记录的 specDetail(同配置判定要逐字一致)"),
376
+ unit: z.string().optional().describe("单位:取来源记录的 unit,标准产品缺省「个」"),
377
+ quantity: z.coerce.number().positive().optional().describe("台数(等同 unitCount,保留旧写法),默认 1"),
378
+ unitCount: z.coerce.number().positive().optional().describe("整机数量(台数),默认取 quantity,再默认 1"),
379
+ salePrice: z.coerce
380
+ .number()
381
+ .min(0)
382
+ .optional()
383
+ .describe("对客报价单价(元/台)。全部行都给了才按「报价 ÷ 成本」反算利润率;缺行则按 profitRate 定价"),
384
+ costPrice: z.coerce
385
+ .number()
386
+ .min(0)
387
+ .optional()
388
+ .describe("整机成本单价(元/台,不含配件):取来源记录的 unitPrice;带 parts 拆改配时必填"),
389
+ parts: z
390
+ .array(QUOTE_PART)
391
+ .optional()
392
+ .describe("拆改配:该整机的加装/拆解配件,成本并入整机单价;没有同配置产品时必须用它补齐差异"),
393
+ vendor: z.string().optional().describe("供应商名称:市场动态来源填该记录的 supplierName,其余来源留空"),
394
+ remark: z.string().optional().describe("备注;拆改配的整机行在这里写「原配置→改后配置」"),
395
+ });
396
+ /**
397
+ * 报价单的利润率必须与「成本合计 / 报价合计」自洽。
398
+ *
399
+ * 前端 `add-quotation.vue#calculate` 的口径是
400
+ * `整机单价 = 行成本合计 × (1 + 利润率/100)`、`销售报价 = 整机单价 × 整机数量`,
401
+ * 而且任何编辑(改数量、改利润率)都会整表重算一遍。
402
+ * 所以利润率不能凭空给 15%:那样界面一重算就把用户报的合计金额改掉
403
+ * (成本 100、报价 150 会掉到 115)。这里按报价反算利润率,
404
+ * 让「成本合计 × (1 + 利润率) = 报价合计」,重算后**合计**金额不变。
405
+ *
406
+ * ⚠️ 利润率是整单一个值,界面是**逐行**重算的:各行毛利率本来一致时,
407
+ * 重算后每行单价也原样不动;各行毛利率不同时只有合计不变,
408
+ * 单行整机单价会按统一利润率重新分配。
409
+ *
410
+ * 999.99% 是 `si_pre_sale.profit_rate`(`decimal(5,2)`)的存储上限。
411
+ */
412
+ function quoteProfitRate(totalSale, totalCost) {
413
+ const rate = Math.round((totalSale / totalCost - 1) * 10000) / 100;
414
+ if (rate > 999.99) {
415
+ throw localError("PARAM_INVALID", `报价合计是成本合计的 ${(totalSale / totalCost).toFixed(1)} 倍,超出售价能存的利润率上限(999.99%)。`
416
+ + "请核对明细里的成本价(costPrice)是否填错。");
417
+ }
418
+ return rate;
419
+ }
420
+ /**
421
+ * 报价单草稿的纯计算部分(不碰网络,便于单测口径)。
422
+ *
423
+ * 口径必须与前端 `add-quotation.vue#calculate` 一致,否则界面一重算金额就变:
424
+ *
425
+ * 单台成本 unitCost = 整机 amount + Σ配件 amount(拆解项是负数)
426
+ * 整机单价 unitPrice = unitCost × (1 + 利润率/100) ← 界面的算法
427
+ * 行报价 salePrice = unitPrice × 整机数量
428
+ * 单据合计 totalAmount = Σ 各父行 salePrice(配件不单独计,否则重复)
429
+ *
430
+ * 整机行的 `quantity` 恒为 1、`price` 是单台成本 —— 与界面落库的数据形状一致。
431
+ * 台数放在 `unitCount`。旧写法「quantity 当台数」仍然接受:没给 unitCount 时取 quantity。
432
+ */
433
+ export function buildQuotationPlan(args) {
434
+ const rawItems = asArray(args["items"]);
435
+ if (rawItems.length === 0)
436
+ throw localError("PARAM_INVALID", "至少需要一条报价明细");
437
+ const warnings = [
438
+ "报价单不关联客户主数据,客户名称填错不会报错,也不会被系统纠正——请让用户核对全称。",
439
+ ];
440
+ // productId 是前端表格的 row-key,也是「配件挂在哪个整机下」的键(配件 parentId = 父行 productId)。
441
+ // 同一单里重复时,前端会拒绝给这两个父行挂配件,配件等于白填;所以显式传的重复值直接拒绝,
442
+ // 让调用方去掉 productId 由这里分配,而不是悄悄改一个(改了用户也对不上是哪一行)。
443
+ const usedIds = new Set();
444
+ const idBase = Date.now() * 100;
445
+ let idSeq = 0;
446
+ const nextProductId = () => {
447
+ let id = idBase + ++idSeq;
448
+ while (usedIds.has(String(id)))
449
+ id = idBase + ++idSeq;
450
+ const value = String(id);
451
+ usedIds.add(value);
452
+ return value;
453
+ };
454
+ // productId 一律走字符串(见 idText 注释):查询工具返回的 Long 是字符串,19 位雪花转 number 会静默改值。
455
+ const takeProductId = (raw, label) => {
456
+ // JSON number 超 2^53 在解析阶段就丢了末几位,再转字符串只会得到另一串数字,必须当场拒绝。
457
+ // 只拦「超出安全整数范围」的数值:1.5 这类小数交给后面的正整数校验,别误报成精度溢出。
458
+ if (typeof raw === "number" && Math.abs(raw) > Number.MAX_SAFE_INTEGER) {
459
+ throw localError("PARAM_INVALID", `${label}.productId 传成了数字 ${raw},已超出 2^53:JSON 数字在解析时就会丢掉末几位,`
460
+ + "落库会变成另一个 ID。请改传字符串(把查询结果里的 id 原样带引号传入);也可以不传,由系统分配。");
461
+ }
462
+ const id = idText(raw);
463
+ if (!id)
464
+ return nextProductId();
465
+ // 0 是「顶层行」的标记(parentId === "0"),拿它当 productId 会让这一行的配件挂不上去
466
+ if (!/^\d+$/.test(id) || Number(id) <= 0) {
467
+ throw localError("PARAM_INVALID", `${label}.productId 必须是正整数(收到「${id}」);也可以不传,由系统分配。`);
468
+ }
469
+ if (usedIds.has(id)) {
470
+ throw localError("PARAM_INVALID", `${label}.productId 与前面的明细重复(${id}):报价单靠 productId 把配件挂到整机下,`
471
+ + "重复会让这一行一个配件都挂不上。要报两台同型号,请去掉 productId 由系统分配。");
472
+ }
473
+ usedIds.add(id);
474
+ return id;
475
+ };
476
+ const groups = rawItems.map((raw, index) => {
477
+ const item = asRecord(raw);
478
+ const label = `items[${index}]`;
479
+ const name = needText(item["name"], `${label}.name`);
480
+ const explicitCount = numeric(item["unitCount"]);
481
+ const quantity = numeric(item["quantity"]);
482
+ const unitCount = explicitCount ?? quantity ?? 1;
483
+ // 整机台数落库是 unit_count(int):Jackson 默认按 intValue() 截断(1.5 存成 1),落库台数就和报价合计对不上了。
484
+ // 按吨/小数计量的物料请写在配件(parts)的 quantity 上,那一列是 decimal,支持小数。
485
+ if (!Number.isInteger(unitCount) || unitCount <= 0) {
486
+ throw localError("PARAM_INVALID", `明细「${name}」的整机数量(unitCount / quantity)必须是正整数,收到 ${unitCount}:`
487
+ + "海竣信息系统的整机数量(unit_count)是整数字段,小数会被截断(1.5 台存成 1 台,台数少算),"
488
+ + "落库台数就和报价合计对不上了。若这条是可按吨/小数计量的物料,请把数量写进它的 parts[].quantity。");
489
+ }
490
+ if (explicitCount !== undefined && quantity !== undefined
491
+ && Math.abs(explicitCount - quantity) >= 0.000001) {
492
+ warnings.push(`${name}同时给了 quantity=${quantity} 与 unitCount=${explicitCount}:`
493
+ + `已按整机数量 ${explicitCount} 台落库。整机行的 quantity 恒为 1(成本单价按单台口径),`
494
+ + "两处都填台数会让成本被算两遍。");
495
+ }
496
+ const costPrice = numeric(item["costPrice"]);
497
+ const salePrice = numeric(item["salePrice"]);
498
+ const productId = takeProductId(item["productId"], label);
499
+ let partsCost = 0;
500
+ let partsMissing = 0;
501
+ let removeCount = 0;
502
+ const parts = asArray(item["parts"]).map((rawPart, partIndex) => {
503
+ const part = asRecord(rawPart);
504
+ const partLabel = `${label}.parts[${partIndex}]`;
505
+ const action = text(part["action"]);
506
+ if (action !== "add" && action !== "remove") {
507
+ throw localError("PARAM_INVALID", `${partLabel}.action 只能是 add(加装)或 remove(拆解),收到「${action}」`);
508
+ }
509
+ const count = numeric(part["quantity"]) ?? 1;
510
+ if (count <= 0) {
511
+ throw localError("PARAM_INVALID", `${partLabel}.quantity 必须传正数(加装/拆解由 action 决定正负),收到 ${count}`);
512
+ }
513
+ const partCost = numeric(part["costPrice"]);
514
+ if (partCost === undefined)
515
+ partsMissing += 1;
516
+ // 界面口径:加装 +N、拆解 −N,amount = quantity × price(拆解项为负)。
517
+ // 缺成本价时按 0 落 price/amount(与界面「配件售价固定 0」同形):
518
+ // 留 null 会让报价单在界面里存不了(canSave 要求每行 price 非空),等于把人挡在门外。
519
+ const signed = action === "add" ? count : -count;
520
+ const amount = money(signed * (partCost ?? 0));
521
+ partsCost = money(partsCost + amount);
522
+ if (action === "remove")
523
+ removeCount += 1;
524
+ return compact({
525
+ parentId: String(productId),
526
+ productId: nextProductId(),
527
+ name: needText(part["name"], `${partLabel}.name`),
528
+ spec: text(part["spec"]),
529
+ specDetail: text(part["specDetail"]),
530
+ unit: text(part["unit"]),
531
+ quantity: signed,
532
+ price: partCost ?? 0,
533
+ amount,
534
+ remark: text(part["remark"]),
535
+ });
536
+ });
537
+ if (partsMissing > 0) {
538
+ warnings.push(`${name}有 ${partsMissing} 个配件没给成本价(costPrice):成本按 ¥0 落库,`
539
+ + "整机成本合计会偏低,按利润率定价时整机单价也会偏低(拆解项则少减)。"
540
+ + "配件成本请从市场动态 / 库存 / 标准产品里同一配件的 unitPrice 取,确实没有才传 0,并让用户核对。");
541
+ }
542
+ if (parts.length > 0 && costPrice !== undefined) {
543
+ warnings.push(`${name}是拆改配(${parts.length} 项配件):成本按「整机成本 + Σ配件成本(拆解为负)」计,`
544
+ + "整机成本取的是**改配前整机**的 unitPrice;若来源记录是改配后的整机价,再叠加配件会重复计成本,请核对。");
545
+ }
546
+ if (removeCount > 0) {
547
+ warnings.push(`${name}有 ${removeCount} 项拆解配件:报价单打印与导出只把**加装**配件拼进整机「规格详情」,`
548
+ + "拆解项不会出现在打印单上,只体现在成本里。要让客户看到拆了什么,只能在海竣信息系统里手工补。");
549
+ }
550
+ const parentCost = costPrice === undefined ? undefined : money(costPrice);
551
+ if (parts.length > 0 && parentCost === undefined) {
552
+ throw localError("PARAM_INVALID", `明细「${name}」带 ${parts.length} 个拆改配配件,但没给整机成本价(costPrice):`
553
+ + "整机行的 amount 会落成空值,海竣信息系统打印/导出这张报价单时会把子配件成本加到空值上"
554
+ + "(NullPointerException),界面也会因为该行 price 为空而无法保存。"
555
+ + "整机成本请取来源记录(市场动态 / 库存 / 标准产品)的 unitPrice;"
556
+ + "确实拿不到成本时传 0(按 ¥0 计,报价仍可正常保存)。");
557
+ }
558
+ return {
559
+ name,
560
+ unitCount,
561
+ unitCost: parentCost === undefined ? undefined : money(parentCost + partsCost),
562
+ costComplete: parentCost !== undefined && partsMissing === 0,
563
+ salePrice,
564
+ parent: compact({
565
+ // 前端只把 parentId === "0" 当顶层行,NULL 会显示成空明细
566
+ parentId: "0",
567
+ productId,
568
+ name,
569
+ spec: text(item["spec"]),
570
+ specDetail: text(item["specDetail"]),
571
+ unit: text(item["unit"]),
572
+ // 整机行:成本数量恒 1,price 是单台成本,amount = 1 × price
573
+ quantity: 1,
574
+ price: parentCost,
575
+ amount: parentCost,
576
+ vendor: text(item["vendor"]),
577
+ remark: text(item["remark"]),
578
+ }),
579
+ parts,
580
+ };
581
+ });
582
+ const pricedGroups = groups.filter((group) => group.salePrice !== undefined);
583
+ const allPriced = pricedGroups.length === groups.length;
584
+ const parentCostMissing = groups.filter((group) => group.unitCost === undefined).length;
585
+ const costComplete = groups.every((group) => group.costComplete);
586
+ // 台账口径:成本要按台数放大(配件成本是「每台」的),否则多台报价的利润率会被算高
587
+ const costTotal = costComplete
588
+ ? money(groups.reduce((sum, group) => sum + Number(group.unitCost ?? 0) * group.unitCount, 0))
589
+ : undefined;
590
+ // 报价合计:和界面的「销售报价 = 整机单价 × 整机数量」同源
591
+ const totalSale = allPriced
592
+ ? money(groups.reduce((sum, group) => sum + Number(group.salePrice ?? 0) * group.unitCount, 0))
593
+ : undefined;
594
+ // 利润率与报价必须自洽,否则界面一重算金额就变(见 quoteProfitRate 注释)
595
+ const requestedRate = numeric(args["profitRate"]);
596
+ let profitRate = requestedRate ?? 15;
597
+ if (!allPriced) {
598
+ const missing = groups.length - pricedGroups.length;
599
+ warnings.push(`有 ${missing} 行没给报价(salePrice):已按「单台成本 × (1 + ${profitRate}%)」定价`
600
+ + `${requestedRate === undefined ? "(默认利润率 15%)" : ""}。请核对成本价是否准确。`);
601
+ // 这一支跳过了后面的「按整单利润率重算」检查,但界面一编辑就会整表重算,
602
+ // 所以已给报价的行、缺成本价的行同样有「金额会变」的风险,必须单独提示。
603
+ const deviated = groups.filter((group) => {
604
+ if (group.salePrice === undefined || group.unitCost === undefined)
605
+ return false;
606
+ return Math.abs(money(group.unitCost * (1 + profitRate / 100)) - group.salePrice) >= 0.01;
607
+ }).length;
608
+ if (deviated > 0) {
609
+ warnings.push(`这 ${deviated} 行已给报价,但与「单台成本 × (1 + ${profitRate}%)」不一致:`
610
+ + "报价单只有整单一个利润率,用户只要触发重算(改数量、改利润率),界面就会按这个利润率"
611
+ + "重写这些行的整机单价,报价金额会变。");
612
+ }
613
+ if (parentCostMissing > 0) {
614
+ warnings.push(`有 ${parentCostMissing} 行没给整机成本价(costPrice):成本小计(amount)是空的,`
615
+ + "用户触发重算时界面会把整机单价算成 ¥0.00(成本为 0),报价金额会变。");
616
+ }
617
+ }
618
+ else if (parentCostMissing > 0) {
619
+ warnings.push(`有 ${parentCostMissing} 行没给成本价(costPrice),无法按报价反算利润率:已按 ${profitRate}% 落库。`
620
+ + `用户打开报价单后只要触发重算(改数量、改利润率),界面就会把这些行的整机单价改成`
621
+ + `「行成本合计 × (1 + ${profitRate}%)」,报价金额会变。`);
622
+ warnings.push(`这 ${parentCostMissing} 行的成本小计(amount)是空的,报价单里的利润参考会偏高。`);
623
+ }
624
+ else if (costTotal === undefined) {
625
+ // 整机成本都给了,只是有配件缺成本价:成本合计不完整,同样不能反算
626
+ warnings.push("有配件没给成本价,成本合计不完整,无法按「报价合计 ÷ 成本合计」反算利润率:"
627
+ + `已按 ${profitRate}% 落库。用户打开报价单后只要触发重算,界面就会按这个利润率重算整机单价,报价金额会变。`);
628
+ }
629
+ else if (costTotal <= 0) {
630
+ // 赠品/试机(成本全 0),或成本价填错成负数:除不了,反算不出利润率
631
+ warnings.push(`成本合计是 ¥${moneyText(costTotal)},无法按「报价合计 ÷ 成本合计」反算利润率:`
632
+ + `已按 ${profitRate}% 落库。用户打开报价单只要触发重算(改数量、改利润率),`
633
+ + `界面就会把每行整机单价改成「行成本合计 × (1 + ${profitRate}%)」——`
634
+ + `成本为 0 的行会直接变成 ¥0.00,总金额从 ¥${moneyText(Number(totalSale ?? 0))} `
635
+ + `变成 ¥${moneyText(money(costTotal * (1 + profitRate / 100)))}。`);
636
+ }
637
+ else {
638
+ const derived = quoteProfitRate(Number(totalSale ?? 0), costTotal);
639
+ const recomputed = money(costTotal * (1 + derived / 100));
640
+ profitRate = derived;
641
+ if (requestedRate !== undefined && Math.abs(requestedRate - derived) >= 0.01) {
642
+ warnings.push(`用户给的利润率 ${requestedRate}% 与「报价合计 ÷ 成本合计 − 1」算出的 ${derived}% 不一致:`
643
+ + `已按 ${derived}% 落库,否则打开报价单改一下数量,界面就会把合计金额从 `
644
+ + `¥${moneyText(Number(totalSale ?? 0))} 改成 ¥${moneyText(money(costTotal * (1 + requestedRate / 100)))}。`);
645
+ }
646
+ if (Math.abs(recomputed - Number(totalSale ?? 0)) >= 0.01) {
647
+ warnings.push(`利润率只能存两位小数,界面重算后的合计金额是 ¥${moneyText(recomputed)},`
648
+ + `与报价合计差 ¥${moneyText(money(Number(totalSale ?? 0) - recomputed))}。`);
649
+ }
650
+ if (derived < 0) {
651
+ warnings.push(`算出的利润率是负数(${derived}%):报价低于成本合计。请让用户确认这不是成本价填错了。`);
652
+ }
653
+ // 界面按行重算:整机单价 = 行成本合计 × (1 + 利润率)。只有逐行都对齐这个公式,
654
+ // 用户一编辑单价才不动;不一致(各行毛利率不同、成本为 0 的行)就会被重分配。
655
+ const shifted = groups.filter((group) => {
656
+ const lineUnit = money(Number(group.unitCost ?? 0) * (1 + derived / 100));
657
+ return Math.abs(lineUnit - Number(group.salePrice ?? 0)) >= 0.01;
658
+ }).length;
659
+ if (shifted > 0) {
660
+ warnings.push(`这 ${shifted} 行按整单利润率 ${derived}% 重算后单价会变(整单合计不变):`
661
+ + "报价单只有整单一个利润率,界面是逐行按它重算的,"
662
+ + "所以各行毛利率不同的报价落库后,单行单价无法原样保留。"
663
+ + "要保留各行自己的定价,只能在海竣信息系统界面里手工改。");
664
+ }
665
+ }
666
+ let totalAmount = 0;
667
+ let sort = 0;
668
+ const items = [];
669
+ for (const group of groups) {
670
+ // 给了报价就用报价(保住用户口径);没给才按成本 × (1 + 利润率) 定价,与界面重算同源
671
+ const unitPrice = group.salePrice
672
+ ?? (group.unitCost === undefined
673
+ ? undefined
674
+ : money(group.unitCost * (1 + profitRate / 100)));
675
+ if (unitPrice === undefined) {
676
+ throw localError("PARAM_INVALID", `明细「${group.name}」既没给报价(salePrice)也没给成本价(costPrice),无法定价。`);
677
+ }
678
+ const lineSale = money(unitPrice * group.unitCount);
679
+ totalAmount = money(totalAmount + lineSale);
680
+ // sort 是「父行 + 其配件」共用的连续序列,界面按它升序还原顺序
681
+ items.push({
682
+ ...group.parent,
683
+ sort: ++sort,
684
+ unitCount: group.unitCount,
685
+ // 行级 unitPrice/salePrice 是「整机单价 / 整行报价」,只有 outPrice 也才是对客单价——
686
+ // 报价单转销售单时前端取的就是 outPrice(product/index.vue:288)
687
+ unitPrice,
688
+ salePrice: lineSale,
689
+ outPrice: unitPrice,
690
+ });
691
+ for (const part of group.parts) {
692
+ items.push({ ...part, sort: ++sort });
693
+ }
694
+ }
695
+ const preSale = compact({
696
+ name: needText(args["name"], "name"),
697
+ customer: needText(args["customer"], "customer"),
698
+ contact: text(args["contact"]),
699
+ contactTel: text(args["contactTel"]),
700
+ customerAddress: text(args["customerAddress"]),
701
+ totalAmount,
702
+ // 与「成本合计 × (1 + 利润率)」同源:见 quoteProfitRate
703
+ profitRate,
704
+ remark: text(args["remark"]),
705
+ });
706
+ return { preSale, items, totalAmount, warnings };
707
+ }
708
+ function registerQuotation(server, ctx) {
709
+ server.registerTool("sems_prepare_quotation", {
710
+ title: "起草报价单(不写库)",
711
+ description: "整理报价单草稿,**不写入海竣信息系统**。报价单的客户字段是**名称字符串**(`customer`),"
712
+ + "不是 ID——它不挂客户主数据,这是与销售单的关键区别。"
713
+ + QUOTE_SOURCE_RULE
714
+ + "写法:整机行的 `parts[]` 每项用 action 区分加装(add)/拆解(remove),成本并入整机单价;"
715
+ + "整机行的 quantity 恒为 1,台数写在 unitCount。",
716
+ inputSchema: {
717
+ name: z.string().min(1).describe("报价单名称"),
718
+ customer: z.string().min(1).describe("客户名称(字符串,报价单不关联客户主数据)"),
719
+ contact: z.string().optional().describe("联系人"),
720
+ contactTel: z.string().optional(),
721
+ customerAddress: z.string().optional(),
722
+ items: z.array(QUOTE_ITEM).min(1).describe("报价明细,至少一条"),
723
+ profitRate: z.coerce
724
+ .number()
725
+ .optional()
726
+ .describe("利润率(百分数,如 15 表示 15%)。全部行都给了 salePrice 且成本价齐全时,会按"
727
+ + "「报价合计 ÷ 成本合计 − 1」反算并覆盖本参数(不一致会在 warnings 里提示);"
728
+ + "有行没给 salePrice 时才用本参数定价,默认 15"),
729
+ remark: z.string().optional(),
730
+ },
731
+ annotations: { readOnlyHint: true },
732
+ }, wrap(ctx, "sems_prepare_quotation", async (args) => {
733
+ const { preSale, items, totalAmount, warnings } = buildQuotationPlan(args);
734
+ const body = { preSale, preSaleDetails: items };
735
+ const parentCount = items.filter((line) => line["parentId"] === "0").length;
736
+ const partCount = items.length - parentCount;
737
+ const draft = ctx.drafts.create({
738
+ tool: "sems_prepare_quotation",
739
+ call: { path: "/invoicing/pre-sale", body },
740
+ digest: digestOf(body),
741
+ summary: `报价单草稿:客户「${String(preSale["customer"])}」,`
742
+ + (partCount > 0
743
+ ? `${parentCount} 项整机(含 ${partCount} 项拆改配配件),`
744
+ : `${items.length} 项明细,`)
745
+ + `报价合计 ¥${moneyText(totalAmount)}(利润率 ${String(preSale["profitRate"])}%)。尚未写入海竣信息系统。`,
746
+ warnings,
747
+ });
748
+ return replyOf(draft, "sems_commit_quotation");
749
+ }));
750
+ server.registerTool("sems_commit_quotation", {
751
+ title: "提交报价单(写库)",
752
+ description: "把 sems_prepare_quotation 产出的草稿写入海竣信息系统。必须传回 draftId 与 digest。",
753
+ inputSchema: {
754
+ draftId: z.string().min(1),
755
+ digest: z.string().min(1),
756
+ },
757
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
758
+ }, wrap(ctx, "sems_commit_quotation", async (args) => commitDraft(ctx, "sems_prepare_quotation", args, "/invoicing/pre-sale", "报价单已创建")));
759
+ }
760
+ // ── 合同与关联 ──────────────────────────────────────────────
761
+ /** `ContractTypeEnum` 的取值;合同类型决定编号前缀,传错会拿到错的合同号。 */
762
+ export const CONTRACT_TYPE = z.enum(["销售合同", "采购合同"]);
763
+ /** 合同类型在库里是 tinyint(1 目录 / 2 采购 / 3 销售),传中文会被反序列化直接打回。 */
764
+ const CONTRACT_TYPE_VALUE = { 采购合同: 2, 销售合同: 3 };
765
+ /** 中文合同类型 → 库里的 tinyint。建合同的入口都走这里,避免各写一份映射写漏。 */
766
+ export function contractTypeValue(raw) {
767
+ const name = needText(raw, "contractType");
768
+ const value = CONTRACT_TYPE_VALUE[name];
769
+ if (value === undefined) {
770
+ throw localError("PARAM_INVALID", `合同类型只能是「销售合同」或「采购合同」,收到 ${name}`);
771
+ }
772
+ return value;
773
+ }
774
+ /**
775
+ * 组装 `si_contract` 的请求体。
776
+ *
777
+ * `Contract` 实体只有 contract_no / customer_name / project_name / attachments /
778
+ * contract_type / status / remark / salesman 这些列。写成 contractName、amount、signTime
779
+ * 不会报错(Jackson 忽略未知字段),但那几列根本不存在,等于没写。
780
+ */
781
+ export function buildContractBody(input) {
782
+ return compact({
783
+ contractType: input.contractType,
784
+ parentId: input.parentId ?? 0,
785
+ customerName: input.customerName,
786
+ projectName: input.projectName,
787
+ remark: input.remark,
788
+ attachments: input.attachments === undefined || input.attachments.length === 0
789
+ ? undefined
790
+ : input.attachments,
791
+ });
792
+ }
793
+ /**
794
+ * 上传接口的返回值 → `Contract.attachments` 的元素。
795
+ *
796
+ * 是前端 `contract-files.vue#parseFileList` 所需字段的**子集**:fileType / uploader /
797
+ * storageType 由前端兜默认值(storageType 兜「远程存储」),这里只给能确定的四项。
798
+ */
799
+ export function contractAttachment(uploaded) {
800
+ return compact({
801
+ fileName: text(uploaded["filename"]),
802
+ filePath: text(uploaded["url"]),
803
+ fileSize: numeric(uploaded["size"]),
804
+ uploadTime: nowText().slice(0, 10),
805
+ });
806
+ }
807
+ /** 库里的 `datetime` 是 `yyyy-MM-dd HH:mm:ss`(本地时区),转毫秒用于比较。 */
808
+ function dbTime(value) {
809
+ const raw = text(value);
810
+ if (!raw)
811
+ return undefined;
812
+ const ms = Date.parse(raw.replace(" ", "T"));
813
+ return Number.isNaN(ms) ? undefined : ms;
814
+ }
815
+ /** 客户端与服务器时钟允许的偏差:回查时把「提交时刻」往前放宽这么多。 */
816
+ const CLOCK_SKEW_MS = 10 * 60 * 1000;
817
+ /** 合同回查的每页条数;也是列表接口实际能返回的上限。 */
818
+ const CONTRACT_PAGE_SIZE = 50;
819
+ /**
820
+ * 新建合同后回查刚写入的那一条。
821
+ *
822
+ * `/invoicing/contract/page` 不带 order by(`ContractController#getContractPage`),
823
+ * MySQL 通常按主键升序返回——客户名下超过一页时,刚建的那张在**最后一页**,
824
+ * 所以要按 `total` 算出末页再取一次。取到后本地按 createTime 倒排,并要求创建时间
825
+ * 不早于本次提交(放宽一个时钟偏差窗口)。取不到就返回空对象:
826
+ * 宁可不报编号,也不报一个错号。
827
+ */
828
+ export async function findNewestContract(ctx, customerName, submittedAt) {
829
+ const since = submittedAt ?? new Date();
830
+ const floor = since.getTime() - CLOCK_SKEW_MS;
831
+ const pad = (n) => String(n).padStart(2, "0");
832
+ const dayStart = `${since.getFullYear()}-${pad(since.getMonth() + 1)}-${pad(since.getDate())} 00:00:00`;
833
+ const query = { customerName, current: 1, size: CONTRACT_PAGE_SIZE, createTimeBegin: dayStart };
834
+ try {
835
+ const listed = await ctx.client.call({
836
+ method: "GET",
837
+ path: "/invoicing/contract/page",
838
+ query,
839
+ });
840
+ const page = asRecord(unwrapSems(listed.data));
841
+ let rows = asArray(page["records"]);
842
+ const total = numeric(page["total"]) ?? rows.length;
843
+ if (total > CONTRACT_PAGE_SIZE) {
844
+ // 没有 order by,只能按末页兜住:新单一定在最后一页
845
+ const tail = await ctx.client.call({
846
+ method: "GET",
847
+ path: "/invoicing/contract/page",
848
+ query: { ...query, current: Math.ceil(total / CONTRACT_PAGE_SIZE) },
849
+ });
850
+ rows = asArray(asRecord(unwrapSems(tail.data))["records"]);
851
+ }
852
+ const newest = rows
853
+ .map(asRecord)
854
+ .filter((row) => text(row["customerName"]).trim() === customerName.trim())
855
+ .filter((row) => {
856
+ // 没有创建时间的记录无法自证是刚建的,排除
857
+ const at = dbTime(row["createTime"]);
858
+ return at !== undefined && at >= floor;
859
+ })
860
+ .sort((a, b) => {
861
+ const left = dbTime(a["createTime"]) ?? 0;
862
+ const right = dbTime(b["createTime"]) ?? 0;
863
+ if (left !== right)
864
+ return right - left;
865
+ // 同一秒建两张时按主键兜底:雪花不能转 number,补齐长度后按字符串比大小
866
+ const lid = String(a["id"] ?? "").padStart(20, "0");
867
+ const rid = String(b["id"] ?? "").padStart(20, "0");
868
+ return lid === rid ? 0 : lid > rid ? -1 : 1;
869
+ })[0];
870
+ return newest === undefined ? {} : pickCreated({ contract: newest });
871
+ }
872
+ catch {
873
+ // 回查失败不影响建单结果,只是拿不到编号
874
+ return {};
875
+ }
876
+ }
877
+ function registerContract(server, ctx) {
878
+ server.registerTool("sems_create_contract", {
879
+ title: "新建合同记录(写库)",
880
+ description: "在海竣信息系统里新建一条合同记录。**这是直接写库,没有草稿阶段**,调用前必须先向用户确认"
881
+ + "客户全称与合同类型。合同编号由海竣信息系统自动生成(销售/采购前缀不同)。"
882
+ + "新建后可用 sems_relate_contract 关联到销售单或采购单。",
883
+ inputSchema: {
884
+ customerName: z.string().min(1).describe("客户全称(海竣信息系统强制必填,用于生成合同编号)"),
885
+ contractType: CONTRACT_TYPE.describe("合同类型,决定编号前缀"),
886
+ projectName: z.string().optional().describe("合同名称(列表里的「合同名称」列)"),
887
+ parentId: z.coerce.number().int().min(0).optional().describe("所属目录 ID,默认 0(根目录)"),
888
+ remark: z.string().optional(),
889
+ },
890
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
891
+ }, wrap(ctx, "sems_create_contract", async (args) => {
892
+ const contractType = contractTypeValue(args["contractType"]);
893
+ // 客户名带空格会导致编号能生成、但按名称查关联单时找不到
894
+ const customerName = needText(args["customerName"], "customerName").trim();
895
+ const submittedAt = new Date();
896
+ const body = buildContractBody({
897
+ customerName,
898
+ contractType,
899
+ projectName: text(args["projectName"]),
900
+ parentId: numeric(args["parentId"]),
901
+ remark: text(args["remark"]),
902
+ });
903
+ const response = await ctx.client.call({ method: "POST", path: "/invoicing/contract", body });
904
+ const data = unwrapSems(response.data);
905
+ ensureSaved(data, "新建合同");
906
+ // 后端 save 只返回布尔值,编号得自己回查一次,否则「请回报编号」就成了空话
907
+ let record = pickCreated(data);
908
+ if (text(record["contractNo"]) === "") {
909
+ record = await findNewestContract(ctx, customerName, submittedAt);
910
+ }
911
+ const gotNo = text(record["contractNo"]) !== "";
912
+ return {
913
+ created: true,
914
+ message: `合同已创建(${text(args["contractType"])},客户「${customerName}」)`,
915
+ record,
916
+ note: gotNo
917
+ ? "合同编号由海竣信息系统按类型前缀自动生成,请把编号回报给用户。"
918
+ + "如果要把它和某张销售单/采购单关联,用 sems_relate_contract。"
919
+ : "合同已写入,但编号没能回查到(可能刚建、列表接口还没返回)。"
920
+ + "请让用户到海竣信息系统合同列表里查看编号,不要替用户编一个。",
921
+ };
922
+ }));
923
+ server.registerTool("sems_relate_contract", {
924
+ title: "合同关联单据(写库)",
925
+ description: "把一张销售单或采购单关联到合同上,合同状态会被置为「已关联」。"
926
+ + "重复关联同一张单是幂等的,不会产生副作用。",
927
+ inputSchema: {
928
+ contractId: z.coerce.number().int().positive().describe("合同 ID"),
929
+ orderType: z.enum(["sale", "purchase"]).describe("单据类型:sale=销售单,purchase=采购单"),
930
+ orderId: z.coerce.number().int().positive().describe("单据 ID"),
931
+ },
932
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true },
933
+ }, wrap(ctx, "sems_relate_contract", async (args) => {
934
+ const contractId = needNumber(args["contractId"], "contractId");
935
+ const orderId = needNumber(args["orderId"], "orderId");
936
+ const orderType = needText(args["orderType"], "orderType");
937
+ if (orderType !== "sale" && orderType !== "purchase") {
938
+ throw localError("PARAM_INVALID", `orderType 只能是 sale 或 purchase,收到 ${orderType}`);
939
+ }
940
+ // 后端是 map.get("orderType").toString(),缺字段会 500 而不是给提示,所以这里先扣死
941
+ const response = await ctx.client.call({
942
+ method: "POST",
943
+ path: `/invoicing/contract/relate/${contractId}`,
944
+ body: { orderType, orderId },
945
+ });
946
+ ensureSaved(unwrapSems(response.data), "合同关联");
947
+ return {
948
+ related: true,
949
+ message: `已把${orderType === "sale" ? "销售单" : "采购单"} ${orderId} 关联到合同 ${contractId}。`,
950
+ };
951
+ }));
952
+ }
953
+ // ── 附件上传 ────────────────────────────────────────────────
954
+ /** 20MB 上限:更大的文件走 SEMS 网页上传,不经过对话链路。 */
955
+ const MAX_UPLOAD_BYTES = 20 * 1024 * 1024;
956
+ const MIME_BY_EXT = {
957
+ ".pdf": "application/pdf",
958
+ ".png": "image/png",
959
+ ".jpg": "image/jpeg",
960
+ ".jpeg": "image/jpeg",
961
+ ".gif": "image/gif",
962
+ ".webp": "image/webp",
963
+ ".doc": "application/msword",
964
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
965
+ ".xls": "application/vnd.ms-excel",
966
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
967
+ ".zip": "application/zip",
968
+ ".txt": "text/plain",
969
+ };
970
+ /** 文件名要进 HTTP 头,必须去掉能把头拆开的字符。 */
971
+ function safeFilename(raw) {
972
+ return raw.replace(/["\r\n\\]/g, "_").slice(0, 200) || "upload.bin";
973
+ }
974
+ function buildMultipart(field, filename, contentType, bytes) {
975
+ const boundary = `----sems${randomBytes(8).toString("hex")}`;
976
+ const head = Buffer.from(`--${boundary}\r\n`
977
+ + `Content-Disposition: form-data; name="${field}"; filename="${filename}"\r\n`
978
+ + `Content-Type: ${contentType}\r\n\r\n`, "utf8");
979
+ const tail = Buffer.from(`\r\n--${boundary}--\r\n`, "utf8");
980
+ return {
981
+ body: Buffer.concat([head, bytes, tail]),
982
+ contentType: `multipart/form-data; boundary=${boundary}`,
983
+ };
984
+ }
985
+ function registerUpload(server, ctx) {
986
+ server.registerTool("sems_upload_file", {
987
+ title: "上传附件到海竣信息系统",
988
+ description: "把本机文件上传到海竣信息系统附件库。传本地绝对路径(sems-mcp 跑在用户电脑上,能直接读文件),"
989
+ + "返回可写进单据附件的 URL。上传本身不改任何业务数据。",
990
+ inputSchema: {
991
+ filePath: z.string().min(1).describe("本机文件的绝对路径"),
992
+ filename: z.string().optional().describe("上传后在海竣信息系统里显示的文件名,默认用原文件名"),
993
+ },
994
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },
995
+ }, wrap(ctx, "sems_upload_file", async (args) => uploadLocalFile(ctx, needText(args["filePath"], "filePath"), text(args["filename"]) || undefined)));
996
+ }
997
+ /**
998
+ * 上传一个本机文件,返回 SEMS 的附件信息。复合编排工具也走这里,
999
+ * 避免「单文件上传」与「合同附件上传」各写一套 multipart 构造。
1000
+ */
1001
+ export async function uploadLocalFile(ctx, filePath, displayName) {
1002
+ let size;
1003
+ try {
1004
+ const stat = statSync(filePath);
1005
+ if (!stat.isFile())
1006
+ throw localError("PARAM_INVALID", `不是文件:${filePath}`);
1007
+ size = stat.size;
1008
+ }
1009
+ catch (err) {
1010
+ if (err instanceof ProxyError)
1011
+ throw err;
1012
+ throw localError("PARAM_INVALID", `读不到这个文件:${filePath}`);
1013
+ }
1014
+ if (size === 0)
1015
+ throw localError("PARAM_INVALID", "文件是空的,没有上传的必要。");
1016
+ if (size > MAX_UPLOAD_BYTES) {
1017
+ throw localError("PARAM_INVALID", `文件 ${(size / 1024 / 1024).toFixed(1)}MB 超过 20MB 上限。请压缩后重试,或让用户在海竣信息系统网页里直接上传。`);
1018
+ }
1019
+ const original = basename(filePath);
1020
+ const filename = safeFilename(displayName || original);
1021
+ const ext = extname(original).toLowerCase();
1022
+ const contentType = MIME_BY_EXT[ext] ?? "application/octet-stream";
1023
+ const bytes = readFileSync(filePath);
1024
+ const multipart = buildMultipart("file", filename, contentType, bytes);
1025
+ const response = await ctx.client.call({
1026
+ method: "POST",
1027
+ path: "/admin/sys-file/upload",
1028
+ raw: {
1029
+ bytes: multipart.body,
1030
+ contentType: multipart.contentType,
1031
+ // multipart 每次的 boundary 都不同,只能用约定占位符参与签名
1032
+ bodyHash: MULTIPART_BODY_HASH,
1033
+ },
1034
+ // 上传比普通查询慢,单独放宽
1035
+ timeoutMs: 120_000,
1036
+ });
1037
+ const data = asRecord(unwrapSems(response.data));
1038
+ // 没有 url 就等于「文件进了存储但拿不到地址」,对用户毫无用处。
1039
+ // 这种情况多发于 SEMS 的存储服务没配好,报「上传成功」会让人以为能用了。
1040
+ const url = text(data["url"]);
1041
+ if (!url) {
1042
+ throw new ProxyError("UPSTREAM_ERROR", 200, "上传接口没有返回文件 URL", false, `响应字段:${Object.keys(data).join("、") || "(空)"}。请让管理员检查海竣信息系统的文件存储配置。`);
1043
+ }
1044
+ return {
1045
+ uploaded: true,
1046
+ filename: data["originName"] ?? filename,
1047
+ url,
1048
+ size: data["size"] ?? size,
1049
+ note: "把这个 url 填进单据的附件字段即可。上传成功不代表已挂到任何单据上。",
1050
+ };
1051
+ }
1052
+ /** 在分页结果里按主键挑一条:proxy 只放行 page 系列,取不到单条详情接口。 */
1053
+ function pickById(payload, id) {
1054
+ const data = asRecord(unwrapSems(payload));
1055
+ return asArray(data["records"]).map(asRecord).find((r) => numeric(r["id"]) === id) ?? {};
1056
+ }
1057
+ /**
1058
+ * 按明细的库存记录/产品档案补齐「规格型号 / 详细配置 / 单位」并顺手带回档案。
1059
+ *
1060
+ * 这三项库里允许 NULL,但前端保存时逐行强制校验,少一项就是一张页面上打不开的单。
1061
+ * 有 `storageManageRecordId` 时**即使三项齐全也要查**:成本、仓库、BOM 只在库存记录里。
1062
+ */
1063
+ async function resolveItemTexts(ctx, item, index) {
1064
+ const notes = [];
1065
+ let spec = text(item.spec);
1066
+ let specDetail = text(item.specDetail);
1067
+ let unit = text(item.unit);
1068
+ const hasStock = item.storageManageRecordId !== undefined;
1069
+ const textsReady = Boolean(spec && specDetail && unit);
1070
+ // 有库存记录就必须查(成本、仓库、BOM 只在它里面);只有产品 ID 时,文本齐了就不必多打一次接口
1071
+ const shouldQuery = hasStock || (item.productId !== undefined && !textsReady);
1072
+ const row = `第 ${index + 1} 行明细「${text(item.name)}」`;
1073
+ let archive = {};
1074
+ let source = "";
1075
+ if (shouldQuery) {
1076
+ try {
1077
+ // proxy 白名单只放行 page 系列,按 id 直取会被拦,只能在分页结果里自己比对主键
1078
+ if (hasStock) {
1079
+ source = "库存记录";
1080
+ const res = await ctx.client.call({
1081
+ method: "GET",
1082
+ path: "/invoicing/storage-manage-record/page",
1083
+ query: {
1084
+ id: item.storageManageRecordId,
1085
+ current: 1,
1086
+ size: 5,
1087
+ // 可用量为 0 也会被后端过滤掉,而补规格跟有没有货无关
1088
+ includingEmpty: true,
1089
+ },
1090
+ });
1091
+ archive = pickById(res.data, item.storageManageRecordId);
1092
+ }
1093
+ else {
1094
+ source = "产品档案";
1095
+ const res = await ctx.client.call({
1096
+ method: "GET",
1097
+ path: "/invoicing/product/page",
1098
+ query: { name: text(item.name), current: 1, size: 20 },
1099
+ });
1100
+ archive = pickById(res.data, item.productId);
1101
+ }
1102
+ }
1103
+ catch (err) {
1104
+ // 补档案只是优化:查不到就走「让用户提供」的报错,别把整单卡在这里
1105
+ const reason = err instanceof ProxyError ? err.message : String(err);
1106
+ notes.push(`${row}读取${source}失败(${reason}),改用入参补齐。`);
1107
+ archive = {};
1108
+ source = "";
1109
+ }
1110
+ }
1111
+ if (source && Object.keys(archive).length === 0) {
1112
+ notes.push(`${row}的${source}没查到(可能不属于当前租户),规格与成本改用入参。`);
1113
+ }
1114
+ spec = spec || text(archive["spec"]);
1115
+ specDetail = specDetail || text(archive["specDetail"]);
1116
+ unit = unit || text(archive["unit"]);
1117
+ // si_product 没有 spec_detail 列,前端「选商品」也是拿 spec 当 specDetail
1118
+ if (!specDetail && spec && source === "产品档案")
1119
+ specDetail = spec;
1120
+ const missing = [];
1121
+ if (!spec)
1122
+ missing.push("规格型号(spec)");
1123
+ if (!specDetail)
1124
+ missing.push("详细配置(specDetail)");
1125
+ if (!unit)
1126
+ missing.push("单位(unit)");
1127
+ if (missing.length > 0) {
1128
+ throw localError("PARAM_INVALID", `${row}缺少${missing.join("、")}:海竣信息系统保存销售单时逐行校验这三项,且空串不算填过。`
1129
+ + `${notes.join("")}`
1130
+ + "请让用户提供,或带上 storageManageRecordId / productId 让系统按档案自动带出。");
1131
+ }
1132
+ return { spec, specDetail, unit, archive, source, notes };
1133
+ }
1134
+ /**
1135
+ * 默认税率(基础数据 tax-rate 里 `isDefault` 的那条)。
1136
+ * 取不到就按 0 处理——税率只影响税金与销售利润,不该因为它让整张单起不了草稿。
1137
+ */
1138
+ async function defaultTaxRate(ctx, warnings) {
1139
+ try {
1140
+ const res = await ctx.client.call({ method: "GET", path: "/invoicing/tax-rate/all" });
1141
+ const list = asArray(unwrapSems(res.data)).map(asRecord);
1142
+ const usable = list.filter((r) => r["delFlag"] !== "1");
1143
+ const hit = usable.find((r) => r["isDefault"] === true || r["isDefault"] === 1) ?? usable[0];
1144
+ const rate = numeric(hit?.["rate"]);
1145
+ if (rate !== undefined)
1146
+ return rate;
1147
+ warnings.push("没取到默认税率配置,明细税率按 0 处理,税金与销售利润会偏大。");
1148
+ }
1149
+ catch (err) {
1150
+ const reason = err instanceof ProxyError ? err.message : String(err);
1151
+ warnings.push(`读取默认税率失败(${reason}),明细税率按 0 处理,税金与销售利润会偏大。`);
1152
+ }
1153
+ return 0;
1154
+ }
1155
+ /** 保留 4 位小数:利润率在库里是 decimal(20,4)。 */
1156
+ function ratio(value) {
1157
+ return Math.round(value * 10000) / 10000;
1158
+ }
1159
+ /**
1160
+ * 姓名 → 路径段。
1161
+ *
1162
+ * 🔴 **不能 URL 编码**:proxy 用 ASGI 解码后的 `scope["path"]` 验签(见 `server/proxy/app/main.py`),
1163
+ * 客户端若先 `encodeURIComponent`,签名原文就与 proxy 重算的不一致,中文姓名必然 HMAC_INVALID。
1164
+ * 反过来 `/ ? # % \` 会改变路由或触发 proxy 的二次编码拦截,能提前判定的就在本地报错。
1165
+ */
1166
+ function userNameSegment(keyword) {
1167
+ if (/[/?#%\\]/.test(keyword) || keyword.length > 64) {
1168
+ throw localError("PARAM_INVALID", `姓名「${keyword}」含路径非法字符(/ ? # % \\)或超长,无法按姓名反查用户;`
1169
+ + "请直接提供 19 位 userId。");
1170
+ }
1171
+ return keyword;
1172
+ }
1173
+ /**
1174
+ * 姓名/用户名 → userId。
1175
+ *
1176
+ * `/admin/user/details/{keyword}`(`SysUserController#user`)同时按 username 与 name 查,
1177
+ * 查不到时返回空 data。**只有这种情况**返回空串,由调用方报「查不到这个人」;
1178
+ * proxy 超时、白名单 403、上游 500 一律原样抛出——把它们说成「用户不存在」会让调用方
1179
+ * 去改姓名,而真正的问题在网络或权限上。
1180
+ */
1181
+ async function userIdByName(ctx, keyword) {
1182
+ const res = await ctx.client.call({
1183
+ method: "GET",
1184
+ path: `/admin/user/details/${userNameSegment(keyword)}`,
1185
+ });
1186
+ return idText(asRecord(unwrapSems(res.data))["userId"]);
1187
+ }
1188
+ /**
1189
+ * 供复合编排工具复用的草稿构造。与 `sems_prepare_*` 工具走同一条路径,
1190
+ * 保证「单步起草」与「编排起草」产出的草稿结构完全一致。
1191
+ */
1192
+ export async function prepareSaleDraft(ctx, args) {
1193
+ // 名称带首尾空格会让后端「按名找客户」失配、进而多建一个重复客户
1194
+ const customerName = needText(args["customerName"], "customerName").trim();
1195
+ const items = asArray(args["items"]).map((raw) => asRecord(raw));
1196
+ if (items.length === 0)
1197
+ throw localError("PARAM_INVALID", "至少需要一条产品明细");
1198
+ const warnings = [];
1199
+ // 税率只影响税金与销售利润,先取一次(取不到按 0 并在告警里说明),别每行都查
1200
+ const taxRate = await defaultTaxRate(ctx, warnings);
1201
+ // 前端树节点键里的时间戳,同一批明细要各自唯一:取一次基准再按行号偏移
1202
+ const stamp = Date.now();
1203
+ const details = await Promise.all(items.map(async (item, index) => {
1204
+ const quantity = needNumber(item.quantity, "items[].quantity");
1205
+ const unitPrice = needNumber(item.unitPrice, "items[].unitPrice");
1206
+ const texts = await resolveItemTexts(ctx, item, index);
1207
+ // 并发补齐会让警告顺序跟着网络返回顺序跑,按明细顺序回收才稳定
1208
+ warnings.push(...texts.notes);
1209
+ const totalPrice = money(quantity * unitPrice);
1210
+ // 与界面口径一致:库存记录的 unit_price 是「销售成本」、original_buy_price 是「采购价」;
1211
+ // 定制产品没有档案,前端也是手填 buyPrice 并同时当作销售成本,所以入参优先
1212
+ const inputCost = numeric(item.buyPrice);
1213
+ const saleCost = inputCost ?? numeric(texts.archive["unitPrice"]) ?? 0;
1214
+ const companyCost = saleCost;
1215
+ const buyPrice = inputCost ?? numeric(texts.archive["originalBuyPrice"]) ?? 0;
1216
+ const tax = taxRate === 0 ? 0 : money(totalPrice * taxRate * 0.01);
1217
+ // 成本合计 = 成本单价 × 数量 + 税金;公司成本不计税(前端 company_profit 就是不含税的)
1218
+ const totalSaleCost = money(saleCost * quantity + tax);
1219
+ const totalCompanyCost = money(companyCost * quantity);
1220
+ const line = compact({
1221
+ // 顶层明细必须显式给字符串 "0":si_sale_detail.parent_id 无默认值,NULL 会让导出和前端回显把这些行全部丢掉
1222
+ parentId: "0",
1223
+ // 走库存的明细入参通常不带 productId,但销售详情的产品图片(SaleMapper 按 product_id 左连 si_product)
1224
+ // 与「按产品汇总利润」都只认这一列,所以档案里有就必须补上
1225
+ productId: item.productId ?? numeric(texts.archive["productId"]),
1226
+ name: needText(item.name, "items[].name"),
1227
+ spec: texts.spec,
1228
+ specDetail: texts.specDetail,
1229
+ unit: texts.unit,
1230
+ quantity,
1231
+ unitPrice,
1232
+ totalPrice,
1233
+ buyPrice,
1234
+ saleCost,
1235
+ companyCost,
1236
+ taxRate,
1237
+ tax,
1238
+ totalSaleCost,
1239
+ totalCompanyCost,
1240
+ saleProfit: money(totalPrice - totalSaleCost),
1241
+ companyProfit: money(totalPrice - totalCompanyCost),
1242
+ storageManageRecordId: item.storageManageRecordId,
1243
+ // 后端出库要按明细上的仓库定位;库存记录里带的就是它
1244
+ storageId: numeric(texts.archive["storageId"]),
1245
+ bom: text(texts.archive["bom"]),
1246
+ // 前端产品树的节点唯一键(拆改配挂靠靠它):库存产品 `库存ID-时间戳`,定制产品纯时间戳
1247
+ computedProductId: item.storageManageRecordId === undefined
1248
+ ? String(stamp + index)
1249
+ : `${item.storageManageRecordId}-${stamp + index}`,
1250
+ remark: text(item.remark),
1251
+ });
1252
+ if (item.storageManageRecordId === undefined) {
1253
+ warnings.push(`明细「${String(line["name"])}」没有 storageManageRecordId:海竣信息系统会当作定制产品,`
1254
+ + "**库存不扣减且不会报错**。"
1255
+ + (inputCost === undefined
1256
+ ? "成本按 0 计、利润会虚高——请用 buyPrice 传入成本单价。"
1257
+ : `成本已按 buyPrice=${inputCost} 计。`)
1258
+ + "如果这是现货销售,请先查库存补上该字段。");
1259
+ }
1260
+ return line;
1261
+ }));
1262
+ // 客户解析:按名字查一次,既用于避免重名误建,也用于补齐 si_sale 的必填列
1263
+ let customerId = numeric(args["customerId"]);
1264
+ let customer;
1265
+ {
1266
+ const found = await ctx.client.call({
1267
+ method: "GET",
1268
+ path: "/scm/customer/page",
1269
+ query: { customerName, size: 5 },
1270
+ });
1271
+ const records = asArray(asRecord(unwrapSems(found.data))["records"]).map(asRecord);
1272
+ // 库里客户名常带首尾空格,严格相等会匹配不上,档案里的省份/联系人跟着取不到
1273
+ const exact = records.filter((r) => text(r["customerName"]).trim() === customerName.trim());
1274
+ if (customerId !== undefined) {
1275
+ // 给了 ID 也要取档案:省份/城市/联系人在档案里,不传就会被后端写成 NULL
1276
+ customer = exact.find((r) => String(numeric(r["customerId"])) === String(customerId)) ?? exact[0];
1277
+ }
1278
+ else if (exact.length === 1) {
1279
+ customerId = numeric(exact[0]?.["customerId"]);
1280
+ customer = exact[0];
1281
+ if (customerId !== undefined) {
1282
+ warnings.push(`已按名称精确匹配到现有客户「${customerName}」(ID ${customerId})。`);
1283
+ }
1284
+ }
1285
+ else if (exact.length > 1) {
1286
+ warnings.push(`海竣信息系统里有 ${exact.length} 个同名客户「${customerName}」,无法确定用哪个。`
1287
+ + "建议先用 sems_query_partners 选定 customerId,否则提交后会**新建一个客户**。");
1288
+ }
1289
+ else {
1290
+ warnings.push(`海竣信息系统里没有名为「${customerName}」的客户:提交后后端会**自动新建这个客户**。`
1291
+ + "请让用户确认这是新客户,否则应改为已有客户的准确名称。");
1292
+ }
1293
+ }
1294
+ // si_sale 的 customer_province / customer_city / contact_name / contact_tel 是 NOT NULL 且无默认值。
1295
+ // 空串也不行:MyBatis-Plus 默认策略会把空串当「未设置」直接从 INSERT 里去掉,后端照样 500。
1296
+ // 只能给真值。优先级:用户显式传 > 客户档案。
1297
+ // 🔴 不再用当前登录账号兜底:拿自己的姓名手机号当客户的联系人是假数据,
1298
+ // 缺了就一次性列全向用户要,而不是替用户做主。
1299
+ const me = await ctx.userProfile.get();
1300
+ const customerField = (key) => text(customer?.[key]);
1301
+ const missingCustomerFields = [];
1302
+ const pick = (label, param, ...candidates) => {
1303
+ const hit = candidates.find((value) => value.length > 0);
1304
+ if (hit !== undefined)
1305
+ return hit;
1306
+ missingCustomerFields.push(`${label}(参数 ${param})`);
1307
+ return "";
1308
+ };
1309
+ const customerProvince = pick("客户省份", "customerProvince", text(args["customerProvince"]), customerField("province"));
1310
+ const customerCity = pick("客户城市", "customerCity", text(args["customerCity"]), customerField("city"));
1311
+ const contactName = pick("客户联系人", "contactName", text(args["contactName"]), customerField("contactName"));
1312
+ const contactTel = pick("联系人电话", "contactTel", text(args["contactTel"]), customerField("mobile1"));
1313
+ if (missingCustomerFields.length > 0) {
1314
+ // 一次报全:逐个报会逼用户改一轮跑一轮,四轮才建得起来
1315
+ throw localError("PARAM_INVALID", `海竣信息系统保存销售单时这 ${missingCustomerFields.length} 项客户信息必填,客户档案里没有:`
1316
+ + `${missingCustomerFields.join("、")}。`
1317
+ + "请向用户询问这几项,拿到后带上同名参数重新起草(也可用 sems_query_partners 换一个档案完整的客户)。");
1318
+ }
1319
+ // si_sale 的 sale_man 与 sale_man_id 是两列,业绩统计分别用它们,
1320
+ // 所以两者必须指向同一个人:只给姓名却拿当前账号的 ID,业绩就记到别人头上了。
1321
+ const isMe = (name) => name !== "" && (name === me.name || name === me.username);
1322
+ let saleMan = text(args["saleMan"]);
1323
+ let saleManId = idText(args["saleManId"]);
1324
+ if (saleMan === "" && saleManId === "") {
1325
+ // 没指定销售员:姓名与 ID 都取当前登录身份
1326
+ saleMan = me.name || me.username;
1327
+ saleManId = me.userId ?? "";
1328
+ }
1329
+ else if (saleMan === "") {
1330
+ // 反查只有「名字 → ID」这一个方向,只给 ID 时补不出姓名,只能要求一起给
1331
+ if (saleManId !== me.userId) {
1332
+ throw localError("PARAM_INVALID", `传了 saleManId(${saleManId})但没传 saleMan 姓名:sale_man 与 sale_man_id `
1333
+ + "在业绩统计里分别使用,必须指向同一个人。请把销售员姓名一起传进来。");
1334
+ }
1335
+ saleMan = me.name || me.username;
1336
+ }
1337
+ else if (isMe(saleMan)) {
1338
+ // 指定的是自己:ID 直接用当前账号,传了别人的 ID 就是两列打架
1339
+ if (saleManId !== "" && saleManId !== me.userId) {
1340
+ throw localError("PARAM_INVALID", `saleMan「${saleMan}」是当前登录账号,但 saleManId(${saleManId})不是当前账号的 ID。`
1341
+ + "两列在业绩统计里分别使用,必须指向同一个人。");
1342
+ }
1343
+ saleManId = me.userId ?? "";
1344
+ }
1345
+ else {
1346
+ // 指定了别人:按姓名反查 ID,查不到就报错,不用自己顶
1347
+ const looked = await userIdByName(ctx, saleMan);
1348
+ if (looked === "") {
1349
+ throw localError("PARAM_INVALID", `海竣信息系统里查不到名为「${saleMan}」的用户,无法确定销售员 ID。`
1350
+ + "请让用户核对姓名,或直接传 saleManId(19 位用户 ID)。"
1351
+ + "不能拿当前登录账号顶替——业绩会记到别人头上。");
1352
+ }
1353
+ if (saleManId !== "" && saleManId !== looked) {
1354
+ throw localError("PARAM_INVALID", `saleMan「${saleMan}」在海竣信息系统里的用户 ID 是 ${looked},与传入的 saleManId(${saleManId})`
1355
+ + "不是同一个人。sale_man 与 sale_man_id 在业绩统计里分别使用,"
1356
+ + "落库后业绩会记到 ID 那个人头上。请让用户确认销售员到底是谁,只传 saleMan 即可。");
1357
+ }
1358
+ saleManId = looked;
1359
+ }
1360
+ // 两列都是 NOT NULL:姓名取不到(账号没填姓名)时后端会 500,这里先拦
1361
+ if (saleMan === "") {
1362
+ throw localError("PARAM_INVALID", "取不到销售员姓名(当前登录账号没有姓名),而销售单的 sale_man 必填。请传 saleMan。");
1363
+ }
1364
+ if (saleManId === "") {
1365
+ throw localError("PARAM_INVALID", "取不到当前账号的用户 ID(销售员 ID 必填),请稍后重试或联系管理员。");
1366
+ }
1367
+ // 约定收款日期前端表单必填且默认当天,MCP 不传会留空,与界面建单不一致
1368
+ const soldTime = normalizeDateTime(text(args["soldTime"])) || nowText();
1369
+ const paymentRateTime = normalizeDateTime(text(args["paymentRateTime"])) || soldTime;
1370
+ // 成本/利润/应收这些派生列后端一律不算(SaleController#save 只兜底单号、制单人、部门、状态),
1371
+ // 前端是自己算好一并提交的。不传就是 0,报表和业绩全错——所以这里按界面的口径算一遍。
1372
+ const sumOf = (key) => money(details.reduce((sum, line) => sum + Number(line[key] ?? 0), 0));
1373
+ const amount = sumOf("totalPrice");
1374
+ const financeCost = money(numeric(args["financeCost"]) ?? 0);
1375
+ const otherCost = money(numeric(args["otherCost"]) ?? 0);
1376
+ const goodsCost = sumOf("totalSaleCost");
1377
+ const totalCost = money(goodsCost + financeCost + otherCost);
1378
+ const profitAmount = money(amount - totalCost);
1379
+ const companyProfit = sumOf("companyProfit");
1380
+ const amountPaid = money(numeric(args["amountPaid"]) ?? 0);
1381
+ const sale = {
1382
+ customerId,
1383
+ customerName,
1384
+ customerTel: text(args["customerTel"]) || contactTel,
1385
+ customerProvince,
1386
+ customerCity,
1387
+ customerAddress: text(args["customerAddress"]) || customerField("address"),
1388
+ contactName,
1389
+ contactTel,
1390
+ saleMan,
1391
+ // 雪花 ID 超 2^53,必须按字符串传,转 number 会静默换成另一个用户
1392
+ saleManId,
1393
+ soldTime,
1394
+ paymentRateTime,
1395
+ amount,
1396
+ amountPaid,
1397
+ amountUnpaid: money(amount - amountPaid),
1398
+ goodsCost,
1399
+ financeCost,
1400
+ otherCost,
1401
+ totalCost,
1402
+ profitAmount,
1403
+ profitRate: amount === 0 ? 0 : ratio(profitAmount / amount),
1404
+ grossProfitRate: amount === 0 ? 0 : ratio(companyProfit / amount),
1405
+ // 前端新建单默认带「增值专用发票」,不传会与界面建单不一致
1406
+ invoiceType: text(args["invoiceType"]) || "增值专用发票",
1407
+ contractId: numeric(args["contractId"]),
1408
+ remark: text(args["remark"]) || undefined,
1409
+ // 请求体里的 source 会被后端忽略:来源以令牌的 client_id 为准(sems-workbuddy ⇒ workbuddy)
1410
+ source: "workbuddy",
1411
+ };
1412
+ const body = { sale, saleDetails: details, source: "workbuddy" };
1413
+ const draft = ctx.drafts.create({
1414
+ tool: "sems_prepare_sale",
1415
+ call: { path: "/invoicing/sale", body },
1416
+ digest: digestOf(body),
1417
+ summary: `销售单草稿:客户「${customerName}」,${details.length} 项明细,`
1418
+ + `合计 ¥${moneyText(amount)}。尚未写入海竣信息系统。`,
1419
+ warnings,
1420
+ });
1421
+ return replyOf(draft, "sems_commit_sale");
1422
+ }
1423
+ /**
1424
+ * 供复合编排工具复用的草稿构造。与 `sems_prepare_*` 工具走同一条路径,
1425
+ * 保证「单步起草」与「编排起草」产出的草稿结构完全一致。
1426
+ */
1427
+ export async function preparePurchaseDraft(ctx, args) {
1428
+ const profile = await ctx.userProfile.get();
1429
+ const warnings = [];
1430
+ // 部门与经办人是 OrderFormServiceImpl#validData 的硬性要求,
1431
+ // 只能取自当前登录身份——让模型猜部门 ID 既猜不到也会猜错。
1432
+ // 联系人不在其中:它属于供应商,见下面的 contactName/contactTel。
1433
+ if (profile.deptId === undefined) {
1434
+ throw localError("PARAM_INVALID", "无法从当前账号取得部门(deptId),而采购单要求「订货部门必填」。请让用户提供部门后再起草。");
1435
+ }
1436
+ if (profile.userId === undefined) {
1437
+ throw localError("PARAM_INVALID", "无法从当前账号取得经办人 ID(handlerId),请稍后重试或联系管理员。");
1438
+ }
1439
+ const supplierName = needText(args["supplierName"], "supplierName").trim();
1440
+ let supplierId = numeric(args["supplierId"]);
1441
+ let supplier;
1442
+ {
1443
+ const found = await ctx.client.call({
1444
+ method: "GET",
1445
+ path: "/scm/supplier/page",
1446
+ query: { customerName: supplierName, size: 5 },
1447
+ });
1448
+ const records = asArray(asRecord(unwrapSems(found.data))["records"]).map(asRecord);
1449
+ // 供应商名普遍带首尾空格,严格相等会匹配不上,进而漏掉联系人
1450
+ const exact = records.filter((r) => text(r["customerName"]).trim() === supplierName);
1451
+ if (supplierId !== undefined) {
1452
+ supplier = exact.find((r) => String(numeric(r["customerId"])) === String(supplierId)) ?? exact[0];
1453
+ }
1454
+ else if (exact.length === 1) {
1455
+ supplierId = numeric(exact[0]?.["customerId"]);
1456
+ supplier = exact[0];
1457
+ if (supplierId !== undefined) {
1458
+ warnings.push(`已按名称精确匹配到现有供应商「${supplierName}」(ID ${supplierId})。`);
1459
+ }
1460
+ }
1461
+ else {
1462
+ warnings.push(exact.length > 1
1463
+ ? `有 ${exact.length} 个同名供应商「${supplierName}」,建议先用 sems_query_partners 选定 ID。`
1464
+ : `海竣信息系统里没有名为「${supplierName}」的供应商,请确认名称是否正确。`);
1465
+ }
1466
+ }
1467
+ // OrderFormServiceImpl#save 用 contactId 判空来决定「新建供应商」,
1468
+ // 不带就会按名字再建一份重复供应商,所以能从档案取到就必须带上
1469
+ const supplierContactId = numeric(supplier?.["customerContactId"]);
1470
+ if (supplierContactId === undefined && supplierId !== undefined) {
1471
+ warnings.push(`供应商「${supplierName}」在档案里没有默认联系人:提交后海竣信息系统会**按名称新建一份重复的供应商**,`
1472
+ + "请让用户在供应商档案里补一个联系人后再提交。");
1473
+ }
1474
+ // 🔴 不再用当前登录账号兜底:拿自己的姓名手机号当供应商的联系人,
1475
+ // 后端还会按它建一条供应商联系人记录——脏数据比报错更难清。
1476
+ // 只能取供应商档案里的默认联系人,或用户显式传入。
1477
+ const contactName = text(args["contactName"]) || text(supplier?.["contactName"]);
1478
+ const contactTel = text(args["contactTel"]) || text(supplier?.["mobile1"]);
1479
+ if (!contactName || !contactTel) {
1480
+ const lack = [!contactName ? "联系人姓名" : "", !contactTel ? "联系人手机" : ""]
1481
+ .filter((v) => v !== "")
1482
+ .join("、");
1483
+ throw localError("PARAM_INVALID", `采购单要求「${lack}」必填,但供应商「${supplierName}」档案里没有。`
1484
+ + "请让用户提供 contactName / contactTel,或先在海竣信息系统供应商档案里补一个联系人。"
1485
+ + "不会拿当前登录账号顶替——那会往供应商档案里写一条假联系人。");
1486
+ }
1487
+ const details = asArray(args["items"]).map((raw) => {
1488
+ const item = asRecord(raw);
1489
+ const quantity = needNumber(item["quantity"], "items[].quantity");
1490
+ const unitPrice = needNumber(item["unitPrice"], "items[].unitPrice");
1491
+ return compact({
1492
+ productId: numeric(item["productId"]),
1493
+ name: needText(item["name"], "items[].name"),
1494
+ spec: needText(item["spec"], "items[].spec"),
1495
+ // 采购明细的详细配置为选填,但界面上填了才好在入库/打印时区分同名产品
1496
+ specDetail: text(item["specDetail"]),
1497
+ unit: needText(item["unit"], "items[].unit"),
1498
+ quantity,
1499
+ unitPrice,
1500
+ amount: money(quantity * unitPrice),
1501
+ // 不传后端不显示(OrderFormDetailDisPlayFlagEnum.show = "1")
1502
+ displayFlag: "1",
1503
+ remark: text(item["remark"]),
1504
+ });
1505
+ });
1506
+ if (details.length === 0)
1507
+ throw localError("PARAM_INVALID", "至少需要一条采购明细");
1508
+ const amount = money(details.reduce((sum, line) => sum + Number(line["amount"] ?? 0), 0));
1509
+ const orderForm = compact({
1510
+ name: needText(args["name"], "name"),
1511
+ deptId: profile.deptId,
1512
+ handlerId: profile.userId,
1513
+ handlerName: profile.name,
1514
+ // SEMS 把采购单上的「销售员」三字段当必填,实际语义是本次采购的联系人
1515
+ contactId: supplierContactId,
1516
+ contactName,
1517
+ contactTel,
1518
+ contactPosition: text(supplier?.["position"]),
1519
+ customerId: supplierId,
1520
+ customerName: supplierName,
1521
+ customerProvince: text(supplier?.["province"]),
1522
+ customerCity: text(supplier?.["city"]),
1523
+ customerAddress: text(args["supplierAddress"]) || text(supplier?.["address"]),
1524
+ taxIncluded: args["taxIncluded"] === undefined ? true : args["taxIncluded"] === true,
1525
+ priority: text(args["priority"]) || "普通",
1526
+ orderTime: normalizeDateTime(text(args["orderTime"])) || nowText(),
1527
+ // 与界面新建采购单的默认值一致(add-order-form.vue#initData)
1528
+ invoiceType: text(args["invoiceType"]) || "增值专用发票",
1529
+ isSigned: false,
1530
+ amount,
1531
+ remark: text(args["remark"]),
1532
+ preSale: false,
1533
+ });
1534
+ // 采购状态由后端按审批流第一步自动写入(实测落「采购中」/completeStatus=2),无需前端硬编码
1535
+ const body = { orderForm, orderFormDetails: details };
1536
+ const draft = ctx.drafts.create({
1537
+ tool: "sems_prepare_purchase",
1538
+ call: { path: "/invoicing/order-form", body },
1539
+ digest: digestOf(body),
1540
+ summary: `采购单草稿:供应商「${supplierName}」,${details.length} 项明细,合计 ¥${moneyText(amount)},`
1541
+ + `订单名称「${String(orderForm["name"])}」。尚未写入海竣信息系统。`,
1542
+ warnings,
1543
+ });
1544
+ return replyOf(draft, "sems_commit_purchase");
1545
+ }
1546
+ //# sourceMappingURL=writes.js.map