@harrylabsj/kiwi 0.11.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -1
- package/contracts/kiwi-contracts.lock.json +1 -1
- package/contracts/manifest.json +2 -2
- package/contracts/runtime-binding/0.1.2/document.schema.json +3 -1
- package/dist/a2a/node.d.ts +2 -0
- package/dist/a2a/node.js +92 -13
- package/dist/a2a/node.js.map +1 -1
- package/dist/a2a/server/merchant-handler.js +31 -17
- package/dist/a2a/server/merchant-handler.js.map +1 -1
- package/dist/a2a/server/pipeline.js +1 -0
- package/dist/a2a/server/pipeline.js.map +1 -1
- package/dist/a2a/server/types.d.ts +1 -0
- package/dist/agent/buyer/buyer-tools.d.ts +2 -2
- package/dist/agent/buyer/buyer-tools.js.map +1 -1
- package/dist/agent/chat-tools.d.ts +2 -11
- package/dist/agent/chat-tools.js.map +1 -1
- package/dist/agent/fake-chat-model.d.ts +3 -3
- package/dist/agent/fake-chat-model.js +3 -5
- package/dist/agent/fake-chat-model.js.map +1 -1
- package/dist/agent/kernel-builder.js +4 -4
- package/dist/agent/kernel-builder.js.map +1 -1
- package/dist/agent/kernel.d.ts +15 -5
- package/dist/agent/kernel.js +143 -67
- package/dist/agent/kernel.js.map +1 -1
- package/dist/agent/kiwi-tool.d.ts +33 -0
- package/dist/agent/kiwi-tool.js +17 -0
- package/dist/agent/kiwi-tool.js.map +1 -0
- package/dist/agent/merchant/merchant-tools.d.ts +2 -17
- package/dist/agent/merchant/merchant-tools.js.map +1 -1
- package/dist/agent/negotiation-chat.d.ts +3 -2
- package/dist/agent/negotiation-chat.js.map +1 -1
- package/dist/agent/session.d.ts +15 -3
- package/dist/agent/session.js +114 -122
- package/dist/agent/session.js.map +1 -1
- package/dist/agent/skills/tools.d.ts +2 -2
- package/dist/agent/skills/tools.js.map +1 -1
- package/dist/cli.d.ts +5 -1
- package/dist/cli.js +239 -32
- package/dist/cli.js.map +1 -1
- package/dist/cloud/binding/enrollment-challenge.d.ts +37 -0
- package/dist/cloud/binding/enrollment-challenge.js +153 -0
- package/dist/cloud/binding/enrollment-challenge.js.map +1 -0
- package/dist/cloud/binding/enrollment-heartbeat.d.ts +26 -0
- package/dist/cloud/binding/enrollment-heartbeat.js +146 -0
- package/dist/cloud/binding/enrollment-heartbeat.js.map +1 -0
- package/dist/cloud/binding/enrollment-key-recovery.d.ts +27 -0
- package/dist/cloud/binding/enrollment-key-recovery.js +127 -0
- package/dist/cloud/binding/enrollment-key-recovery.js.map +1 -0
- package/dist/cloud/binding/runtime-challenge.d.ts +1 -1
- package/dist/cloud/binding/runtime-challenge.js +8 -1
- package/dist/cloud/binding/runtime-challenge.js.map +1 -1
- package/dist/cloud/bootstrap.d.ts +2 -0
- package/dist/cloud/bootstrap.js +324 -18
- package/dist/cloud/bootstrap.js.map +1 -1
- package/dist/cloud/catalog-client.d.ts +305 -0
- package/dist/cloud/catalog-client.js +962 -0
- package/dist/cloud/catalog-client.js.map +1 -0
- package/dist/cloud/config.d.ts +12 -0
- package/dist/cloud/config.js +45 -0
- package/dist/cloud/config.js.map +1 -1
- package/dist/cloud/connect-service.d.ts +144 -0
- package/dist/cloud/connect-service.js +776 -0
- package/dist/cloud/connect-service.js.map +1 -0
- package/dist/cloud/file-listing-publication.d.ts +105 -0
- package/dist/cloud/file-listing-publication.js +436 -0
- package/dist/cloud/file-listing-publication.js.map +1 -0
- package/dist/cloud/http-router.d.ts +2 -0
- package/dist/cloud/http-router.js +8 -0
- package/dist/cloud/http-router.js.map +1 -1
- package/dist/cloud/listing-publisher.d.ts +45 -0
- package/dist/cloud/listing-publisher.js +244 -0
- package/dist/cloud/listing-publisher.js.map +1 -0
- package/dist/cloud/merchant-connect.d.ts +53 -0
- package/dist/cloud/merchant-connect.js +90 -0
- package/dist/cloud/merchant-connect.js.map +1 -0
- package/dist/cloud/merchant-identity.d.ts +14 -0
- package/dist/cloud/merchant-identity.js +76 -0
- package/dist/cloud/merchant-identity.js.map +1 -0
- package/dist/cloud/onboarding/catalog-pipeline.d.ts +135 -0
- package/dist/cloud/onboarding/catalog-pipeline.js +454 -0
- package/dist/cloud/onboarding/catalog-pipeline.js.map +1 -0
- package/dist/cloud/onboarding/steps.js +2 -2
- package/dist/cloud/onboarding/steps.js.map +1 -1
- package/dist/cloud/product-import-tabular.d.ts +100 -0
- package/dist/cloud/product-import-tabular.js +1073 -0
- package/dist/cloud/product-import-tabular.js.map +1 -0
- package/dist/cloud/product-source.d.ts +8 -1
- package/dist/cloud/product-source.js +63 -13
- package/dist/cloud/product-source.js.map +1 -1
- package/dist/config/profile.d.ts +4 -0
- package/dist/config/profile.js +14 -0
- package/dist/config/profile.js.map +1 -1
- package/dist/discovery/catalog-source/cloud-card.d.ts +1 -1
- package/dist/discovery/catalog-source/cloud-card.js +7 -1
- package/dist/discovery/catalog-source/cloud-card.js.map +1 -1
- package/dist/http/merchant-management/api.d.ts +37 -0
- package/dist/http/merchant-management/api.js +379 -7
- package/dist/http/merchant-management/api.js.map +1 -1
- package/dist/http/merchant-management/page.d.ts +4 -1
- package/dist/http/merchant-management/page.js +426 -25
- package/dist/http/merchant-management/page.js.map +1 -1
- package/dist/mcp/merchant-runtime-assembly.js +4 -1
- package/dist/mcp/merchant-runtime-assembly.js.map +1 -1
- package/dist/mcp/merchant-server.d.ts +2 -0
- package/dist/mcp/merchant-server.js +15 -0
- package/dist/mcp/merchant-server.js.map +1 -1
- package/dist/merchant/negotiation-observer.d.ts +92 -0
- package/dist/merchant/negotiation-observer.js +278 -0
- package/dist/merchant/negotiation-observer.js.map +1 -0
- package/dist/merchant/operations-report.d.ts +85 -0
- package/dist/merchant/operations-report.js +227 -0
- package/dist/merchant/operations-report.js.map +1 -0
- package/dist/merchant/stats-store.d.ts +5 -0
- package/dist/merchant/stats-store.js +18 -0
- package/dist/merchant/stats-store.js.map +1 -1
- package/dist/merchant-gateway/catalog-publications.d.ts +28 -0
- package/dist/merchant-gateway/catalog-publications.js +69 -0
- package/dist/merchant-gateway/catalog-publications.js.map +1 -1
- package/dist/merchant-gateway/catalog-tools.js +20 -0
- package/dist/merchant-gateway/catalog-tools.js.map +1 -1
- package/dist/negotiation/lease/store.js +21 -2
- package/dist/negotiation/lease/store.js.map +1 -1
- package/dist/product-cli.d.ts +2 -2
- package/dist/product-cli.js +24 -9
- package/dist/product-cli.js.map +1 -1
- package/dist/product-init.d.ts +4 -1
- package/dist/product-init.js +39 -11
- package/dist/product-init.js.map +1 -1
- package/dist/product-publish.d.ts +8 -2
- package/dist/product-publish.js +222 -142
- package/dist/product-publish.js.map +1 -1
- package/dist/runtime/fake-model.js +9 -3
- package/dist/runtime/fake-model.js.map +1 -1
- package/package.json +10 -5
|
@@ -0,0 +1,1073 @@
|
|
|
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
|
+
* 表格商品导入(WP12):CSV / .xlsx → 云端商品表(`product-source.ts`)的
|
|
18
|
+
* 唯一转换与校验实现。工作台「商品与导入」、shopping-cli 导出脚本与技能
|
|
19
|
+
* `kiwi-product-import` 的列说明都以本模块为准。
|
|
20
|
+
*
|
|
21
|
+
* 设计要点:
|
|
22
|
+
* - 解析在**服务端**:一份实现同时服务工作台与脚本(浏览器端会在无构建步
|
|
23
|
+
* 的内联页面脚本里复制逻辑,必然漂移);xlsx 用 node:zlib 解 DEFLATE,
|
|
24
|
+
* **零新增依赖**(供应链锁定不变);
|
|
25
|
+
* - 表头映射容错:中文/英文/常见别名(大小写、空格、全半角标点归一化后
|
|
26
|
+
* 匹配);模板表头为「中文名/字段名」双写;
|
|
27
|
+
* - **疑似底价/成本/进价列 → 整表拒绝**:私密策略值不属于商品表(设计
|
|
28
|
+
* §10.1 硬规则),宁可拒收也不让底价混进公开表;
|
|
29
|
+
* - 无法识别的列不阻断导入,逐列列出交商家确认;
|
|
30
|
+
* - 转换出的表**再过一次** `parseProductTable`(纵深防御),最终落盘仍走
|
|
31
|
+
* 既有 import-drafts 严格校验与整表替换预览;
|
|
32
|
+
* - 上限:数据行 5000、列 64、单文件 4 MiB、单元格 2000 字符。
|
|
33
|
+
*/
|
|
34
|
+
import { inflateRawSync } from "node:zlib";
|
|
35
|
+
import { parseProductTable, PRODUCT_TABLE_SCHEMA_VERSION, ProductTableError, } from "./product-source.js";
|
|
36
|
+
// ── 上限与常量 ─────────────────────────────────────────────────────────
|
|
37
|
+
export const TABULAR_IMPORT_MAX_ROWS = 5000;
|
|
38
|
+
export const TABULAR_IMPORT_MAX_COLUMNS = 64;
|
|
39
|
+
export const TABULAR_IMPORT_MAX_BYTES = 4 * 1024 * 1024;
|
|
40
|
+
export const TABULAR_IMPORT_MAX_CELL_CHARS = 2000;
|
|
41
|
+
/** 结构性失败(CSV/xlsx 解不开、超上限)抛出;逐行/逐格问题进 errors 数组。 */
|
|
42
|
+
export class TabularImportError extends Error {
|
|
43
|
+
code;
|
|
44
|
+
constructor(code, message) {
|
|
45
|
+
super(message);
|
|
46
|
+
this.name = "TabularImportError";
|
|
47
|
+
this.code = code;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export const TABULAR_FIELDS = [
|
|
51
|
+
{
|
|
52
|
+
field: "sku",
|
|
53
|
+
zh: "商品编号",
|
|
54
|
+
required: true,
|
|
55
|
+
aliases: ["sku", "skucode", "skuno", "商品编号", "商品编码", "货号", "商品sku", "itemcode"],
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
field: "title",
|
|
59
|
+
zh: "名称",
|
|
60
|
+
required: true,
|
|
61
|
+
aliases: ["title", "name", "productname", "producttitle", "商品名称", "产品名称", "品名", "名称", "商品标题"],
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
field: "currency",
|
|
65
|
+
zh: "币种",
|
|
66
|
+
required: true,
|
|
67
|
+
aliases: ["currency", "currencycode", "币种", "币别", "货币", "计价币种"],
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
field: "unit",
|
|
71
|
+
zh: "计价单位",
|
|
72
|
+
required: true,
|
|
73
|
+
aliases: ["unit", "units", "pricingunit", "unitofmeasure", "uom", "计价单位", "单位", "计量单位", "价格单位"],
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
field: "price",
|
|
77
|
+
zh: "单价",
|
|
78
|
+
required: true,
|
|
79
|
+
aliases: [
|
|
80
|
+
"price",
|
|
81
|
+
"unitprice",
|
|
82
|
+
"listprice",
|
|
83
|
+
"sellingprice",
|
|
84
|
+
"单价",
|
|
85
|
+
"价格",
|
|
86
|
+
"销售价",
|
|
87
|
+
"销售单价",
|
|
88
|
+
"售价",
|
|
89
|
+
"公开价",
|
|
90
|
+
"报价",
|
|
91
|
+
],
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
field: "moq",
|
|
95
|
+
zh: "起订量",
|
|
96
|
+
required: false,
|
|
97
|
+
aliases: ["moq", "minorderqty", "minimumorderquantity", "起订量", "最小起订量", "起订数量"],
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
field: "stock",
|
|
101
|
+
zh: "库存",
|
|
102
|
+
required: false,
|
|
103
|
+
aliases: ["stock", "stockqty", "inventory", "qty", "quantity", "库存", "库存数量", "可用库存", "剩余库存"],
|
|
104
|
+
},
|
|
105
|
+
{
|
|
106
|
+
field: "supply_note",
|
|
107
|
+
zh: "供货说明",
|
|
108
|
+
required: false,
|
|
109
|
+
aliases: ["supplynote", "note", "notes", "remark", "remarks", "供货说明", "供货备注", "备注", "说明", "商品说明", "描述", "description"],
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
field: "updated_at",
|
|
113
|
+
zh: "更新时间",
|
|
114
|
+
required: false,
|
|
115
|
+
aliases: ["updatedat", "updatetime", "lastupdated", "更新时间", "数据时间", "修改时间", "最近更新"],
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
field: "valid_until",
|
|
119
|
+
zh: "有效期至",
|
|
120
|
+
required: true,
|
|
121
|
+
aliases: [
|
|
122
|
+
"validuntil",
|
|
123
|
+
"validtill",
|
|
124
|
+
"validity",
|
|
125
|
+
"expiry",
|
|
126
|
+
"expireat",
|
|
127
|
+
"有效期",
|
|
128
|
+
"有效期至",
|
|
129
|
+
"有效期限",
|
|
130
|
+
"有效期到",
|
|
131
|
+
"截止日期",
|
|
132
|
+
"截止时间",
|
|
133
|
+
"到期日",
|
|
134
|
+
"失效日期",
|
|
135
|
+
],
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
field: "status",
|
|
139
|
+
zh: "状态",
|
|
140
|
+
required: false,
|
|
141
|
+
aliases: ["status", "listingstatus", "active", "状态", "商品状态", "销售状态", "上架状态"],
|
|
142
|
+
},
|
|
143
|
+
];
|
|
144
|
+
/**
|
|
145
|
+
* 疑似底价/成本/进价列(归一化后**包含**即命中):整表拒绝。底价、成本
|
|
146
|
+
* 属于商家私密策略,绝不能进公开商品表(设计 §10.1 硬规则)。
|
|
147
|
+
*/
|
|
148
|
+
const COST_COLUMN_TOKENS = [
|
|
149
|
+
"底价",
|
|
150
|
+
"成本",
|
|
151
|
+
"进价",
|
|
152
|
+
"进货价",
|
|
153
|
+
"采购价",
|
|
154
|
+
"购入价",
|
|
155
|
+
"内部价",
|
|
156
|
+
"cost",
|
|
157
|
+
"costprice",
|
|
158
|
+
"floorprice",
|
|
159
|
+
"floor",
|
|
160
|
+
"baseprice",
|
|
161
|
+
"purchaseprice",
|
|
162
|
+
"buyprice",
|
|
163
|
+
"buyingprice",
|
|
164
|
+
];
|
|
165
|
+
/** 表头归一化:小写、去空白与中英文标点(模板「中文/字段」双写靠这个收敛)。 */
|
|
166
|
+
function normalizeHeader(raw) {
|
|
167
|
+
return raw
|
|
168
|
+
.normalize("NFKC")
|
|
169
|
+
.toLowerCase()
|
|
170
|
+
.replace(/[\s\-_·•、,,。.::;;()()[\]【】{}*#"'’“”]/g, "");
|
|
171
|
+
}
|
|
172
|
+
function buildAliasIndex() {
|
|
173
|
+
const index = new Map();
|
|
174
|
+
for (const spec of TABULAR_FIELDS) {
|
|
175
|
+
index.set(normalizeHeader(spec.field), spec.field);
|
|
176
|
+
index.set(normalizeHeader(spec.zh), spec.field);
|
|
177
|
+
index.set(normalizeHeader(`${spec.zh}/${spec.field}`), spec.field);
|
|
178
|
+
for (const alias of spec.aliases) {
|
|
179
|
+
const key = normalizeHeader(alias);
|
|
180
|
+
if (!index.has(key))
|
|
181
|
+
index.set(key, spec.field);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return index;
|
|
185
|
+
}
|
|
186
|
+
const ALIAS_INDEX = buildAliasIndex();
|
|
187
|
+
function isCostColumn(normalized) {
|
|
188
|
+
return COST_COLUMN_TOKENS.some((token) => normalized.includes(token));
|
|
189
|
+
}
|
|
190
|
+
// ── 值解析:数字 / 日期 / 币种 / 状态 ─────────────────────────────────
|
|
191
|
+
const NUMBER_STRIP_RE = /[¥¥$€\s,,]/g;
|
|
192
|
+
/** 解析数字:允许货币符号前缀与千分位分隔;必须是非空有限数。 */
|
|
193
|
+
function parseCellNumber(raw) {
|
|
194
|
+
const cleaned = raw.replace(NUMBER_STRIP_RE, "");
|
|
195
|
+
if (!/^\d+(\.\d+)?$/.test(cleaned))
|
|
196
|
+
return Number.NaN;
|
|
197
|
+
return Number(cleaned);
|
|
198
|
+
}
|
|
199
|
+
const CURRENCY_MAP = {
|
|
200
|
+
人民币: "CNY",
|
|
201
|
+
人民币元: "CNY",
|
|
202
|
+
元: "CNY",
|
|
203
|
+
cny: "CNY",
|
|
204
|
+
rmb: "CNY",
|
|
205
|
+
美元: "USD",
|
|
206
|
+
美金: "USD",
|
|
207
|
+
usd: "USD",
|
|
208
|
+
欧元: "EUR",
|
|
209
|
+
eur: "EUR",
|
|
210
|
+
港币: "HKD",
|
|
211
|
+
港元: "HKD",
|
|
212
|
+
hkd: "HKD",
|
|
213
|
+
日元: "JPY",
|
|
214
|
+
jpy: "JPY",
|
|
215
|
+
英镑: "GBP",
|
|
216
|
+
gbp: "GBP",
|
|
217
|
+
};
|
|
218
|
+
function parseCellCurrency(raw) {
|
|
219
|
+
const key = raw.trim().normalize("NFKC").toLowerCase();
|
|
220
|
+
const mapped = CURRENCY_MAP[key];
|
|
221
|
+
if (mapped !== undefined)
|
|
222
|
+
return mapped;
|
|
223
|
+
if (/^[a-z]{3}$/.test(key))
|
|
224
|
+
return key.toUpperCase();
|
|
225
|
+
return "";
|
|
226
|
+
}
|
|
227
|
+
const STATUS_ACTIVE = new Set([
|
|
228
|
+
"active",
|
|
229
|
+
"在售",
|
|
230
|
+
"正常",
|
|
231
|
+
"销售",
|
|
232
|
+
"销售中",
|
|
233
|
+
"售卖",
|
|
234
|
+
"售卖中",
|
|
235
|
+
"上架",
|
|
236
|
+
"已上架",
|
|
237
|
+
"启用",
|
|
238
|
+
"1",
|
|
239
|
+
"yes",
|
|
240
|
+
"true",
|
|
241
|
+
]);
|
|
242
|
+
const STATUS_PAUSED = new Set([
|
|
243
|
+
"paused",
|
|
244
|
+
"暂停",
|
|
245
|
+
"已暂停",
|
|
246
|
+
"暂停销售",
|
|
247
|
+
"停售",
|
|
248
|
+
"下架",
|
|
249
|
+
"已下架",
|
|
250
|
+
"停用",
|
|
251
|
+
"0",
|
|
252
|
+
"no",
|
|
253
|
+
"false",
|
|
254
|
+
]);
|
|
255
|
+
function parseCellStatus(raw) {
|
|
256
|
+
const key = raw.trim().normalize("NFKC").toLowerCase();
|
|
257
|
+
if (STATUS_ACTIVE.has(key))
|
|
258
|
+
return "active";
|
|
259
|
+
if (STATUS_PAUSED.has(key))
|
|
260
|
+
return "paused";
|
|
261
|
+
return "";
|
|
262
|
+
}
|
|
263
|
+
const DATE_RE = /^(\d{4})[-/年.](\d{1,2})[-/月.](\d{1,2})日?(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?$/;
|
|
264
|
+
/**
|
|
265
|
+
* 解析日期单元格:YYYY-MM-DD / YYYY/M/D / YYYY年M月D日(可带时间)或 ISO
|
|
266
|
+
* 时间戳。纯日期按 UTC 解释;`endOfDay=true`(有效期)取当日 23:59:59,
|
|
267
|
+
* 避免商家填「2027-12-31」当天上午就过期。其余返回空串(由调用方报错)。
|
|
268
|
+
*/
|
|
269
|
+
function parseCellDate(raw, options) {
|
|
270
|
+
const text = raw.trim();
|
|
271
|
+
const match = DATE_RE.exec(text);
|
|
272
|
+
if (match !== null) {
|
|
273
|
+
const year = Number(match[1]);
|
|
274
|
+
const month = Number(match[2]);
|
|
275
|
+
const day = Number(match[3]);
|
|
276
|
+
const hour = match[4] !== undefined ? Number(match[4]) : 0;
|
|
277
|
+
const minute = match[5] !== undefined ? Number(match[5]) : 0;
|
|
278
|
+
const second = match[6] !== undefined ? Number(match[6]) : 0;
|
|
279
|
+
const hasTime = match[4] !== undefined;
|
|
280
|
+
if (month < 1 || month > 12 || day < 1 || day > 31)
|
|
281
|
+
return "";
|
|
282
|
+
const date = new Date(Date.UTC(year, month - 1, day, hasTime ? hour : options.endOfDay ? 23 : 0, hasTime ? minute : options.endOfDay ? 59 : 0, hasTime ? second : options.endOfDay ? 59 : 0));
|
|
283
|
+
// 回读校验:Date.UTC 会静默滚动非法日期(如 2 月 30 日),必须拒绝。
|
|
284
|
+
if (date.getUTCFullYear() !== year ||
|
|
285
|
+
date.getUTCMonth() !== month - 1 ||
|
|
286
|
+
date.getUTCDate() !== day) {
|
|
287
|
+
return "";
|
|
288
|
+
}
|
|
289
|
+
return date.toISOString();
|
|
290
|
+
}
|
|
291
|
+
if (/^\d{4}-\d{2}-\d{2}T/.test(text)) {
|
|
292
|
+
const parsed = Date.parse(text);
|
|
293
|
+
if (Number.isNaN(parsed))
|
|
294
|
+
return "";
|
|
295
|
+
return new Date(parsed).toISOString();
|
|
296
|
+
}
|
|
297
|
+
return "";
|
|
298
|
+
}
|
|
299
|
+
// ── CSV 解析(RFC 4180 风格:引号、双引号转义、CRLF、BOM)────────────
|
|
300
|
+
export function parseCsv(text) {
|
|
301
|
+
if (text.length > TABULAR_IMPORT_MAX_BYTES) {
|
|
302
|
+
throw new TabularImportError("LIMIT_BYTES", `文件超过上限 ${TABULAR_IMPORT_MAX_BYTES} 字节`);
|
|
303
|
+
}
|
|
304
|
+
const stripped = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
305
|
+
const rows = [];
|
|
306
|
+
let row = [];
|
|
307
|
+
let cell = "";
|
|
308
|
+
let inQuotes = false;
|
|
309
|
+
for (let i = 0; i < stripped.length; i += 1) {
|
|
310
|
+
const ch = stripped[i];
|
|
311
|
+
if (inQuotes) {
|
|
312
|
+
if (ch === '"') {
|
|
313
|
+
if (stripped[i + 1] === '"') {
|
|
314
|
+
cell += '"';
|
|
315
|
+
i += 1;
|
|
316
|
+
}
|
|
317
|
+
else {
|
|
318
|
+
inQuotes = false;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
else {
|
|
322
|
+
cell += ch;
|
|
323
|
+
}
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
if (ch === '"') {
|
|
327
|
+
inQuotes = true;
|
|
328
|
+
}
|
|
329
|
+
else if (ch === ",") {
|
|
330
|
+
row.push(cell);
|
|
331
|
+
cell = "";
|
|
332
|
+
}
|
|
333
|
+
else if (ch === "\n") {
|
|
334
|
+
row.push(cell);
|
|
335
|
+
rows.push(row);
|
|
336
|
+
row = [];
|
|
337
|
+
cell = "";
|
|
338
|
+
}
|
|
339
|
+
else if (ch === "\r") {
|
|
340
|
+
if (stripped[i + 1] === "\n")
|
|
341
|
+
i += 1;
|
|
342
|
+
row.push(cell);
|
|
343
|
+
rows.push(row);
|
|
344
|
+
row = [];
|
|
345
|
+
cell = "";
|
|
346
|
+
}
|
|
347
|
+
else {
|
|
348
|
+
cell += ch;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
if (cell !== "" || row.length > 0) {
|
|
352
|
+
row.push(cell);
|
|
353
|
+
rows.push(row);
|
|
354
|
+
}
|
|
355
|
+
return rows.filter((line) => !(line.length === 1 && line[0] === ""));
|
|
356
|
+
}
|
|
357
|
+
// ── xlsx 读取(ZIP + sheet XML;零依赖)───────────────────────────────
|
|
358
|
+
/**
|
|
359
|
+
* xlsx 读取的 zip 炸弹防护上限(验收修复):入口已有压缩文件 ≤4 MiB 的限制,
|
|
360
|
+
* 但 deflate 可把 4 MiB 膨胀到 GB 级——单条目与全部条目的解压总量都必须封顶。
|
|
361
|
+
*/
|
|
362
|
+
export const XLSX_MAX_ZIP_ENTRIES = 128;
|
|
363
|
+
export const XLSX_MAX_ENTRY_BYTES = 32 * 1024 * 1024;
|
|
364
|
+
export const XLSX_MAX_TOTAL_BYTES = 32 * 1024 * 1024;
|
|
365
|
+
/**
|
|
366
|
+
* 最小 ZIP 读取器:EOCD → 中央目录(只登记,不解压)→ 按需读本地头与数据。
|
|
367
|
+
* 只在 read() 时才解压(未引用的条目不消耗内存),解压前后都按声明的大小
|
|
368
|
+
* 校验,任何超限或声明不实都按 zip 炸弹拒绝。
|
|
369
|
+
*/
|
|
370
|
+
function createZipReader(bytes) {
|
|
371
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
372
|
+
let eocd = -1;
|
|
373
|
+
for (let i = bytes.length - 22; i >= 0 && i >= bytes.length - 22 - 65536; i -= 1) {
|
|
374
|
+
if (view.getUint32(i, true) === 0x06054b50) {
|
|
375
|
+
eocd = i;
|
|
376
|
+
break;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (eocd < 0)
|
|
380
|
+
throw new TabularImportError("PARSE_ERROR", "不是合法的 xlsx 文件(找不到 ZIP 目录)");
|
|
381
|
+
const entryCount = view.getUint16(eocd + 10, true);
|
|
382
|
+
if (entryCount > XLSX_MAX_ZIP_ENTRIES) {
|
|
383
|
+
throw new TabularImportError("LIMIT_ZIP_ENTRIES", `xlsx 的 ZIP 条目数 ${entryCount} 超过上限 ${XLSX_MAX_ZIP_ENTRIES},拒绝读取`);
|
|
384
|
+
}
|
|
385
|
+
const cdOffset = view.getUint32(eocd + 16, true);
|
|
386
|
+
const entries = new Map();
|
|
387
|
+
let cursor = cdOffset;
|
|
388
|
+
for (let index = 0; index < entryCount; index += 1) {
|
|
389
|
+
if (cursor + 46 > bytes.length || view.getUint32(cursor, true) !== 0x02014b50) {
|
|
390
|
+
throw new TabularImportError("PARSE_ERROR", "xlsx 的 ZIP 中央目录损坏");
|
|
391
|
+
}
|
|
392
|
+
const method = view.getUint16(cursor + 10, true);
|
|
393
|
+
const compressedSize = view.getUint32(cursor + 20, true);
|
|
394
|
+
const uncompressedSize = view.getUint32(cursor + 24, true);
|
|
395
|
+
const nameLength = view.getUint16(cursor + 28, true);
|
|
396
|
+
const extraLength = view.getUint16(cursor + 30, true);
|
|
397
|
+
const commentLength = view.getUint16(cursor + 32, true);
|
|
398
|
+
const localOffset = view.getUint32(cursor + 42, true);
|
|
399
|
+
const name = new TextDecoder().decode(bytes.subarray(cursor + 46, cursor + 46 + nameLength));
|
|
400
|
+
entries.set(name, { name, method, compressedSize, uncompressedSize, localOffset });
|
|
401
|
+
cursor += 46 + nameLength + extraLength + commentLength;
|
|
402
|
+
}
|
|
403
|
+
const cache = new Map();
|
|
404
|
+
let totalInflated = 0;
|
|
405
|
+
const read = (name) => {
|
|
406
|
+
const cached = cache.get(name);
|
|
407
|
+
if (cached !== undefined)
|
|
408
|
+
return cached;
|
|
409
|
+
const entry = entries.get(name);
|
|
410
|
+
if (entry === undefined)
|
|
411
|
+
return undefined;
|
|
412
|
+
if (entry.uncompressedSize > XLSX_MAX_ENTRY_BYTES) {
|
|
413
|
+
throw new TabularImportError("ZIP_BOMB", `xlsx 内部文件 ${name} 声明解压后 ${entry.uncompressedSize} 字节,超过单条目上限 ${XLSX_MAX_ENTRY_BYTES} 字节(疑似 zip 炸弹),拒绝读取`);
|
|
414
|
+
}
|
|
415
|
+
const local = entry.localOffset;
|
|
416
|
+
if (local + 30 > bytes.length || view.getUint32(local, true) !== 0x04034b50) {
|
|
417
|
+
throw new TabularImportError("PARSE_ERROR", `xlsx 的本地文件头损坏:${entry.name}`);
|
|
418
|
+
}
|
|
419
|
+
const localNameLength = view.getUint16(local + 26, true);
|
|
420
|
+
const localExtraLength = view.getUint16(local + 28, true);
|
|
421
|
+
const dataStart = local + 30 + localNameLength + localExtraLength;
|
|
422
|
+
const data = bytes.subarray(dataStart, dataStart + entry.compressedSize);
|
|
423
|
+
let content;
|
|
424
|
+
if (entry.method === 0) {
|
|
425
|
+
content = data;
|
|
426
|
+
if (content.length !== entry.uncompressedSize) {
|
|
427
|
+
throw new TabularImportError("ZIP_BOMB", `xlsx 内部文件 ${name} 声明大小 ${entry.uncompressedSize} 字节与实际 ${content.length} 字节不符(疑似 zip 炸弹),拒绝读取`);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
else if (entry.method === 8) {
|
|
431
|
+
try {
|
|
432
|
+
content = new Uint8Array(inflateRawSync(Buffer.from(data), { maxOutputLength: XLSX_MAX_ENTRY_BYTES }));
|
|
433
|
+
}
|
|
434
|
+
catch (err) {
|
|
435
|
+
// 输出超过 maxOutputLength 时 Node 抛 RangeError/ERR_BUFFER_TOO_LARGE。
|
|
436
|
+
if (err instanceof RangeError) {
|
|
437
|
+
throw new TabularImportError("ZIP_BOMB", `xlsx 内部文件 ${name} 解压输出超过单条目上限 ${XLSX_MAX_ENTRY_BYTES} 字节(疑似 zip 炸弹),拒绝读取`);
|
|
438
|
+
}
|
|
439
|
+
throw new TabularImportError("PARSE_ERROR", `xlsx 内部文件解压失败:${entry.name}`);
|
|
440
|
+
}
|
|
441
|
+
if (content.length !== entry.uncompressedSize) {
|
|
442
|
+
throw new TabularImportError("ZIP_BOMB", `xlsx 内部文件 ${name} 解压后 ${content.length} 字节与声明的 ${entry.uncompressedSize} 字节不符(疑似 zip 炸弹),拒绝读取`);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
else {
|
|
446
|
+
throw new TabularImportError("PARSE_ERROR", `xlsx 使用了不支持的压缩方式:${entry.name}`);
|
|
447
|
+
}
|
|
448
|
+
totalInflated += content.length;
|
|
449
|
+
if (totalInflated > XLSX_MAX_TOTAL_BYTES) {
|
|
450
|
+
throw new TabularImportError("ZIP_BOMB", `xlsx 内部文件累计解压 ${totalInflated} 字节,超过总上限 ${XLSX_MAX_TOTAL_BYTES} 字节(疑似 zip 炸弹),拒绝读取`);
|
|
451
|
+
}
|
|
452
|
+
cache.set(name, content);
|
|
453
|
+
return content;
|
|
454
|
+
};
|
|
455
|
+
return { read };
|
|
456
|
+
}
|
|
457
|
+
function decodeXmlEntities(text) {
|
|
458
|
+
return text
|
|
459
|
+
.replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCodePoint(Number.parseInt(hex, 16)))
|
|
460
|
+
.replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec)))
|
|
461
|
+
.replace(/</g, "<")
|
|
462
|
+
.replace(/>/g, ">")
|
|
463
|
+
.replace(/"/g, '"')
|
|
464
|
+
.replace(/'/g, "'")
|
|
465
|
+
.replace(/&/g, "&");
|
|
466
|
+
}
|
|
467
|
+
/** Excel 序列日(1900 系,历元 1899-12-30)→ ISO 字符串;整数为纯日期。 */
|
|
468
|
+
function excelSerialToIso(serial) {
|
|
469
|
+
const rounded = Math.round(serial * 86400) / 86400;
|
|
470
|
+
const ms = Math.round((rounded - 25569) * 86400000);
|
|
471
|
+
const date = new Date(ms);
|
|
472
|
+
if (Number.isNaN(date.getTime()))
|
|
473
|
+
return "";
|
|
474
|
+
const hasTime = Math.abs(serial - Math.round(serial)) > 1e-9;
|
|
475
|
+
if (!hasTime)
|
|
476
|
+
return date.toISOString().slice(0, 10);
|
|
477
|
+
return date.toISOString();
|
|
478
|
+
}
|
|
479
|
+
function columnToIndex(ref) {
|
|
480
|
+
const match = /^([A-Z]+)/.exec(ref);
|
|
481
|
+
if (match === null)
|
|
482
|
+
return -1;
|
|
483
|
+
let index = 0;
|
|
484
|
+
for (const ch of match[1] ?? "")
|
|
485
|
+
index = index * 26 + (ch.charCodeAt(0) - 64);
|
|
486
|
+
return index - 1;
|
|
487
|
+
}
|
|
488
|
+
/** 解析第一张工作表为字符串矩阵;数值保持原文,日期样式数值转 ISO。 */
|
|
489
|
+
export function parseXlsx(bytes) {
|
|
490
|
+
if (bytes.length > TABULAR_IMPORT_MAX_BYTES) {
|
|
491
|
+
throw new TabularImportError("LIMIT_BYTES", `文件超过上限 ${TABULAR_IMPORT_MAX_BYTES} 字节`);
|
|
492
|
+
}
|
|
493
|
+
const reader = createZipReader(bytes);
|
|
494
|
+
const sheetPath = resolveFirstSheetPath(reader);
|
|
495
|
+
const sheetXml = reader.read(sheetPath);
|
|
496
|
+
if (sheetXml === undefined) {
|
|
497
|
+
throw new TabularImportError("PARSE_ERROR", `xlsx 里找不到工作表:${sheetPath}`);
|
|
498
|
+
}
|
|
499
|
+
const shared = readSharedStrings(reader.read("xl/sharedStrings.xml"));
|
|
500
|
+
const dateStyles = readDateStyles(reader.read("xl/styles.xml"));
|
|
501
|
+
const xml = new TextDecoder().decode(sheetXml);
|
|
502
|
+
const rows = [];
|
|
503
|
+
const rowRe = /<row[^>]*\br="(\d+)"[^>]*>([\s\S]*?)<\/row>|<row[^>]*\/>/g;
|
|
504
|
+
let rowMatch;
|
|
505
|
+
while ((rowMatch = rowRe.exec(xml)) !== null) {
|
|
506
|
+
if (rows.length >= TABULAR_IMPORT_MAX_ROWS + 1) {
|
|
507
|
+
throw new TabularImportError("LIMIT_ROWS", `数据行超过上限 ${TABULAR_IMPORT_MAX_ROWS} 行`);
|
|
508
|
+
}
|
|
509
|
+
const cells = [];
|
|
510
|
+
const body = rowMatch[2] ?? "";
|
|
511
|
+
const cellRe = /<c([^>]*)(?:\/>|>([\s\S]*?)<\/c>)/g;
|
|
512
|
+
let cellMatch;
|
|
513
|
+
let fallbackColumn = 0;
|
|
514
|
+
while ((cellMatch = cellRe.exec(body)) !== null) {
|
|
515
|
+
const attrs = cellMatch[1] ?? "";
|
|
516
|
+
const inner = cellMatch[2] ?? "";
|
|
517
|
+
const ref = /\br="([A-Z]+\d+)"/.exec(attrs)?.[1] ?? "";
|
|
518
|
+
const type = /\bt="([^"]+)"/.exec(attrs)?.[1] ?? "";
|
|
519
|
+
const style = /\bs="(\d+)"/.exec(attrs)?.[1];
|
|
520
|
+
const column = ref !== "" ? columnToIndex(ref) : fallbackColumn;
|
|
521
|
+
fallbackColumn = column + 1;
|
|
522
|
+
if (column < 0 || column >= TABULAR_IMPORT_MAX_COLUMNS) {
|
|
523
|
+
if (column >= TABULAR_IMPORT_MAX_COLUMNS) {
|
|
524
|
+
throw new TabularImportError("LIMIT_COLUMNS", `列数超过上限 ${TABULAR_IMPORT_MAX_COLUMNS}`);
|
|
525
|
+
}
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
const value = readCellValue(inner, type, style, shared, dateStyles);
|
|
529
|
+
cells[column] = value;
|
|
530
|
+
}
|
|
531
|
+
// cells 是稀疏数组(按列号落位);map/forEach 会跳过空洞导致错位,
|
|
532
|
+
// 必须先稠密化。
|
|
533
|
+
const normalized = Array.from({ length: cells.length }, (_, index) => cells[index] ?? "");
|
|
534
|
+
rows.push(normalized.slice(0, TABULAR_IMPORT_MAX_COLUMNS));
|
|
535
|
+
}
|
|
536
|
+
return rows.filter((line) => !line.every((cell) => cell === ""));
|
|
537
|
+
}
|
|
538
|
+
function resolveFirstSheetPath(reader) {
|
|
539
|
+
const workbook = reader.read("xl/workbook.xml");
|
|
540
|
+
const rels = reader.read("xl/_rels/workbook.xml.rels");
|
|
541
|
+
if (workbook !== undefined && rels !== undefined) {
|
|
542
|
+
const rid = /<sheet[^>]*\br:id="(rId\d+)"/.exec(new TextDecoder().decode(workbook))?.[1];
|
|
543
|
+
if (rid !== undefined) {
|
|
544
|
+
const relXml = new TextDecoder().decode(rels);
|
|
545
|
+
const relRe = new RegExp(`<Relationship[^>]*\\bId="${rid}"[^>]*\\bTarget="([^"]+)"`);
|
|
546
|
+
const target = relRe.exec(relXml)?.[1];
|
|
547
|
+
if (target !== undefined) {
|
|
548
|
+
return target.startsWith("/") ? target.slice(1) : `xl/${target.replace(/^\.\//, "")}`;
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
return "xl/worksheets/sheet1.xml";
|
|
553
|
+
}
|
|
554
|
+
function readCellValue(inner, type, style, shared, dateStyles) {
|
|
555
|
+
if (type === "inlineStr") {
|
|
556
|
+
const parts = [];
|
|
557
|
+
const textRe = /<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g;
|
|
558
|
+
let textMatch;
|
|
559
|
+
while ((textMatch = textRe.exec(inner)) !== null)
|
|
560
|
+
parts.push(decodeXmlEntities(textMatch[1] ?? ""));
|
|
561
|
+
return parts.join("");
|
|
562
|
+
}
|
|
563
|
+
const value = /<v>([\s\S]*?)<\/v>/.exec(inner)?.[1] ?? "";
|
|
564
|
+
if (value === "")
|
|
565
|
+
return "";
|
|
566
|
+
if (type === "s") {
|
|
567
|
+
const index = Number.parseInt(value, 10);
|
|
568
|
+
return shared[index] ?? "";
|
|
569
|
+
}
|
|
570
|
+
if (type === "str" || type === "b") {
|
|
571
|
+
if (type === "b")
|
|
572
|
+
return value === "1" ? "true" : "false";
|
|
573
|
+
return decodeXmlEntities(value);
|
|
574
|
+
}
|
|
575
|
+
// 数值单元格:日期样式 → ISO;否则保留原文(由列转换按数字解析)。
|
|
576
|
+
if (style !== undefined && dateStyles.has(Number(style))) {
|
|
577
|
+
const numeric = Number(value);
|
|
578
|
+
if (Number.isFinite(numeric))
|
|
579
|
+
return excelSerialToIso(numeric);
|
|
580
|
+
}
|
|
581
|
+
return decodeXmlEntities(value);
|
|
582
|
+
}
|
|
583
|
+
function readSharedStrings(xml) {
|
|
584
|
+
if (xml === undefined)
|
|
585
|
+
return [];
|
|
586
|
+
const text = new TextDecoder().decode(xml);
|
|
587
|
+
const strings = [];
|
|
588
|
+
const siRe = /<si>([\s\S]*?)<\/si>/g;
|
|
589
|
+
let siMatch;
|
|
590
|
+
while ((siMatch = siRe.exec(text)) !== null) {
|
|
591
|
+
const parts = [];
|
|
592
|
+
const textRe = /<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g;
|
|
593
|
+
let textMatch;
|
|
594
|
+
while ((textMatch = textRe.exec(siMatch[1] ?? "")) !== null) {
|
|
595
|
+
parts.push(decodeXmlEntities(textMatch[1] ?? ""));
|
|
596
|
+
}
|
|
597
|
+
strings.push(parts.join(""));
|
|
598
|
+
}
|
|
599
|
+
return strings;
|
|
600
|
+
}
|
|
601
|
+
/** 内建日期数字格式(14–22、45–47)+ 自定义含 y/m/d/h/s 的格式。 */
|
|
602
|
+
function readDateStyles(xml) {
|
|
603
|
+
const styles = new Set();
|
|
604
|
+
if (xml === undefined)
|
|
605
|
+
return styles;
|
|
606
|
+
const text = new TextDecoder().decode(xml);
|
|
607
|
+
const customFormats = new Map();
|
|
608
|
+
const fmtRe = /<numFmt[^>]*\bnumFmtId="(\d+)"[^>]*\bformatCode="([^"]*)"/g;
|
|
609
|
+
let fmtMatch;
|
|
610
|
+
while ((fmtMatch = fmtRe.exec(text)) !== null) {
|
|
611
|
+
customFormats.set(Number(fmtMatch[1]), fmtMatch[2] ?? "");
|
|
612
|
+
}
|
|
613
|
+
const cellXfs = /<cellXfs[^>]*>([\s\S]*?)<\/cellXfs>/.exec(text)?.[1] ?? "";
|
|
614
|
+
const xfRe = /<xf\b[^>]*?(?:\/>|>)/g;
|
|
615
|
+
let xfMatch;
|
|
616
|
+
let styleIndex = 0;
|
|
617
|
+
while ((xfMatch = xfRe.exec(cellXfs)) !== null) {
|
|
618
|
+
// xf 可省略 numFmtId(继承样式 0);索引按 xf 出现顺序递增,不能跳过。
|
|
619
|
+
const numFmtId = Number(/\bnumFmtId="(\d+)"/.exec(xfMatch[0])?.[1] ?? 0);
|
|
620
|
+
if ((numFmtId >= 14 && numFmtId <= 22) ||
|
|
621
|
+
(numFmtId >= 45 && numFmtId <= 47) ||
|
|
622
|
+
(customFormats.get(numFmtId) ?? "").replace(/\[[^\]]*\]|"[^"]*"/g, "").match(/[ymdhs]/i) !== null) {
|
|
623
|
+
styles.add(styleIndex);
|
|
624
|
+
}
|
|
625
|
+
styleIndex += 1;
|
|
626
|
+
}
|
|
627
|
+
return styles;
|
|
628
|
+
}
|
|
629
|
+
// ── 模板生成(CSV + xlsx;同一份表头与示例行)────────────────────────
|
|
630
|
+
/** 模板表头(「中文名/字段名」双写),CSV 与 xlsx 模板、别名索引共用。 */
|
|
631
|
+
export const TABULAR_TEMPLATE_HEADER = [
|
|
632
|
+
"商品编号/sku",
|
|
633
|
+
"名称/title",
|
|
634
|
+
"币种/currency",
|
|
635
|
+
"计价单位/unit",
|
|
636
|
+
"单价/price",
|
|
637
|
+
"起订量/moq",
|
|
638
|
+
"库存/stock",
|
|
639
|
+
"供货说明/supply_note",
|
|
640
|
+
"更新时间/updated_at",
|
|
641
|
+
"有效期至/valid_until",
|
|
642
|
+
"状态/status",
|
|
643
|
+
];
|
|
644
|
+
export const TABULAR_TEMPLATE_EXAMPLE_ROWS = [
|
|
645
|
+
[
|
|
646
|
+
"DEMO-001",
|
|
647
|
+
"不锈钢保温杯 500ml",
|
|
648
|
+
"CNY",
|
|
649
|
+
"piece",
|
|
650
|
+
"29.90",
|
|
651
|
+
"50",
|
|
652
|
+
"2000",
|
|
653
|
+
"现货,下单后 3 个工作日发货",
|
|
654
|
+
"",
|
|
655
|
+
"2027-12-31",
|
|
656
|
+
"在售",
|
|
657
|
+
],
|
|
658
|
+
[
|
|
659
|
+
"DEMO-002",
|
|
660
|
+
"瓦楞纸箱 五层加强",
|
|
661
|
+
"CNY",
|
|
662
|
+
"box",
|
|
663
|
+
"3.50",
|
|
664
|
+
"100",
|
|
665
|
+
"8000",
|
|
666
|
+
"按订单生产,约 7 天交期",
|
|
667
|
+
"2026-09-01",
|
|
668
|
+
"2028-06-30",
|
|
669
|
+
"在售",
|
|
670
|
+
],
|
|
671
|
+
];
|
|
672
|
+
function csvEscape(cell) {
|
|
673
|
+
return /[",\r\n]/.test(cell) ? `"${cell.replace(/"/g, '""')}"` : cell;
|
|
674
|
+
}
|
|
675
|
+
/** CSV 模板(带 BOM,Excel 直接打开中文不乱码;本模块的解析器会剥掉 BOM)。 */
|
|
676
|
+
export function renderImportTemplateCsv() {
|
|
677
|
+
const lines = [TABULAR_TEMPLATE_HEADER, ...TABULAR_TEMPLATE_EXAMPLE_ROWS].map((row) => row.map(csvEscape).join(","));
|
|
678
|
+
return `\ufeff${lines.join("\r\n")}\r\n`;
|
|
679
|
+
}
|
|
680
|
+
// ── xlsx 模板写出(stored ZIP:无需压缩,只算 CRC32)──────────────────
|
|
681
|
+
const CRC_TABLE = (() => {
|
|
682
|
+
const table = new Array(256);
|
|
683
|
+
for (let n = 0; n < 256; n += 1) {
|
|
684
|
+
let c = n;
|
|
685
|
+
for (let k = 0; k < 8; k += 1)
|
|
686
|
+
c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
|
687
|
+
table[n] = c >>> 0;
|
|
688
|
+
}
|
|
689
|
+
return table;
|
|
690
|
+
})();
|
|
691
|
+
function crc32(bytes) {
|
|
692
|
+
let crc = 0xffffffff;
|
|
693
|
+
for (const byte of bytes)
|
|
694
|
+
crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);
|
|
695
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
696
|
+
}
|
|
697
|
+
function xmlEscape(text) {
|
|
698
|
+
return text.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c] ?? c);
|
|
699
|
+
}
|
|
700
|
+
/** 打一个最小 stored ZIP(全 ASCII 文件名;UTF-8 内容)。 */
|
|
701
|
+
function buildStoredZip(entries) {
|
|
702
|
+
const encoder = new TextEncoder();
|
|
703
|
+
const locals = [];
|
|
704
|
+
const centrals = [];
|
|
705
|
+
let offset = 0;
|
|
706
|
+
for (const entry of entries) {
|
|
707
|
+
const nameBytes = encoder.encode(entry.name);
|
|
708
|
+
const dataBytes = encoder.encode(entry.content);
|
|
709
|
+
const crc = crc32(dataBytes);
|
|
710
|
+
const local = new Uint8Array(30 + nameBytes.length);
|
|
711
|
+
const localView = new DataView(local.buffer);
|
|
712
|
+
localView.setUint32(0, 0x04034b50, true);
|
|
713
|
+
localView.setUint16(4, 20, true);
|
|
714
|
+
localView.setUint16(6, 0x0800, true); // UTF-8 文件名标志
|
|
715
|
+
localView.setUint16(8, 0, true); // stored
|
|
716
|
+
localView.setUint32(14, crc, true);
|
|
717
|
+
localView.setUint32(18, dataBytes.length, true);
|
|
718
|
+
localView.setUint32(22, dataBytes.length, true);
|
|
719
|
+
localView.setUint16(26, nameBytes.length, true);
|
|
720
|
+
local.set(nameBytes, 30);
|
|
721
|
+
const central = new Uint8Array(46 + nameBytes.length);
|
|
722
|
+
const centralView = new DataView(central.buffer);
|
|
723
|
+
centralView.setUint32(0, 0x02014b50, true);
|
|
724
|
+
centralView.setUint16(4, 20, true);
|
|
725
|
+
centralView.setUint16(6, 20, true);
|
|
726
|
+
centralView.setUint16(8, 0x0800, true);
|
|
727
|
+
centralView.setUint16(10, 0, true);
|
|
728
|
+
centralView.setUint32(16, crc, true);
|
|
729
|
+
centralView.setUint32(20, dataBytes.length, true);
|
|
730
|
+
centralView.setUint32(24, dataBytes.length, true);
|
|
731
|
+
centralView.setUint16(28, nameBytes.length, true);
|
|
732
|
+
centralView.setUint32(42, offset, true);
|
|
733
|
+
central.set(nameBytes, 46);
|
|
734
|
+
locals.push(local, dataBytes);
|
|
735
|
+
centrals.push(central);
|
|
736
|
+
offset += local.length + dataBytes.length;
|
|
737
|
+
}
|
|
738
|
+
const centralSize = centrals.reduce((sum, chunk) => sum + chunk.length, 0);
|
|
739
|
+
const eocd = new Uint8Array(22);
|
|
740
|
+
const eocdView = new DataView(eocd.buffer);
|
|
741
|
+
eocdView.setUint32(0, 0x06054b50, true);
|
|
742
|
+
eocdView.setUint16(8, entries.length, true);
|
|
743
|
+
eocdView.setUint16(10, entries.length, true);
|
|
744
|
+
eocdView.setUint32(12, centralSize, true);
|
|
745
|
+
eocdView.setUint32(16, offset, true);
|
|
746
|
+
const totalLength = offset + centralSize + 22;
|
|
747
|
+
const out = new Uint8Array(totalLength);
|
|
748
|
+
let cursor = 0;
|
|
749
|
+
for (const chunk of [...locals, ...centrals, eocd]) {
|
|
750
|
+
out.set(chunk, cursor);
|
|
751
|
+
cursor += chunk.length;
|
|
752
|
+
}
|
|
753
|
+
return out;
|
|
754
|
+
}
|
|
755
|
+
function sheetXmlFromGrid(rows) {
|
|
756
|
+
const columnCount = Math.max(...rows.map((row) => row.length));
|
|
757
|
+
const body = rows
|
|
758
|
+
.map((row, rowIndex) => {
|
|
759
|
+
const cells = row
|
|
760
|
+
.map((cell, columnIndex) => cell === ""
|
|
761
|
+
? ""
|
|
762
|
+
: `<c r="${columnName(columnIndex)}${rowIndex + 1}" t="inlineStr"><is><t xml:space="preserve">${xmlEscape(cell)}</t></is></c>`)
|
|
763
|
+
.join("");
|
|
764
|
+
return `<row r="${rowIndex + 1}">${cells}</row>`;
|
|
765
|
+
})
|
|
766
|
+
.join("");
|
|
767
|
+
const cols = Array.from({ length: columnCount }, (_, index) => {
|
|
768
|
+
const width = index === 0 || index === 7 ? 260 : 110;
|
|
769
|
+
return `<col min="${index + 1}" max="${index + 1}" width="${width}" customWidth="1"/>`;
|
|
770
|
+
}).join("");
|
|
771
|
+
return (`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
|
|
772
|
+
`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">` +
|
|
773
|
+
`<cols>${cols}</cols><sheetData>${body}</sheetData></worksheet>`);
|
|
774
|
+
}
|
|
775
|
+
function columnName(index) {
|
|
776
|
+
let name = "";
|
|
777
|
+
let rest = index;
|
|
778
|
+
do {
|
|
779
|
+
name = String.fromCharCode(65 + (rest % 26)) + name;
|
|
780
|
+
rest = Math.floor(rest / 26) - 1;
|
|
781
|
+
} while (rest >= 0);
|
|
782
|
+
return name;
|
|
783
|
+
}
|
|
784
|
+
/** xlsx 模板(单工作表「商品导入模板」;单元格为内联字符串,stored ZIP)。 */
|
|
785
|
+
export function renderImportTemplateXlsx() {
|
|
786
|
+
const grid = [TABULAR_TEMPLATE_HEADER, ...TABULAR_TEMPLATE_EXAMPLE_ROWS];
|
|
787
|
+
return buildStoredZip([
|
|
788
|
+
{
|
|
789
|
+
name: "[Content_Types].xml",
|
|
790
|
+
content: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
|
|
791
|
+
`<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
|
|
792
|
+
`<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>` +
|
|
793
|
+
`<Default Extension="xml" ContentType="application/xml"/>` +
|
|
794
|
+
`<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>` +
|
|
795
|
+
`<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>` +
|
|
796
|
+
`</Types>`,
|
|
797
|
+
},
|
|
798
|
+
{
|
|
799
|
+
name: "_rels/.rels",
|
|
800
|
+
content: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
|
|
801
|
+
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
|
|
802
|
+
`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>` +
|
|
803
|
+
`</Relationships>`,
|
|
804
|
+
},
|
|
805
|
+
{
|
|
806
|
+
name: "xl/workbook.xml",
|
|
807
|
+
content: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
|
|
808
|
+
`<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" ` +
|
|
809
|
+
`xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">` +
|
|
810
|
+
`<sheets><sheet name="商品导入模板" sheetId="1" r:id="rId1"/></sheets></workbook>`,
|
|
811
|
+
},
|
|
812
|
+
{
|
|
813
|
+
name: "xl/_rels/workbook.xml.rels",
|
|
814
|
+
content: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
|
|
815
|
+
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
|
|
816
|
+
`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>` +
|
|
817
|
+
`</Relationships>`,
|
|
818
|
+
},
|
|
819
|
+
{ name: "xl/worksheets/sheet1.xml", content: sheetXmlFromGrid(grid) },
|
|
820
|
+
]);
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* CSV/xlsx → 云端商品表。任何行级/格级问题都进 `errors`(整表拒绝、逐条列
|
|
824
|
+
* 出);成功时再过一次 `parseProductTable`(复用既有严格校验,纵深防御)。
|
|
825
|
+
*/
|
|
826
|
+
export function convertTabularImport(input, options) {
|
|
827
|
+
const now = options.now ?? (() => new Date());
|
|
828
|
+
const errors = [];
|
|
829
|
+
let grid;
|
|
830
|
+
try {
|
|
831
|
+
grid = input.kind === "csv" ? parseCsv(input.text) : parseXlsx(input.bytes);
|
|
832
|
+
}
|
|
833
|
+
catch (err) {
|
|
834
|
+
if (err instanceof TabularImportError) {
|
|
835
|
+
return {
|
|
836
|
+
ok: false,
|
|
837
|
+
report: { format: input.kind, rows: 0, header_mapping: [], unrecognized_columns: [], defaulted_fields: [], skipped_empty_rows: 0 },
|
|
838
|
+
errors: [{ code: err.code, message: err.message }],
|
|
839
|
+
};
|
|
840
|
+
}
|
|
841
|
+
throw err;
|
|
842
|
+
}
|
|
843
|
+
const report = {
|
|
844
|
+
format: input.kind,
|
|
845
|
+
rows: 0,
|
|
846
|
+
header_mapping: [],
|
|
847
|
+
unrecognized_columns: [],
|
|
848
|
+
defaulted_fields: [],
|
|
849
|
+
skipped_empty_rows: 0,
|
|
850
|
+
};
|
|
851
|
+
const headerRow = grid[0];
|
|
852
|
+
if (headerRow === undefined || headerRow.every((cell) => cell.trim() === "")) {
|
|
853
|
+
return { ok: false, report, errors: [{ code: "EMPTY_TABLE", message: "表格是空的:第一行应为表头" }] };
|
|
854
|
+
}
|
|
855
|
+
if (grid.length - 1 <= 0) {
|
|
856
|
+
return { ok: false, report, errors: [{ code: "EMPTY_TABLE", message: "表格只有表头,没有商品行" }] };
|
|
857
|
+
}
|
|
858
|
+
if (headerRow.length > TABULAR_IMPORT_MAX_COLUMNS) {
|
|
859
|
+
return {
|
|
860
|
+
ok: false,
|
|
861
|
+
report,
|
|
862
|
+
errors: [
|
|
863
|
+
{
|
|
864
|
+
code: "LIMIT_COLUMNS",
|
|
865
|
+
message: `表头有 ${headerRow.length} 列,超过上限 ${TABULAR_IMPORT_MAX_COLUMNS} 列`,
|
|
866
|
+
},
|
|
867
|
+
],
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
// 表头识别 + 成本列拒绝。
|
|
871
|
+
const columnField = [];
|
|
872
|
+
headerRow.forEach((raw, index) => {
|
|
873
|
+
const trimmed = raw.trim();
|
|
874
|
+
if (trimmed === "") {
|
|
875
|
+
report.header_mapping.push({ column: trimmed });
|
|
876
|
+
columnField.push(undefined);
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
const normalized = normalizeHeader(trimmed);
|
|
880
|
+
const field = ALIAS_INDEX.get(normalized);
|
|
881
|
+
if (field !== undefined) {
|
|
882
|
+
report.header_mapping.push({ column: trimmed, field });
|
|
883
|
+
columnField.push(field);
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
if (isCostColumn(normalized)) {
|
|
887
|
+
errors.push({
|
|
888
|
+
column: trimmed,
|
|
889
|
+
code: "COST_COLUMN",
|
|
890
|
+
message: `第 ${index + 1} 列「${trimmed}」疑似底价/成本/进价列:底价与成本属于私密报价策略,不能出现在公开商品表里。请删除该列(及同类列)后重新导出再导入。`,
|
|
891
|
+
});
|
|
892
|
+
report.header_mapping.push({ column: trimmed });
|
|
893
|
+
columnField.push(undefined);
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
report.header_mapping.push({ column: trimmed });
|
|
897
|
+
report.unrecognized_columns.push(trimmed);
|
|
898
|
+
columnField.push(undefined);
|
|
899
|
+
});
|
|
900
|
+
const hasCostColumn = errors.some((issue) => issue.code === "COST_COLUMN");
|
|
901
|
+
if (hasCostColumn)
|
|
902
|
+
return { ok: false, report, errors };
|
|
903
|
+
// 必需列检查(缺价格单独点名,其余列出一并报)。
|
|
904
|
+
const present = new Set(columnField.filter((field) => field !== undefined));
|
|
905
|
+
for (const spec of TABULAR_FIELDS) {
|
|
906
|
+
if (spec.required && !present.has(spec.field)) {
|
|
907
|
+
const label = spec.field === "price" ? "单价/价格" : `${spec.zh}(${spec.field})`;
|
|
908
|
+
errors.push({
|
|
909
|
+
field: spec.field,
|
|
910
|
+
code: "MISSING_COLUMN",
|
|
911
|
+
message: `表头缺少必需列:${label}。请按导入模板补齐后再导入(模板可在工作台「商品与导入」页下载)。`,
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
if (!spec.required && !present.has(spec.field)) {
|
|
915
|
+
report.defaulted_fields.push(spec.field);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
if (errors.length > 0)
|
|
919
|
+
return { ok: false, report, errors };
|
|
920
|
+
// 数据行 → CloudProductRecord。
|
|
921
|
+
const columnIndex = new Map();
|
|
922
|
+
columnField.forEach((field, index) => {
|
|
923
|
+
if (field !== undefined && !columnIndex.has(field))
|
|
924
|
+
columnIndex.set(field, index);
|
|
925
|
+
});
|
|
926
|
+
const cellOf = (row, field) => {
|
|
927
|
+
const index = columnIndex.get(field);
|
|
928
|
+
return index === undefined ? "" : (row[index] ?? "").trim();
|
|
929
|
+
};
|
|
930
|
+
const products = [];
|
|
931
|
+
const skuRows = new Map();
|
|
932
|
+
for (let index = 1; index < grid.length; index += 1) {
|
|
933
|
+
const row = grid[index] ?? [];
|
|
934
|
+
const rowNumber = index + 1; // 表头是第 1 行,与 Excel 行号一致。
|
|
935
|
+
if (row.every((cell) => cell.trim() === "")) {
|
|
936
|
+
report.skipped_empty_rows += 1;
|
|
937
|
+
continue;
|
|
938
|
+
}
|
|
939
|
+
if (products.length >= TABULAR_IMPORT_MAX_ROWS) {
|
|
940
|
+
errors.push({
|
|
941
|
+
code: "LIMIT_ROWS",
|
|
942
|
+
message: `数据行超过上限 ${TABULAR_IMPORT_MAX_ROWS} 行(第 ${rowNumber} 行起未读取)。请分批导入或精简表格。`,
|
|
943
|
+
});
|
|
944
|
+
break;
|
|
945
|
+
}
|
|
946
|
+
report.rows += 1;
|
|
947
|
+
for (const [field] of columnIndex) {
|
|
948
|
+
const cell = cellOf(row, field);
|
|
949
|
+
if (cell.length > TABULAR_IMPORT_MAX_CELL_CHARS) {
|
|
950
|
+
errors.push({
|
|
951
|
+
row: rowNumber,
|
|
952
|
+
field,
|
|
953
|
+
code: "CELL_TOO_LONG",
|
|
954
|
+
message: `第 ${rowNumber} 行「${field}」超过 ${TABULAR_IMPORT_MAX_CELL_CHARS} 字符`,
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
const sku = cellOf(row, "sku");
|
|
959
|
+
if (sku === "") {
|
|
960
|
+
errors.push({ row: rowNumber, field: "sku", code: "EMPTY_REQUIRED", message: `第 ${rowNumber} 行商品编号(sku)为空` });
|
|
961
|
+
}
|
|
962
|
+
const title = cellOf(row, "title");
|
|
963
|
+
if (title === "") {
|
|
964
|
+
errors.push({ row: rowNumber, field: "title", code: "EMPTY_REQUIRED", message: `第 ${rowNumber} 行名称(title)为空` });
|
|
965
|
+
}
|
|
966
|
+
const unit = cellOf(row, "unit");
|
|
967
|
+
if (unit === "") {
|
|
968
|
+
errors.push({ row: rowNumber, field: "unit", code: "EMPTY_REQUIRED", message: `第 ${rowNumber} 行计价单位(unit)为空` });
|
|
969
|
+
}
|
|
970
|
+
const priceRaw = cellOf(row, "price");
|
|
971
|
+
const price = parseCellNumber(priceRaw);
|
|
972
|
+
if (priceRaw === "") {
|
|
973
|
+
errors.push({ row: rowNumber, field: "price", code: "EMPTY_REQUIRED", message: `第 ${rowNumber} 行单价(price)为空:价格必须由商家提供,不能缺省` });
|
|
974
|
+
}
|
|
975
|
+
else if (Number.isNaN(price) || price <= 0) {
|
|
976
|
+
errors.push({ row: rowNumber, field: "price", code: "BAD_NUMBER", message: `第 ${rowNumber} 行单价不是正数(收到「${priceRaw}」)` });
|
|
977
|
+
}
|
|
978
|
+
const currencyRaw = cellOf(row, "currency");
|
|
979
|
+
const currency = parseCellCurrency(currencyRaw);
|
|
980
|
+
if (currencyRaw === "") {
|
|
981
|
+
errors.push({ row: rowNumber, field: "currency", code: "EMPTY_REQUIRED", message: `第 ${rowNumber} 行币种为空` });
|
|
982
|
+
}
|
|
983
|
+
else if (currency === "") {
|
|
984
|
+
errors.push({ row: rowNumber, field: "currency", code: "BAD_CURRENCY", message: `第 ${rowNumber} 行币种无法识别(收到「${currencyRaw}」):请填三字母代码(如 CNY/USD)或常见中文名(人民币/美元/欧元/港币/日元/英镑)` });
|
|
985
|
+
}
|
|
986
|
+
const validRaw = cellOf(row, "valid_until");
|
|
987
|
+
const validUntil = parseCellDate(validRaw, { endOfDay: true });
|
|
988
|
+
if (validRaw === "") {
|
|
989
|
+
errors.push({ row: rowNumber, field: "valid_until", code: "EMPTY_REQUIRED", message: `第 ${rowNumber} 行有效期至为空:请填商品可报价的截止日期(如 2027-12-31)` });
|
|
990
|
+
}
|
|
991
|
+
else if (validUntil === "") {
|
|
992
|
+
errors.push({ row: rowNumber, field: "valid_until", code: "BAD_DATE", message: `第 ${rowNumber} 行有效期不是合法日期(收到「${validRaw}」):请用 2027-12-31、2027/12/31 或 2027年12月31日 格式` });
|
|
993
|
+
}
|
|
994
|
+
const updatedRaw = cellOf(row, "updated_at");
|
|
995
|
+
const updatedAt = updatedRaw === "" ? now().toISOString() : parseCellDate(updatedRaw, { endOfDay: false });
|
|
996
|
+
if (updatedRaw !== "" && updatedAt === "") {
|
|
997
|
+
errors.push({ row: rowNumber, field: "updated_at", code: "BAD_DATE", message: `第 ${rowNumber} 行更新时间不是合法日期(收到「${updatedRaw}」):留空将自动使用导入时间` });
|
|
998
|
+
}
|
|
999
|
+
const statusRaw = cellOf(row, "status");
|
|
1000
|
+
const status = statusRaw === "" ? "active" : parseCellStatus(statusRaw);
|
|
1001
|
+
if (statusRaw !== "" && status === "") {
|
|
1002
|
+
errors.push({ row: rowNumber, field: "status", code: "BAD_STATUS", message: `第 ${rowNumber} 行状态无法识别(收到「${statusRaw}」):留空=在售;或填 在售/暂停` });
|
|
1003
|
+
}
|
|
1004
|
+
const moqRaw = cellOf(row, "moq");
|
|
1005
|
+
let moq;
|
|
1006
|
+
if (moqRaw !== "") {
|
|
1007
|
+
const parsed = parseCellNumber(moqRaw);
|
|
1008
|
+
if (Number.isNaN(parsed) || !Number.isInteger(parsed) || parsed <= 0) {
|
|
1009
|
+
errors.push({ row: rowNumber, field: "moq", code: "BAD_NUMBER", message: `第 ${rowNumber} 行起订量必须是正整数(收到「${moqRaw}」)` });
|
|
1010
|
+
}
|
|
1011
|
+
else {
|
|
1012
|
+
moq = parsed;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
const stockRaw = cellOf(row, "stock");
|
|
1016
|
+
let stock;
|
|
1017
|
+
if (stockRaw !== "") {
|
|
1018
|
+
const parsed = parseCellNumber(stockRaw);
|
|
1019
|
+
if (Number.isNaN(parsed) || !Number.isInteger(parsed) || parsed < 0) {
|
|
1020
|
+
errors.push({ row: rowNumber, field: "stock", code: "BAD_NUMBER", message: `第 ${rowNumber} 行库存必须是非负整数(收到「${stockRaw}」);不确定就留空,不要填 0 冒充` });
|
|
1021
|
+
}
|
|
1022
|
+
else {
|
|
1023
|
+
stock = parsed;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
if (sku !== "") {
|
|
1027
|
+
const firstRow = skuRows.get(sku);
|
|
1028
|
+
if (firstRow !== undefined) {
|
|
1029
|
+
errors.push({ row: rowNumber, field: "sku", code: "DUPLICATE_SKU", message: `第 ${rowNumber} 行商品编号「${sku}」与第 ${firstRow} 行重复:同一 SKU 只能出现一次` });
|
|
1030
|
+
}
|
|
1031
|
+
else {
|
|
1032
|
+
skuRows.set(sku, rowNumber);
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
products.push({
|
|
1036
|
+
sku,
|
|
1037
|
+
title,
|
|
1038
|
+
currency: currency === "" ? currencyRaw : currency,
|
|
1039
|
+
unit,
|
|
1040
|
+
price: Number.isNaN(price) ? 0 : Math.round(price * 100) / 100,
|
|
1041
|
+
...(moq !== undefined ? { moq } : {}),
|
|
1042
|
+
...(stock !== undefined ? { stock } : {}),
|
|
1043
|
+
...(cellOf(row, "supply_note") !== "" ? { supply_note: cellOf(row, "supply_note") } : {}),
|
|
1044
|
+
updated_at: updatedAt === "" ? now().toISOString() : updatedAt,
|
|
1045
|
+
valid_until: validUntil === "" ? validRaw : validUntil,
|
|
1046
|
+
status: status === "" ? "active" : status,
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
if (errors.length > 0)
|
|
1050
|
+
return { ok: false, report, errors };
|
|
1051
|
+
if (products.length === 0) {
|
|
1052
|
+
return { ok: false, report, errors: [{ code: "EMPTY_TABLE", message: "表格没有有效商品行" }] };
|
|
1053
|
+
}
|
|
1054
|
+
const table = {
|
|
1055
|
+
schema_version: PRODUCT_TABLE_SCHEMA_VERSION,
|
|
1056
|
+
// WP5 语义:merchant_id 是 Catalog 确认后的身份,只在绑定后由服务端注入;
|
|
1057
|
+
// 转换产物只声明本地租户边界 runtime_owner_id(绑定前导入即保存,不因此被拒)。
|
|
1058
|
+
runtime_owner_id: options.merchantId,
|
|
1059
|
+
source: "merchant_upload",
|
|
1060
|
+
generated_at: now().toISOString(),
|
|
1061
|
+
products,
|
|
1062
|
+
};
|
|
1063
|
+
try {
|
|
1064
|
+
// 复用 product-source 的严格校验(任何结构问题都不放行)。
|
|
1065
|
+
parseProductTable(table, "tabular import");
|
|
1066
|
+
}
|
|
1067
|
+
catch (err) {
|
|
1068
|
+
const message = err instanceof ProductTableError ? err.message : String(err);
|
|
1069
|
+
return { ok: false, report, errors: [{ code: "TABLE_INVALID", message: `转换结果未通过商品表校验:${message}` }] };
|
|
1070
|
+
}
|
|
1071
|
+
return { ok: true, table, report, errors: [] };
|
|
1072
|
+
}
|
|
1073
|
+
//# sourceMappingURL=product-import-tabular.js.map
|