@harrylabsj/kiwi 0.12.15 → 0.12.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/a2a/server/negotiation-approvals.d.ts +14 -1
- package/dist/a2a/server/negotiation-approvals.js +32 -0
- package/dist/a2a/server/negotiation-approvals.js.map +1 -1
- package/dist/cli.js +193 -0
- package/dist/cli.js.map +1 -1
- package/dist/mcp/merchant-ops-server.d.ts +38 -0
- package/dist/mcp/merchant-ops-server.js +283 -0
- package/dist/mcp/merchant-ops-server.js.map +1 -0
- package/dist/mcp/merchant-runtime-assembly.js +28 -0
- package/dist/mcp/merchant-runtime-assembly.js.map +1 -1
- package/dist/mcp/merchant-server.d.ts +16 -0
- package/dist/mcp/merchant-server.js +24 -0
- package/dist/mcp/merchant-server.js.map +1 -1
- package/dist/merchant/negotiation-observer.d.ts +35 -0
- package/dist/merchant/negotiation-observer.js +159 -51
- package/dist/merchant/negotiation-observer.js.map +1 -1
- package/dist/merchant/negotiation-ops.d.ts +77 -0
- package/dist/merchant/negotiation-ops.js +203 -0
- package/dist/merchant/negotiation-ops.js.map +1 -0
- package/dist/merchant/watch/detect.d.ts +37 -0
- package/dist/merchant/watch/detect.js +147 -0
- package/dist/merchant/watch/detect.js.map +1 -0
- package/dist/merchant/watch/notify.d.ts +48 -0
- package/dist/merchant/watch/notify.js +108 -0
- package/dist/merchant/watch/notify.js.map +1 -0
- package/dist/merchant/watch/service.d.ts +43 -0
- package/dist/merchant/watch/service.js +167 -0
- package/dist/merchant/watch/service.js.map +1 -0
- package/dist/merchant/watch/state.d.ts +49 -0
- package/dist/merchant/watch/state.js +68 -0
- package/dist/merchant/watch/state.js.map +1 -0
- package/dist/merchant/watch/weixin.d.ts +54 -0
- package/dist/merchant/watch/weixin.js +271 -0
- package/dist/merchant/watch/weixin.js.map +1 -0
- package/dist/merchant-runtime/services.d.ts +0 -8
- package/dist/merchant-runtime/services.js +38 -0
- package/dist/merchant-runtime/services.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
import { createNegotiationObserver } from "./negotiation-observer.js";
|
|
17
|
+
const STATUS_BY_CODE = {
|
|
18
|
+
invalid_request: 400,
|
|
19
|
+
not_found: 404,
|
|
20
|
+
conflict: 409,
|
|
21
|
+
unavailable: 503,
|
|
22
|
+
forbidden: 403,
|
|
23
|
+
internal: 500,
|
|
24
|
+
};
|
|
25
|
+
export class NegotiationOpsError extends Error {
|
|
26
|
+
code;
|
|
27
|
+
status;
|
|
28
|
+
/** 机器可读的细分原因(如 below_floor),不参与文案。 */
|
|
29
|
+
reason;
|
|
30
|
+
constructor(code, message, reason) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.name = "NegotiationOpsError";
|
|
33
|
+
this.code = code;
|
|
34
|
+
this.status = STATUS_BY_CODE[code];
|
|
35
|
+
if (reason !== undefined)
|
|
36
|
+
this.reason = reason;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const APPROVAL_STATUSES = new Set([
|
|
40
|
+
"pending",
|
|
41
|
+
"approved",
|
|
42
|
+
"consumed",
|
|
43
|
+
"expired",
|
|
44
|
+
"rejected",
|
|
45
|
+
]);
|
|
46
|
+
function requireText(value, field, max = 128) {
|
|
47
|
+
const text = typeof value === "string" ? value.trim() : "";
|
|
48
|
+
if (text === "" || text.length > max) {
|
|
49
|
+
throw new NegotiationOpsError("invalid_request", `${field} 必须是非空字符串(≤${max} 字符)`);
|
|
50
|
+
}
|
|
51
|
+
return text;
|
|
52
|
+
}
|
|
53
|
+
function optionalStatus(value) {
|
|
54
|
+
if (value === undefined || value === "" || value === "all")
|
|
55
|
+
return "all";
|
|
56
|
+
if (typeof value === "string" && APPROVAL_STATUSES.has(value)) {
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
throw new NegotiationOpsError("invalid_request", "status 不是合法的审批状态");
|
|
60
|
+
}
|
|
61
|
+
function mapStoreError(err) {
|
|
62
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
63
|
+
if (message.includes("no pending negotiation approval")) {
|
|
64
|
+
return new NegotiationOpsError("conflict", "该审批已处理或已过期");
|
|
65
|
+
}
|
|
66
|
+
if (message.includes("reject reason")) {
|
|
67
|
+
return new NegotiationOpsError("invalid_request", "拒绝原因过长(≤500 字符)");
|
|
68
|
+
}
|
|
69
|
+
if (message.includes("locked by another process")) {
|
|
70
|
+
return new NegotiationOpsError("conflict", "审批队列正被另一个进程写入,请重试");
|
|
71
|
+
}
|
|
72
|
+
return new NegotiationOpsError("internal", "审批写入失败");
|
|
73
|
+
}
|
|
74
|
+
export function createNegotiationOps(options) {
|
|
75
|
+
const observer = createNegotiationObserver({
|
|
76
|
+
ledgerDir: options.ledgerDir,
|
|
77
|
+
...(options.now !== undefined ? { now: options.now } : {}),
|
|
78
|
+
});
|
|
79
|
+
const findApproval = (approvalId) => options.approvals.list().find((record) => record.approval_id === approvalId);
|
|
80
|
+
const notFoundLedger = (err) => {
|
|
81
|
+
if (err instanceof Error && err.name === "MerchantWorkbenchError") {
|
|
82
|
+
const kind = err.kind;
|
|
83
|
+
if (kind === "unavailable") {
|
|
84
|
+
throw new NegotiationOpsError("unavailable", "磋商账本不可读");
|
|
85
|
+
}
|
|
86
|
+
if (kind === "validation") {
|
|
87
|
+
throw new NegotiationOpsError("invalid_request", "磋商查询参数不合法");
|
|
88
|
+
}
|
|
89
|
+
if (kind === "not_found") {
|
|
90
|
+
throw new NegotiationOpsError("not_found", "未找到该磋商");
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
throw new NegotiationOpsError("internal", "磋商读取失败");
|
|
94
|
+
};
|
|
95
|
+
return {
|
|
96
|
+
info() {
|
|
97
|
+
try {
|
|
98
|
+
const all = observer.listOwner({ status: "all", limit: 1 });
|
|
99
|
+
return {
|
|
100
|
+
merchant_id: options.merchantId,
|
|
101
|
+
version: options.version,
|
|
102
|
+
ledger_negotiations: all.total,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
return notFoundLedger(err);
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
listNegotiations(query) {
|
|
110
|
+
try {
|
|
111
|
+
return observer.listOwner(query);
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
return notFoundLedger(err);
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
negotiationDetail(negotiationId) {
|
|
118
|
+
try {
|
|
119
|
+
return observer.timelineOwner(requireText(negotiationId, "negotiation_id"));
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
if (err instanceof NegotiationOpsError)
|
|
123
|
+
throw err;
|
|
124
|
+
return notFoundLedger(err);
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
listApprovals(status) {
|
|
128
|
+
const resolved = optionalStatus(status);
|
|
129
|
+
return options.approvals.list(resolved === "all" ? undefined : resolved);
|
|
130
|
+
},
|
|
131
|
+
approve(input) {
|
|
132
|
+
const approvalId = requireText(input.approval_id, "approval_id");
|
|
133
|
+
if (!Number.isSafeInteger(input.approved_minor) || input.approved_minor < 0) {
|
|
134
|
+
throw new NegotiationOpsError("invalid_request", "approved_minor 必须是非负整数");
|
|
135
|
+
}
|
|
136
|
+
const actor = requireText(input.actor, "actor");
|
|
137
|
+
const ttl = input.ttl_seconds ?? 3600;
|
|
138
|
+
if (!Number.isSafeInteger(ttl) || ttl < 60 || ttl > 86_400) {
|
|
139
|
+
throw new NegotiationOpsError("invalid_request", "ttl_seconds 必须是 60..86400 的整数");
|
|
140
|
+
}
|
|
141
|
+
const current = findApproval(approvalId);
|
|
142
|
+
if (current === undefined) {
|
|
143
|
+
throw new NegotiationOpsError("not_found", "未找到该审批");
|
|
144
|
+
}
|
|
145
|
+
if (current.status !== "pending") {
|
|
146
|
+
throw new NegotiationOpsError("conflict", "该审批已处理或已过期");
|
|
147
|
+
}
|
|
148
|
+
if (current.floor_minor !== undefined && input.approved_minor < current.floor_minor) {
|
|
149
|
+
throw new NegotiationOpsError("invalid_request", "批准价低于私有底价", "below_floor");
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
return options.approvals.approve({
|
|
153
|
+
approval_id: approvalId,
|
|
154
|
+
approved_minor: input.approved_minor,
|
|
155
|
+
ttl_seconds: ttl,
|
|
156
|
+
approved_by: actor,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
catch (err) {
|
|
160
|
+
throw mapStoreError(err);
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
reject(input) {
|
|
164
|
+
const approvalId = requireText(input.approval_id, "approval_id");
|
|
165
|
+
const actor = requireText(input.actor, "actor");
|
|
166
|
+
const reason = typeof input.reason === "string" ? input.reason.trim() : "";
|
|
167
|
+
if (reason.length > 500) {
|
|
168
|
+
throw new NegotiationOpsError("invalid_request", "拒绝原因过长(≤500 字符)");
|
|
169
|
+
}
|
|
170
|
+
const current = findApproval(approvalId);
|
|
171
|
+
if (current === undefined) {
|
|
172
|
+
throw new NegotiationOpsError("not_found", "未找到该审批");
|
|
173
|
+
}
|
|
174
|
+
if (current.status !== "pending") {
|
|
175
|
+
throw new NegotiationOpsError("conflict", "该审批已处理或已过期");
|
|
176
|
+
}
|
|
177
|
+
try {
|
|
178
|
+
return options.approvals.reject({
|
|
179
|
+
approval_id: approvalId,
|
|
180
|
+
...(reason !== "" ? { reason } : {}),
|
|
181
|
+
rejected_by: actor,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
catch (err) {
|
|
185
|
+
throw mapStoreError(err);
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
snapshot() {
|
|
189
|
+
try {
|
|
190
|
+
const all = observer.listOwner({ status: "all", limit: 100 });
|
|
191
|
+
return {
|
|
192
|
+
negotiations: all.items,
|
|
193
|
+
total: all.total,
|
|
194
|
+
approvals: options.approvals.list(),
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
return notFoundLedger(err);
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
//# sourceMappingURL=negotiation-ops.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"negotiation-ops.js","sourceRoot":"","sources":["../../src/merchant/negotiation-ops.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAmBH,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAetE,MAAM,cAAc,GAA4C;IAC9D,eAAe,EAAE,GAAG;IACpB,SAAS,EAAE,GAAG;IACd,QAAQ,EAAE,GAAG;IACb,WAAW,EAAE,GAAG;IAChB,SAAS,EAAE,GAAG;IACd,QAAQ,EAAE,GAAG;CACd,CAAC;AAEF,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IACnC,IAAI,CAA0B;IAC9B,MAAM,CAAS;IACxB,sCAAsC;IAC7B,MAAM,CAAU;IAEzB,YAAY,IAA6B,EAAE,OAAe,EAAE,MAAe;QACzE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;QAClC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,MAAM,GAAG,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AAM,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACpC,WAAW,EAAE,KAAK;iBACnB,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,MAAM,aAAa,CAAC,GAAG,CAAC,CAAC;YAC3B,CAAC;QACH,CAAC;QAED,QAAQ;YACN,IAAI,CAAC;gBACH,MAAM,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;gBAC9D,OAAO;oBACL,YAAY,EAAE,GAAG,CAAC,KAAK;oBACvB,KAAK,EAAE,GAAG,CAAC,KAAK;oBAChB,SAAS,EAAE,OAAO,CAAC,SAAS,CAAC,IAAI,EAAE;iBACpC,CAAC;YACJ,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,OAAO,cAAc,CAAC,GAAG,CAAC,CAAC;YAC7B,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
import type { NegotiationOpsSnapshot } from "../negotiation-ops.js";
|
|
17
|
+
import type { WatchState } from "./state.js";
|
|
18
|
+
export interface WatchNotification {
|
|
19
|
+
key: string;
|
|
20
|
+
texts: Record<string, string>;
|
|
21
|
+
}
|
|
22
|
+
export interface DetectOptions {
|
|
23
|
+
channels: readonly string[];
|
|
24
|
+
/** 同一 (negotiation, sku) 的审批通知冷却。 */
|
|
25
|
+
approvalCooldownMs?: number;
|
|
26
|
+
now: Date;
|
|
27
|
+
}
|
|
28
|
+
export declare function money(currency: string, minor: number): string;
|
|
29
|
+
export interface DetectResult {
|
|
30
|
+
notifications: WatchNotification[];
|
|
31
|
+
next: WatchState;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* 对比状态与快照,返回待投递通知与推进后的状态。
|
|
35
|
+
* 首次运行(initialized_at 缺省)不回放历史磋商,但现存 pending 审批仍通知。
|
|
36
|
+
*/
|
|
37
|
+
export declare function detectNotifications(state: WatchState, snapshot: NegotiationOpsSnapshot, options: DetectOptions): DetectResult;
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
const DEFAULT_APPROVAL_COOLDOWN_MS = 10 * 60 * 1000;
|
|
17
|
+
export function money(currency, minor) {
|
|
18
|
+
const whole = Math.trunc(minor / 100);
|
|
19
|
+
const cents = String(minor % 100).padStart(2, "0");
|
|
20
|
+
return `${currency === "CNY" ? "¥" : currency}${whole}.${cents}`;
|
|
21
|
+
}
|
|
22
|
+
function shortId(id) {
|
|
23
|
+
return id.length <= 24 ? id : `${id.slice(0, 21)}…`;
|
|
24
|
+
}
|
|
25
|
+
function approvalTexts(record, channels, kind) {
|
|
26
|
+
const texts = {};
|
|
27
|
+
const base = [
|
|
28
|
+
`【Kiwi 商家】待审批还价`,
|
|
29
|
+
`SKU ${record.sku} × ${record.quantity}${record.unit !== undefined ? ` ${record.unit}` : ""}`,
|
|
30
|
+
`买家还价 ${money(record.currency, record.buyer_offer_minor)}`,
|
|
31
|
+
...(record.public_bound_minor !== undefined
|
|
32
|
+
? [`公开边界 ${money(record.currency, record.public_bound_minor)}`]
|
|
33
|
+
: []),
|
|
34
|
+
`审批 ${record.approval_id}`,
|
|
35
|
+
`磋商 ${shortId(record.negotiation_id)}`,
|
|
36
|
+
"批准后需买家再次还价才会生效。",
|
|
37
|
+
];
|
|
38
|
+
if (kind !== "pending") {
|
|
39
|
+
const label = kind === "approved" ? "已批准" : kind === "consumed" ? "已生效" : kind === "rejected" ? "已拒绝" : "已过期";
|
|
40
|
+
base[0] = `【Kiwi 商家】审批${label}`;
|
|
41
|
+
if (record.approved_minor !== undefined && kind !== "rejected") {
|
|
42
|
+
base.splice(2, 0, `批准价 ${money(record.currency, record.approved_minor)}`);
|
|
43
|
+
}
|
|
44
|
+
base[base.length - 1] = kind === "expired" ? "授权已过期,需重新还价/审批。" : "状态已更新。";
|
|
45
|
+
}
|
|
46
|
+
for (const channel of channels) {
|
|
47
|
+
const lines = [...base];
|
|
48
|
+
if (kind === "pending" && channel === "weixin" && record.floor_minor !== undefined) {
|
|
49
|
+
lines.splice(3, 0, `私有底价 ${money(record.currency, record.floor_minor)}`);
|
|
50
|
+
}
|
|
51
|
+
texts[channel] = lines.join("\n");
|
|
52
|
+
}
|
|
53
|
+
return texts;
|
|
54
|
+
}
|
|
55
|
+
function negotiationTexts(row, channels, kind) {
|
|
56
|
+
const text = kind === "agreement"
|
|
57
|
+
? `【Kiwi 商家】磋商已达成非绑定协议\nSKU ${row.sku}${row.quantity !== undefined ? ` × ${row.quantity}` : ""}\n磋商 ${shortId(row.negotiation_id)}`
|
|
58
|
+
: `【Kiwi 商家】买家等待回应\nSKU ${row.sku}${row.quantity !== undefined ? ` × ${row.quantity}` : ""}${row.last_action !== "" ? `\n最近动作 ${row.last_action}` : ""}\n磋商 ${shortId(row.negotiation_id)}`;
|
|
59
|
+
return Object.fromEntries(channels.map((channel) => [channel, text]));
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* 对比状态与快照,返回待投递通知与推进后的状态。
|
|
63
|
+
* 首次运行(initialized_at 缺省)不回放历史磋商,但现存 pending 审批仍通知。
|
|
64
|
+
*/
|
|
65
|
+
export function detectNotifications(state, snapshot, options) {
|
|
66
|
+
const nowIso = options.now.toISOString();
|
|
67
|
+
const cooldown = options.approvalCooldownMs ?? DEFAULT_APPROVAL_COOLDOWN_MS;
|
|
68
|
+
const firstRun = state.initialized_at === undefined;
|
|
69
|
+
const next = {
|
|
70
|
+
version: 1,
|
|
71
|
+
updated_at: nowIso,
|
|
72
|
+
...(state.initialized_at !== undefined ? { initialized_at: state.initialized_at } : { initialized_at: nowIso }),
|
|
73
|
+
negotiations: { ...state.negotiations },
|
|
74
|
+
approvals: { ...state.approvals },
|
|
75
|
+
queue: state.queue,
|
|
76
|
+
};
|
|
77
|
+
const notifications = [];
|
|
78
|
+
for (const row of snapshot.negotiations) {
|
|
79
|
+
const previous = state.negotiations[row.negotiation_id];
|
|
80
|
+
const newDigest = row.last_event_digest !== "" && previous?.last_event_digest !== row.last_event_digest;
|
|
81
|
+
if (newDigest && !firstRun) {
|
|
82
|
+
if (row.needs_attention) {
|
|
83
|
+
notifications.push({
|
|
84
|
+
key: `neg:${row.negotiation_id}:${row.last_event_digest}`,
|
|
85
|
+
texts: negotiationTexts(row, options.channels, "attention"),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
else if (row.agreement && !previous?.agreement) {
|
|
89
|
+
notifications.push({
|
|
90
|
+
key: `neg:${row.negotiation_id}:${row.last_event_digest}:agreement`,
|
|
91
|
+
texts: negotiationTexts(row, options.channels, "agreement"),
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
next.negotiations[row.negotiation_id] = {
|
|
96
|
+
last_event_digest: row.last_event_digest,
|
|
97
|
+
agreement: row.agreement,
|
|
98
|
+
...(previous?.last_notified_at !== undefined
|
|
99
|
+
? { last_notified_at: previous.last_notified_at }
|
|
100
|
+
: {}),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
for (const record of snapshot.approvals) {
|
|
104
|
+
const previous = state.approvals[record.approval_id];
|
|
105
|
+
const changed = previous === undefined ||
|
|
106
|
+
previous.status !== record.status ||
|
|
107
|
+
previous.updated_at !== record.updated_at;
|
|
108
|
+
if (!changed)
|
|
109
|
+
continue;
|
|
110
|
+
const transitionKind = record.status === "pending"
|
|
111
|
+
? "pending"
|
|
112
|
+
: previous?.status === "approved" && record.status === "consumed"
|
|
113
|
+
? "consumed"
|
|
114
|
+
: previous?.status === "approved" && record.status === "expired"
|
|
115
|
+
? "expired"
|
|
116
|
+
: record.status === "rejected"
|
|
117
|
+
? "rejected"
|
|
118
|
+
: undefined;
|
|
119
|
+
let notifiedAt = previous?.notified_at;
|
|
120
|
+
if (transitionKind !== undefined) {
|
|
121
|
+
const recentSameSku = Object.values(state.approvals).some((entry) => entry.negotiation_id === record.negotiation_id &&
|
|
122
|
+
entry.sku === record.sku &&
|
|
123
|
+
entry.notified_at !== undefined &&
|
|
124
|
+
options.now.getTime() - Date.parse(entry.notified_at) < cooldown);
|
|
125
|
+
const cooling = transitionKind === "pending" &&
|
|
126
|
+
(recentSameSku ||
|
|
127
|
+
(previous?.notified_at !== undefined &&
|
|
128
|
+
options.now.getTime() - Date.parse(previous.notified_at) < cooldown));
|
|
129
|
+
if (!cooling) {
|
|
130
|
+
notifications.push({
|
|
131
|
+
key: `nap:${record.approval_id}:${record.status}:${record.updated_at}`,
|
|
132
|
+
texts: approvalTexts(record, options.channels, transitionKind),
|
|
133
|
+
});
|
|
134
|
+
notifiedAt = nowIso;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
next.approvals[record.approval_id] = {
|
|
138
|
+
status: record.status,
|
|
139
|
+
updated_at: record.updated_at,
|
|
140
|
+
negotiation_id: record.negotiation_id,
|
|
141
|
+
sku: record.sku,
|
|
142
|
+
...(notifiedAt !== undefined ? { notified_at: notifiedAt } : {}),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
return { notifications, next };
|
|
146
|
+
}
|
|
147
|
+
//# sourceMappingURL=detect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"detect.js","sourceRoot":"","sources":["../../../src/merchant/watch/detect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AA0BH,MAAM,4BAA4B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAEpD,MAAM,UAAU,KAAK,CAAC,QAAgB,EAAE,KAAa;IACnD,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,GAAG,CAAC,CAAC;IACtC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,GAAG,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IACnD,OAAO,GAAG,QAAQ,KAAK,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,GAAG,KAAK,IAAI,KAAK,EAAE,CAAC;AACnE,CAAC;AAED,SAAS,OAAO,CAAC,EAAU;IACzB,OAAO,EAAE,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC;AACtD,CAAC;AAED,SAAS,aAAa,CACpB,MAAiC,EACjC,QAA2B,EAC3B,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Ac,CAAC;iBAC/D,CAAC,CAAC;gBACH,UAAU,GAAG,MAAM,CAAC;YACtB,CAAC;QACH,CAAC;QACD,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,WAAW,CAAC,GAAG;YACnC,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,UAAU,EAAE,MAAM,CAAC,UAAU;YAC7B,cAAc,EAAE,MAAM,CAAC,cAAc;YACrC,GAAG,EAAE,MAAM,CAAC,GAAG;YACf,GAAG,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACjE,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC;AACjC,CAAC"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* watch 通知渠道。
|
|
18
|
+
*
|
|
19
|
+
* - 企业微信群机器人 webhook:主通道;只接受 https + 显式主机白名单,
|
|
20
|
+
* 禁止重定向,5s 超时,响应 ≤256 KiB;文本由调用方保证不含私有底价。
|
|
21
|
+
* - 个人微信 iLink:增强通道;主动发送尽量带上最近一次入站 context_token,
|
|
22
|
+
* 无 token 时仍尝试一次,失败由调用方按“通道降级”处理。
|
|
23
|
+
*/
|
|
24
|
+
import type { BotCredentials } from "../../weixin/types.js";
|
|
25
|
+
import type { IlinkClient } from "../../weixin/ilink-client.js";
|
|
26
|
+
export interface WatchChannel {
|
|
27
|
+
readonly name: string;
|
|
28
|
+
send(text: string): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export declare class WecomWebhookChannel implements WatchChannel {
|
|
31
|
+
private readonly options;
|
|
32
|
+
readonly name = "wecom";
|
|
33
|
+
private readonly url;
|
|
34
|
+
constructor(webhookUrl: string, options?: {
|
|
35
|
+
allowedHosts?: readonly string[];
|
|
36
|
+
fetchImpl?: typeof fetch;
|
|
37
|
+
});
|
|
38
|
+
send(text: string): Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
export declare class IlinkWatchChannel implements WatchChannel {
|
|
41
|
+
private readonly client;
|
|
42
|
+
private readonly credentials;
|
|
43
|
+
private readonly recipients;
|
|
44
|
+
private readonly contextTokenFor;
|
|
45
|
+
readonly name = "weixin";
|
|
46
|
+
constructor(client: IlinkClient, credentials: BotCredentials, recipients: readonly string[], contextTokenFor: (userId: string) => string | undefined);
|
|
47
|
+
send(text: string): Promise<void>;
|
|
48
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
const MAX_RESPONSE_BYTES = 256 * 1024;
|
|
17
|
+
const SEND_TIMEOUT_MS = 5_000;
|
|
18
|
+
export class WecomWebhookChannel {
|
|
19
|
+
options;
|
|
20
|
+
name = "wecom";
|
|
21
|
+
url;
|
|
22
|
+
constructor(webhookUrl, options = {}) {
|
|
23
|
+
this.options = options;
|
|
24
|
+
let parsed;
|
|
25
|
+
try {
|
|
26
|
+
parsed = new URL(webhookUrl);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
throw new Error("企业微信 webhook URL 不合法");
|
|
30
|
+
}
|
|
31
|
+
if (parsed.protocol !== "https:") {
|
|
32
|
+
throw new Error("企业微信 webhook 必须是 https");
|
|
33
|
+
}
|
|
34
|
+
if (parsed.username !== "" || parsed.password !== "") {
|
|
35
|
+
throw new Error("企业微信 webhook 不允许 userinfo");
|
|
36
|
+
}
|
|
37
|
+
const allowed = options.allowedHosts ?? ["qyapi.weixin.qq.com"];
|
|
38
|
+
if (!allowed.includes(parsed.hostname)) {
|
|
39
|
+
throw new Error(`企业微信 webhook 主机不在白名单:${parsed.hostname}`);
|
|
40
|
+
}
|
|
41
|
+
this.url = parsed;
|
|
42
|
+
}
|
|
43
|
+
async send(text) {
|
|
44
|
+
const fetchImpl = this.options.fetchImpl ?? fetch;
|
|
45
|
+
const response = await fetchImpl(this.url, {
|
|
46
|
+
method: "POST",
|
|
47
|
+
headers: { "content-type": "application/json" },
|
|
48
|
+
body: JSON.stringify({ msgtype: "text", text: { content: text } }),
|
|
49
|
+
redirect: "error",
|
|
50
|
+
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
|
|
51
|
+
});
|
|
52
|
+
const body = await response.text();
|
|
53
|
+
if (Buffer.byteLength(body) > MAX_RESPONSE_BYTES) {
|
|
54
|
+
throw new Error("企业微信 webhook 响应过大");
|
|
55
|
+
}
|
|
56
|
+
if (!response.ok) {
|
|
57
|
+
throw new Error(`企业微信 webhook HTTP ${response.status}`);
|
|
58
|
+
}
|
|
59
|
+
let parsed;
|
|
60
|
+
try {
|
|
61
|
+
parsed = JSON.parse(body);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
throw new Error("企业微信 webhook 响应不是 JSON");
|
|
65
|
+
}
|
|
66
|
+
const errcode = parsed.errcode;
|
|
67
|
+
if (typeof errcode === "number" && errcode !== 0) {
|
|
68
|
+
throw new Error(`企业微信 webhook errcode ${errcode}`);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
export class IlinkWatchChannel {
|
|
73
|
+
client;
|
|
74
|
+
credentials;
|
|
75
|
+
recipients;
|
|
76
|
+
contextTokenFor;
|
|
77
|
+
name = "weixin";
|
|
78
|
+
constructor(client, credentials, recipients, contextTokenFor) {
|
|
79
|
+
this.client = client;
|
|
80
|
+
this.credentials = credentials;
|
|
81
|
+
this.recipients = recipients;
|
|
82
|
+
this.contextTokenFor = contextTokenFor;
|
|
83
|
+
}
|
|
84
|
+
async send(text) {
|
|
85
|
+
if (this.recipients.length === 0) {
|
|
86
|
+
throw new Error("个人微信通道没有授权接收人");
|
|
87
|
+
}
|
|
88
|
+
const failures = [];
|
|
89
|
+
for (const userId of this.recipients) {
|
|
90
|
+
try {
|
|
91
|
+
await this.client.sendMessage({
|
|
92
|
+
to_user_id: userId,
|
|
93
|
+
text: text.length > 2000 ? `${text.slice(0, 2000)}…` : text,
|
|
94
|
+
...(this.contextTokenFor(userId) !== undefined
|
|
95
|
+
? { context_token: this.contextTokenFor(userId) }
|
|
96
|
+
: {}),
|
|
97
|
+
}, this.credentials);
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
failures.push(`${userId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (failures.length > 0) {
|
|
104
|
+
throw new Error(`个人微信发送失败(${failures.length}/${this.recipients.length})`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
//# sourceMappingURL=notify.js.map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IAAI,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC;QAC5E,CAAC;IACH,CAAC;CACF"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright 2026 harrylabsj
|
|
3
|
+
*
|
|
4
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
* you may not use this file except in compliance with the License.
|
|
6
|
+
* You may obtain a copy of the License at
|
|
7
|
+
*
|
|
8
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
*
|
|
10
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
* See the License for the specific language governing permissions and
|
|
14
|
+
* limitations under the License.
|
|
15
|
+
*/
|
|
16
|
+
import type { NegotiationOps } from "../negotiation-ops.js";
|
|
17
|
+
import type { WatchChannel } from "./notify.js";
|
|
18
|
+
export interface MerchantWatchServiceOptions {
|
|
19
|
+
dataDir: string;
|
|
20
|
+
ops: NegotiationOps;
|
|
21
|
+
channels: readonly WatchChannel[];
|
|
22
|
+
intervalMs?: number;
|
|
23
|
+
now?: () => Date;
|
|
24
|
+
log?: (line: string) => void;
|
|
25
|
+
}
|
|
26
|
+
export declare class MerchantWatchService {
|
|
27
|
+
private readonly options;
|
|
28
|
+
private readonly statePath;
|
|
29
|
+
private readonly channels;
|
|
30
|
+
private readonly intervalMs;
|
|
31
|
+
private readonly now;
|
|
32
|
+
private readonly log;
|
|
33
|
+
private timer;
|
|
34
|
+
private running;
|
|
35
|
+
private ticking;
|
|
36
|
+
constructor(options: MerchantWatchServiceOptions);
|
|
37
|
+
start(): void;
|
|
38
|
+
stop(): void;
|
|
39
|
+
tick(): Promise<void>;
|
|
40
|
+
private runTick;
|
|
41
|
+
private deliver;
|
|
42
|
+
private retryQueue;
|
|
43
|
+
}
|