@sea-ecommerce/admin-mcp-server 0.2.2 → 0.2.3

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.
@@ -21947,6 +21947,88 @@ var MedusaAdminClient = class {
21947
21947
  listCollections(params = {}) {
21948
21948
  return this.request("GET", `/admin/collections${buildQuery(params)}`);
21949
21949
  }
21950
+ // ─── 产品分类(Product Categories)───
21951
+ // ⚠️ Medusa v2 契约:列表响应键为 product_categories,单条为 product_category;
21952
+ // 更新是 POST /admin/product-categories/:id(非 PUT/PATCH);父级字段名为 parent_category_id(非 parent_id)。
21953
+ listProductCategories(params = {}) {
21954
+ return this.request("GET", `/admin/product-categories${buildQuery(params)}`);
21955
+ }
21956
+ getProductCategory(id) {
21957
+ return this.request("GET", `/admin/product-categories/${encodeURIComponent(id)}`);
21958
+ }
21959
+ createProductCategory(body) {
21960
+ return this.request("POST", "/admin/product-categories", body);
21961
+ }
21962
+ updateProductCategory(id, body) {
21963
+ return this.request("POST", `/admin/product-categories/${encodeURIComponent(id)}`, body);
21964
+ }
21965
+ deleteProductCategory(id) {
21966
+ return this.request("DELETE", `/admin/product-categories/${encodeURIComponent(id)}`);
21967
+ }
21968
+ /**
21969
+ * 把「分类 id / handle / name」解析为分类 id。
21970
+ * ⚠️ GET /admin/product-categories/:id 只认 id;handle/name 必须走列表端点解析。
21971
+ * id 直接返回;否则先按 handle 精确匹配(?handle=),再按 q 查并在结果里精确比 name。
21972
+ */
21973
+ async resolveProductCategoryId(idOrHandleOrName) {
21974
+ const s = idOrHandleOrName.trim();
21975
+ if (/^pcat_[a-z0-9]+$/i.test(s)) return s;
21976
+ try {
21977
+ const byHandle = await this.request(
21978
+ "GET",
21979
+ `/admin/product-categories${buildQuery({ handle: s, limit: 10 })}`
21980
+ );
21981
+ const handleList = byHandle?.product_categories || [];
21982
+ const exactHandle = handleList.find((c) => c.handle === s);
21983
+ if (exactHandle) return exactHandle.id;
21984
+ const byName = await this.request(
21985
+ "GET",
21986
+ `/admin/product-categories${buildQuery({ q: s, limit: 100 })}`
21987
+ );
21988
+ const nameList = byName?.product_categories || [];
21989
+ const exactName = nameList.find((c) => c.name === s);
21990
+ return (exactName ?? nameList[0])?.id || null;
21991
+ } catch {
21992
+ return null;
21993
+ }
21994
+ }
21995
+ // ─── 产品系列 / 集合(Collections)───
21996
+ // ⚠️ 更新是 POST /admin/collections/:id;官方 validator 字段仅 title/handle/external_id/metadata(无 description)。
21997
+ getCollection(id) {
21998
+ return this.request("GET", `/admin/collections/${encodeURIComponent(id)}`);
21999
+ }
22000
+ createCollection(body) {
22001
+ return this.request("POST", "/admin/collections", body);
22002
+ }
22003
+ updateCollection(id, body) {
22004
+ return this.request("POST", `/admin/collections/${encodeURIComponent(id)}`, body);
22005
+ }
22006
+ deleteCollection(id) {
22007
+ return this.request("DELETE", `/admin/collections/${encodeURIComponent(id)}`);
22008
+ }
22009
+ /**
22010
+ * 把「系列 id / handle / title」解析为系列 id。
22011
+ * ⚠️ GET /admin/collections/:id 只认 id;handle/title 必须走列表端点解析。
22012
+ */
22013
+ async resolveCollectionId(idOrHandleOrTitle) {
22014
+ const s = idOrHandleOrTitle.trim();
22015
+ if (/^pcol_[a-z0-9]+$/i.test(s)) return s;
22016
+ try {
22017
+ const byHandle = await this.request(
22018
+ "GET",
22019
+ `/admin/collections${buildQuery({ handle: s, limit: 10 })}`
22020
+ );
22021
+ const handleList = byHandle?.collections || [];
22022
+ const exactHandle = handleList.find((c) => c.handle === s);
22023
+ if (exactHandle) return exactHandle.id;
22024
+ const byTitle = await this.request("GET", `/admin/collections${buildQuery({ q: s, limit: 100 })}`);
22025
+ const titleList = byTitle?.collections || [];
22026
+ const exactTitle = titleList.find((c) => c.title === s);
22027
+ return (exactTitle ?? titleList[0])?.id || null;
22028
+ } catch {
22029
+ return null;
22030
+ }
22031
+ }
21950
22032
  /**
21951
22033
  * 把一组商品加入销售渠道(POST /admin/sales-channels/{id}/products)。
21952
22034
  * ⚠️ 注意:Medusa v2 该端点挂在「渠道」下,不是商品下;body 为 { add:[productIds], remove:[] }。
@@ -21958,6 +22040,67 @@ var MedusaAdminClient = class {
21958
22040
  remove: []
21959
22041
  });
21960
22042
  }
22043
+ /**
22044
+ * 原生 CSV 导入(Medusa 后台 Products → Import 的等效自动化):
22045
+ * 把本地 CSV 以 multipart 上传到 POST /admin/products/import,返回 transaction_id 与 summary(toCreate/toUpdate)。
22046
+ * ⚠️ 该端点只「登记」导入事务,需再调用 confirmProductImport 才会真正在后台批量建/更商品;
22047
+ * 仅上传不 confirm 时零副作用(不会创建任何商品),可安全用于预检 CSV 是否合法、将建/更多少款。
22048
+ */
22049
+ async importProductsCsv(fileBuffer, filename) {
22050
+ const form = new FormData();
22051
+ form.append("file", new Blob([new Uint8Array(fileBuffer)], { type: "text/csv" }), filename);
22052
+ const doPost = async () => {
22053
+ const res = await fetch(`${this.config.backendUrl}/admin/products/import`, {
22054
+ method: "POST",
22055
+ headers: this.auth.headers(),
22056
+ body: form
22057
+ });
22058
+ if (res.status === 401) {
22059
+ this.auth.clear();
22060
+ await this.auth.login();
22061
+ return doPost();
22062
+ }
22063
+ if (!res.ok) {
22064
+ const text = await res.text();
22065
+ throw new MedusaAdminError(res.status, text || res.statusText);
22066
+ }
22067
+ return await res.json();
22068
+ };
22069
+ return doPost();
22070
+ }
22071
+ /**
22072
+ * 确认 CSV 导入:触发后台批量建/更商品(POST /admin/products/import/{transaction_id}/confirm)。
22073
+ * Medusa 的导入工作流默认「等待确认」才执行,所以上传后必须显式 confirm。
22074
+ */
22075
+ async confirmProductImport(transactionId) {
22076
+ await this.request("POST", `/admin/products/import/${encodeURIComponent(transactionId)}/confirm`, {});
22077
+ }
22078
+ /**
22079
+ * 查询导入工作流执行状态。
22080
+ * ⚠️ Medusa 2.21 **没有** `/admin/workflows/executions/{id}` 这个路径:只能走列表端点
22081
+ * `GET /admin/workflows-executions?transaction_id=<id>&workflow_id=import-products`,
22082
+ * 返回 `{ workflow_executions: [{ state, execution, ... }] }`——状态字段是 `state` 而不是 `status`。
22083
+ * 查不到记录时返回 null,由调用方兜底(不抛错)。
22084
+ */
22085
+ async getWorkflowExecution(transactionId, workflowId = "import-products") {
22086
+ const data = await this.request(
22087
+ "GET",
22088
+ `/admin/workflows-executions${buildQuery({ transaction_id: transactionId, workflow_id: workflowId })}`
22089
+ );
22090
+ const row = (data?.workflow_executions || [])[0];
22091
+ if (!row) return null;
22092
+ return { state: String(row.state || "") };
22093
+ }
22094
+ /**
22095
+ * 为已有商品的选项补取值(POST /admin/products/{id}/options/batch 的 update 段,Medusa ≥2.17)。
22096
+ * 更新商品(POST /admin/products/{id})自 2.16 起禁止传 `options`,新增选项/取值只能走本端点;
22097
+ * 新建变体前必须先确保其引用的选项取值已存在,否则商品 update 会因找不到选项值而失败。
22098
+ */
22099
+ addProductOptionValues(productId, update) {
22100
+ return this.request("POST", `/admin/products/${encodeURIComponent(productId)}/options/batch`, {
22101
+ update
22102
+ });
22103
+ }
21961
22104
  // ─── 商品详情页富内容(product_content 模块)───
21962
22105
  /**
21963
22106
  * 读取某商品某语言的富内容块(GET /admin/product-contents)。
@@ -23227,6 +23370,366 @@ storefront \u8BE6\u60C5\u9875\u300C\u5BCC\u5185\u5BB9\u300D\u533A\u7531\u8FD9\u4
23227
23370
  }
23228
23371
  ];
23229
23372
 
23373
+ // src/tools/categories.ts
23374
+ var categoryTranslationShape = external_exports.object({
23375
+ name: external_exports.string().optional(),
23376
+ description: external_exports.string().optional()
23377
+ });
23378
+ function toCategoryTranslations(raw) {
23379
+ return Object.entries(raw ?? {}).map(([locale, t]) => ({
23380
+ locale_code: canonLocaleKey(locale),
23381
+ translations: Object.fromEntries(
23382
+ Object.entries(t ?? {}).filter(([, v]) => v !== void 0 && v !== null)
23383
+ )
23384
+ }));
23385
+ }
23386
+ var categoryTools = [
23387
+ {
23388
+ name: "list_product_categories",
23389
+ description: "\u67E5\u8BE2\u540E\u53F0\u4EA7\u54C1\u5206\u7C7B\u5217\u8868\uFF08GET /admin/product-categories\uFF09\u3002\u652F\u6301 q/handle/parent_category_id/is_internal/is_active \u8FC7\u6EE4\u3002\u5206\u7C7B\u5168\u7AD9\u5171\u7528\uFF0C\u4E0D\u6309\u56FD\u5BB6\u7AD9\u70B9\u533A\u5206\u3002",
23390
+ schema: {
23391
+ q: external_exports.string().optional().describe("\u5173\u952E\u8BCD\uFF08\u5339\u914D name/handle\uFF09"),
23392
+ handle: external_exports.string().optional(),
23393
+ parent_category_id: external_exports.string().optional().describe("\u53EA\u53D6\u67D0\u7236\u5206\u7C7B\u7684\u76F4\u63A5\u5B50\u7EA7"),
23394
+ is_internal: external_exports.boolean().optional().describe("\u662F\u5426\u4EC5\u5185\u90E8\u53EF\u89C1"),
23395
+ is_active: external_exports.boolean().optional(),
23396
+ limit: external_exports.number().int().positive().max(100).default(50),
23397
+ offset: external_exports.number().int().nonnegative().default(0)
23398
+ },
23399
+ async run(input, { client: client2 }) {
23400
+ return client2.listProductCategories({
23401
+ q: input.q,
23402
+ handle: input.handle,
23403
+ parent_category_id: input.parent_category_id,
23404
+ is_internal: input.is_internal,
23405
+ is_active: input.is_active,
23406
+ limit: input.limit,
23407
+ offset: input.offset
23408
+ });
23409
+ }
23410
+ },
23411
+ {
23412
+ name: "get_product_category",
23413
+ description: "\u6309\u5206\u7C7B id\u3001handle \u6216\u540D\u79F0\u83B7\u53D6\u5206\u7C7B\u8BE6\u60C5\uFF08GET /admin/product-categories/:id\uFF09\u3002\u4F20 handle/name \u4F1A\u5148\u89E3\u6790\u4E3A id\u3002",
23414
+ schema: { id_or_handle_or_name: external_exports.string() },
23415
+ async run(input, { client: client2 }) {
23416
+ const id = await client2.resolveProductCategoryId(input.id_or_handle_or_name);
23417
+ if (!id) return `\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230\u5206\u7C7B "${input.id_or_handle_or_name}"\uFF08\u7528 list_product_categories \u67E5\u770B\u53EF\u7528\u5206\u7C7B\uFF09`;
23418
+ return client2.getProductCategory(id);
23419
+ }
23420
+ },
23421
+ {
23422
+ name: "create_product_category",
23423
+ description: `\u65B0\u5EFA\u4E00\u4E2A\u4EA7\u54C1\u5206\u7C7B\u3002
23424
+ handle \u4EC5\u542B\u5C0F\u5199\u5B57\u6BCD/\u6570\u5B57/\u8FDE\u5B57\u7B26\uFF0C\u5DE5\u5177\u81EA\u52A8\u5F52\u4E00\u5316\uFF1B\u4E0D\u586B\u5219\u7531 name \u751F\u6210\u3002
23425
+ parent_category_id \u53EF\u4F20\u7236\u5206\u7C7B id \u6216\u5176\u540D\u79F0/handle\uFF08\u81EA\u52A8\u89E3\u6790\uFF09\u3002is_internal \u9ED8\u8BA4 false\uFF0Cis_active \u9ED8\u8BA4 true\u3002
23426
+ \u591A\u8BED\u8A00\uFF1Atranslations \u53EF\u4F20 { "zh-CN": {"name":"...","description":"..."}, ... }\uFF08\u77ED\u7801/\u533A\u57DF\u7801\u5747\u53EF\uFF0C\u7EDF\u4E00\u5F52\u4E00\u5316\u4E3A BCP-47 \u843D\u5E93\uFF09\uFF0C\u8D70\u72EC\u7ACB\u7684\u7FFB\u8BD1\u7AEF\u70B9\uFF0C\u5931\u8D25\u4E0D\u963B\u65AD\u5206\u7C7B\u521B\u5EFA\uFF08\u4F1A\u8FD4\u56DE warning\uFF09\u3002
23427
+ \u9ED8\u8BA4 dry_run\uFF08confirm=false\uFF09\u4EC5\u9884\u89C8\uFF0Cconfirm=true \u624D\u771F\u6B63\u521B\u5EFA\u3002`,
23428
+ schema: {
23429
+ name: external_exports.string().describe("\u5206\u7C7B\u540D\u79F0\uFF08\u5FC5\u586B\uFF09"),
23430
+ handle: external_exports.string().optional().describe("\u4E0D\u586B\u5219\u7531 name \u5F52\u4E00\u5316\u751F\u6210"),
23431
+ description: external_exports.string().optional(),
23432
+ parent_category_id: external_exports.string().optional().describe("\u7236\u5206\u7C7B id / \u540D\u79F0 / handle"),
23433
+ is_internal: external_exports.boolean().default(false).describe("\u662F\u5426\u4EC5\u5185\u90E8\u53EF\u89C1\uFF0C\u9ED8\u8BA4 false"),
23434
+ is_active: external_exports.boolean().default(true).describe("\u662F\u5426\u542F\u7528\uFF0C\u9ED8\u8BA4 true"),
23435
+ external_id: external_exports.string().optional(),
23436
+ metadata: external_exports.record(external_exports.string(), external_exports.any()).optional().describe("\u4EFB\u610F\u952E\u503C\u5143\u6570\u636E"),
23437
+ rank: external_exports.number().int().optional().describe("\u540C\u7EA7\u6392\u5E8F\u503C"),
23438
+ translations: external_exports.record(external_exports.string(), categoryTranslationShape).optional(),
23439
+ confirm: external_exports.boolean().default(false)
23440
+ },
23441
+ async run(input, { client: client2 }) {
23442
+ const handle = normalizeHandle(input.handle || input.name);
23443
+ if (!HANDLE_RE.test(handle)) {
23444
+ return `\u9519\u8BEF\uFF1A\u5F52\u4E00\u5316\u540E\u7684 handle "${handle}" \u975E\u6CD5\uFF08\u53EA\u80FD\u5C0F\u5199\u5B57\u6BCD/\u6570\u5B57/\u8FDE\u5B57\u7B26\uFF09\u3002\u8BF7\u68C0\u67E5\u8F93\u5165\u3002`;
23445
+ }
23446
+ let parentId = input.parent_category_id;
23447
+ if (parentId && !parentId.startsWith("pcat_")) {
23448
+ const resolved = await client2.resolveProductCategoryId(parentId);
23449
+ if (!resolved) return `\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230\u7236\u5206\u7C7B "${parentId}"\uFF08\u7528 list_product_categories \u67E5\u770B\uFF09`;
23450
+ parentId = resolved;
23451
+ }
23452
+ let collision = null;
23453
+ try {
23454
+ const existing = await client2.listProductCategories({ handle, limit: 5 });
23455
+ const dup = (existing?.product_categories || []).find((c) => c.handle === handle);
23456
+ if (dup) collision = { id: dup.id, name: dup.name };
23457
+ } catch {
23458
+ }
23459
+ const warnings = [];
23460
+ if (collision) {
23461
+ warnings.push(`handle "${handle}" \u5DF2\u88AB\u5206\u7C7B\u300C${collision.name}\u300D(${collision.id}) \u5360\u7528`);
23462
+ if (input.confirm) {
23463
+ return `\u9519\u8BEF\uFF1Ahandle "${handle}" \u5DF2\u88AB\u5206\u7C7B ${collision.id}\uFF08\u300C${collision.name}\u300D\uFF09\u5360\u7528\uFF0C\u65E0\u6CD5\u91CD\u590D\u521B\u5EFA\u3002\u82E5\u662F\u8981\u4FEE\u6539\u8BE5\u5206\u7C7B\u8BF7\u7528 update_product_category\u3002`;
23464
+ }
23465
+ }
23466
+ const entries = toCategoryTranslations(input.translations);
23467
+ const payload = {
23468
+ name: input.name,
23469
+ handle,
23470
+ is_internal: input.is_internal,
23471
+ is_active: input.is_active
23472
+ };
23473
+ if (input.description) payload.description = input.description;
23474
+ if (parentId) payload.parent_category_id = parentId;
23475
+ if (input.external_id) payload.external_id = input.external_id;
23476
+ if (input.metadata) payload.metadata = input.metadata;
23477
+ if (input.rank != null) payload.rank = input.rank;
23478
+ if (!input.confirm) {
23479
+ return {
23480
+ dry_run: true,
23481
+ will_create: payload,
23482
+ translation_locales: entries.map((e) => e.locale_code),
23483
+ warnings,
23484
+ handle_collision: collision,
23485
+ note: "\u672A confirm\uFF0C\u4EC5\u9884\u89C8\u3002\u786E\u8BA4\u8BF7\u8BBE confirm=true\u3002"
23486
+ };
23487
+ }
23488
+ const data = await client2.createProductCategory(payload);
23489
+ const categoryId = data?.product_category?.id || data?.id;
23490
+ let translationResult = null;
23491
+ if (entries.length && categoryId) {
23492
+ try {
23493
+ translationResult = await upsertTranslations(client2, "product_category", categoryId, entries);
23494
+ } catch (e) {
23495
+ warnings.push(`\u7FFB\u8BD1\u5199\u5165\u5931\u8D25\uFF08\u5206\u7C7B\u5DF2\u521B\u5EFA\uFF0C\u53EF\u8865\u8C03 set_translations reference=product_category\uFF09\u2014\u2014 ${e?.message || e}`);
23496
+ }
23497
+ }
23498
+ return { created: data, translations: translationResult, warnings };
23499
+ }
23500
+ },
23501
+ {
23502
+ name: "update_product_category",
23503
+ description: `\u4FEE\u6539\u4EA7\u54C1\u5206\u7C7B\u5B57\u6BB5\uFF08\u540D\u79F0/handle/\u63CF\u8FF0/\u7236\u7EA7/\u542F\u7528\u72B6\u6001/\u5185\u90E8\u53EF\u89C1/metadata/\u6392\u5E8F/\u591A\u8BED\u8A00\uFF09\u3002
23504
+ id \u53EF\u4F20\u5206\u7C7B id\u3001handle \u6216\u540D\u79F0\u3002handle \u81EA\u52A8\u5F52\u4E00\u5316\uFF1Bmetadata \u4E3A\u5408\u5E76\u8BED\u4E49\uFF08\u65B0\u952E\u8986\u76D6\u540C\u540D\u952E\uFF0C\u672A\u63D0\u53CA\u7684\u65E7\u952E\u4FDD\u7559\uFF09\u3002
23505
+ parent_category_id \u4F20\u7A7A\u5B57\u7B26\u4E32\u53EF\u89E3\u7ED1\u7236\u7EA7\u3002translations \u4E3A upsert\uFF08\u540C\u8BED\u8A00\u5408\u5E76\u66F4\u65B0\uFF0C\u4E0D\u4EA7\u751F\u91CD\u590D\u884C\uFF09\u3002\u9ED8\u8BA4 dry_run\u3002`,
23506
+ schema: {
23507
+ id: external_exports.string().describe("\u5206\u7C7B id / handle / \u540D\u79F0"),
23508
+ name: external_exports.string().optional(),
23509
+ handle: external_exports.string().optional(),
23510
+ description: external_exports.string().optional(),
23511
+ parent_category_id: external_exports.string().optional().describe("\u7236\u5206\u7C7B id / \u540D\u79F0 / handle\uFF1B\u4F20\u7A7A\u5B57\u7B26\u4E32\u89E3\u7ED1\u7236\u7EA7"),
23512
+ is_internal: external_exports.boolean().optional(),
23513
+ is_active: external_exports.boolean().optional(),
23514
+ external_id: external_exports.string().optional(),
23515
+ metadata: external_exports.record(external_exports.string(), external_exports.any()).optional().describe("\u5408\u5E76\u8FDB\u73B0\u6709 metadata\uFF08\u4E0D\u6574\u4F53\u8986\u76D6\uFF09"),
23516
+ rank: external_exports.number().int().optional(),
23517
+ translations: external_exports.record(external_exports.string(), categoryTranslationShape).optional(),
23518
+ confirm: external_exports.boolean().default(false)
23519
+ },
23520
+ async run(input, { client: client2 }) {
23521
+ const categoryId = await client2.resolveProductCategoryId(input.id);
23522
+ if (!categoryId) return `\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230\u5206\u7C7B "${input.id}"\uFF08\u7528 list_product_categories \u67E5\u770B\uFF09`;
23523
+ const patch = {};
23524
+ if (input.name) patch.name = input.name;
23525
+ if (input.handle) {
23526
+ const h = normalizeHandle(input.handle);
23527
+ if (!HANDLE_RE.test(h)) return `\u9519\u8BEF\uFF1A\u5F52\u4E00\u5316 handle "${h}" \u975E\u6CD5\u3002`;
23528
+ patch.handle = h;
23529
+ }
23530
+ if (input.description) patch.description = input.description;
23531
+ if (input.parent_category_id !== void 0) {
23532
+ if (input.parent_category_id === "") {
23533
+ patch.parent_category_id = null;
23534
+ } else if (!input.parent_category_id.startsWith("pcat_")) {
23535
+ const resolved = await client2.resolveProductCategoryId(input.parent_category_id);
23536
+ if (!resolved) return `\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230\u7236\u5206\u7C7B "${input.parent_category_id}"`;
23537
+ patch.parent_category_id = resolved;
23538
+ } else {
23539
+ patch.parent_category_id = input.parent_category_id;
23540
+ }
23541
+ }
23542
+ if (input.is_internal !== void 0) patch.is_internal = input.is_internal;
23543
+ if (input.is_active !== void 0) patch.is_active = input.is_active;
23544
+ if (input.external_id) patch.external_id = input.external_id;
23545
+ if (input.rank != null) patch.rank = input.rank;
23546
+ if (input.metadata && Object.keys(input.metadata).length) {
23547
+ const cur = await client2.getProductCategory(categoryId).catch(() => null);
23548
+ const existingMeta = (cur?.product_category ?? cur)?.metadata || {};
23549
+ patch.metadata = { ...existingMeta, ...input.metadata };
23550
+ }
23551
+ const entries = toCategoryTranslations(input.translations);
23552
+ if (!input.confirm) {
23553
+ return { dry_run: true, will_update: { id: categoryId, ...patch }, translation_locales: entries.map((e) => e.locale_code) };
23554
+ }
23555
+ const data = await client2.updateProductCategory(categoryId, patch);
23556
+ let translationResult = null;
23557
+ if (entries.length) {
23558
+ try {
23559
+ translationResult = await upsertTranslations(client2, "product_category", categoryId, entries);
23560
+ } catch (e) {
23561
+ return { updated: data, warning_translations: `\u7FFB\u8BD1\u5199\u5165\u5931\u8D25 \u2014\u2014 ${e?.message || e}` };
23562
+ }
23563
+ }
23564
+ return { updated: data, translations: translationResult };
23565
+ }
23566
+ },
23567
+ {
23568
+ name: "delete_product_category",
23569
+ description: "\u5220\u9664\u4E00\u4E2A\u4EA7\u54C1\u5206\u7C7B\uFF08DELETE /admin/product-categories/:id\uFF09\u3002id \u53EF\u4F20\u5206\u7C7B id\u3001handle \u6216\u540D\u79F0\u3002\u26A0\uFE0F \u6709\u5B50\u5206\u7C7B\u6216\u5DF2\u6302\u5546\u54C1\u7684\u5206\u7C7B\u5220\u9664\u53EF\u80FD\u5931\u8D25\uFF0C\u9700\u5148\u8C03\u6574\u3002\u9ED8\u8BA4 dry_run\u3002",
23570
+ schema: {
23571
+ id: external_exports.string().describe("\u5206\u7C7B id / handle / \u540D\u79F0"),
23572
+ confirm: external_exports.boolean().default(false)
23573
+ },
23574
+ async run(input, { client: client2 }) {
23575
+ const categoryId = await client2.resolveProductCategoryId(input.id);
23576
+ if (!categoryId) return `\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230\u5206\u7C7B "${input.id}"\uFF08\u7528 list_product_categories \u67E5\u770B\uFF09`;
23577
+ if (!input.confirm) {
23578
+ return { dry_run: true, will_delete: { id: categoryId, input: input.id }, note: "\u672A confirm\uFF0C\u4EC5\u9884\u89C8\u3002\u786E\u8BA4\u8BF7\u8BBE confirm=true\u3002" };
23579
+ }
23580
+ return client2.deleteProductCategory(categoryId);
23581
+ }
23582
+ }
23583
+ ];
23584
+
23585
+ // src/tools/collections.ts
23586
+ var collectionTranslationShape = external_exports.object({
23587
+ title: external_exports.string().optional()
23588
+ });
23589
+ function toCollectionTranslations(raw) {
23590
+ return Object.entries(raw ?? {}).map(([locale, t]) => ({
23591
+ locale_code: canonLocaleKey(locale),
23592
+ translations: Object.fromEntries(
23593
+ Object.entries(t ?? {}).filter(([, v]) => v !== void 0 && v !== null)
23594
+ )
23595
+ }));
23596
+ }
23597
+ var collectionTools = [
23598
+ {
23599
+ name: "get_collection",
23600
+ description: "\u6309\u7CFB\u5217 id\u3001handle \u6216\u6807\u9898\u83B7\u53D6\u7CFB\u5217\u8BE6\u60C5\uFF08GET /admin/collections/:id\uFF09\u3002\u4F20 handle/title \u4F1A\u5148\u89E3\u6790\u4E3A id\u3002",
23601
+ schema: { id_or_handle_or_title: external_exports.string() },
23602
+ async run(input, { client: client2 }) {
23603
+ const id = await client2.resolveCollectionId(input.id_or_handle_or_title);
23604
+ if (!id) return `\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230\u7CFB\u5217 "${input.id_or_handle_or_title}"\uFF08\u7528 list_collections \u67E5\u770B\u53EF\u7528\u7CFB\u5217\uFF09`;
23605
+ return client2.getCollection(id);
23606
+ }
23607
+ },
23608
+ {
23609
+ name: "create_collection",
23610
+ description: `\u65B0\u5EFA\u4E00\u4E2A\u4EA7\u54C1\u7CFB\u5217 / \u96C6\u5408\uFF08\u5982\u6D3B\u52A8\u96C6\u5408\u3001\u9996\u9875\u7CBE\u9009\u96C6\u5408 featured\uFF09\u3002
23611
+ handle \u4EC5\u542B\u5C0F\u5199\u5B57\u6BCD/\u6570\u5B57/\u8FDE\u5B57\u7B26\uFF0C\u5DE5\u5177\u81EA\u52A8\u5F52\u4E00\u5316\uFF1B\u4E0D\u586B\u5219\u7531 title \u751F\u6210\u3002
23612
+ \u26A0\uFE0F \u5B98\u65B9 collection validator \u6CA1\u6709 description \u5B57\u6BB5\uFF0C\u5982\u9700\u63CF\u8FF0\u8BF7\u653E metadata\uFF08\u5982 {"description":"..."}\uFF09\u3002
23613
+ \u591A\u8BED\u8A00\uFF1Atranslations \u53EF\u4F20 { "zh-CN": {"title":"..."}, ... }\uFF08\u77ED\u7801/\u533A\u57DF\u7801\u5747\u53EF\uFF0C\u7EDF\u4E00\u5F52\u4E00\u5316\u4E3A BCP-47 \u843D\u5E93\uFF09\uFF0C\u8D70\u72EC\u7ACB\u7FFB\u8BD1\u7AEF\u70B9\uFF0C\u5931\u8D25\u4E0D\u963B\u65AD\u521B\u5EFA\u3002
23614
+ \u9ED8\u8BA4 dry_run\uFF08confirm=false\uFF09\u4EC5\u9884\u89C8\uFF0Cconfirm=true \u624D\u771F\u6B63\u521B\u5EFA\u3002`,
23615
+ schema: {
23616
+ title: external_exports.string().describe("\u7CFB\u5217\u6807\u9898\uFF08\u5FC5\u586B\uFF09"),
23617
+ handle: external_exports.string().optional().describe("\u4E0D\u586B\u5219\u7531 title \u5F52\u4E00\u5316\u751F\u6210"),
23618
+ external_id: external_exports.string().optional(),
23619
+ metadata: external_exports.record(external_exports.string(), external_exports.any()).optional().describe('\u4EFB\u610F\u952E\u503C\u5143\u6570\u636E\uFF0C\u5982 {"is_navigable":true,"description":"..."}'),
23620
+ translations: external_exports.record(external_exports.string(), collectionTranslationShape).optional(),
23621
+ confirm: external_exports.boolean().default(false)
23622
+ },
23623
+ async run(input, { client: client2 }) {
23624
+ const handle = normalizeHandle(input.handle || input.title);
23625
+ if (!HANDLE_RE.test(handle)) {
23626
+ return `\u9519\u8BEF\uFF1A\u5F52\u4E00\u5316\u540E\u7684 handle "${handle}" \u975E\u6CD5\uFF08\u53EA\u80FD\u5C0F\u5199\u5B57\u6BCD/\u6570\u5B57/\u8FDE\u5B57\u7B26\uFF09\u3002\u8BF7\u68C0\u67E5\u8F93\u5165\u3002`;
23627
+ }
23628
+ let collision = null;
23629
+ try {
23630
+ const existing = await client2.listCollections({ handle, limit: 5 });
23631
+ const dup = (existing?.collections || []).find((c) => c.handle === handle);
23632
+ if (dup) collision = { id: dup.id, title: dup.title };
23633
+ } catch {
23634
+ }
23635
+ const warnings = [];
23636
+ if (collision) {
23637
+ warnings.push(`handle "${handle}" \u5DF2\u88AB\u7CFB\u5217\u300C${collision.title}\u300D(${collision.id}) \u5360\u7528`);
23638
+ if (input.confirm) {
23639
+ return `\u9519\u8BEF\uFF1Ahandle "${handle}" \u5DF2\u88AB\u7CFB\u5217 ${collision.id}\uFF08\u300C${collision.title}\u300D\uFF09\u5360\u7528\uFF0C\u65E0\u6CD5\u91CD\u590D\u521B\u5EFA\u3002\u82E5\u662F\u8981\u4FEE\u6539\u8BE5\u7CFB\u5217\u8BF7\u7528 update_collection\u3002`;
23640
+ }
23641
+ }
23642
+ const entries = toCollectionTranslations(input.translations);
23643
+ const payload = { title: input.title, handle };
23644
+ if (input.external_id) payload.external_id = input.external_id;
23645
+ if (input.metadata) payload.metadata = input.metadata;
23646
+ if (!input.confirm) {
23647
+ return {
23648
+ dry_run: true,
23649
+ will_create: payload,
23650
+ translation_locales: entries.map((e) => e.locale_code),
23651
+ warnings,
23652
+ handle_collision: collision,
23653
+ note: "\u672A confirm\uFF0C\u4EC5\u9884\u89C8\u3002\u786E\u8BA4\u8BF7\u8BBE confirm=true\u3002"
23654
+ };
23655
+ }
23656
+ const data = await client2.createCollection(payload);
23657
+ const collectionId = data?.collection?.id || data?.id;
23658
+ let translationResult = null;
23659
+ if (entries.length && collectionId) {
23660
+ try {
23661
+ translationResult = await upsertTranslations(client2, "product_collection", collectionId, entries);
23662
+ } catch (e) {
23663
+ warnings.push(`\u7FFB\u8BD1\u5199\u5165\u5931\u8D25\uFF08\u7CFB\u5217\u5DF2\u521B\u5EFA\uFF0C\u53EF\u8865\u8C03 set_translations reference=product_collection\uFF09\u2014\u2014 ${e?.message || e}`);
23664
+ }
23665
+ }
23666
+ return { created: data, translations: translationResult, warnings };
23667
+ }
23668
+ },
23669
+ {
23670
+ name: "update_collection",
23671
+ description: `\u4FEE\u6539\u4EA7\u54C1\u7CFB\u5217\u5B57\u6BB5\uFF08\u6807\u9898/handle/external_id/metadata/\u591A\u8BED\u8A00\uFF09\u3002id \u53EF\u4F20\u7CFB\u5217 id\u3001handle \u6216\u6807\u9898\u3002
23672
+ handle \u81EA\u52A8\u5F52\u4E00\u5316\uFF1Bmetadata \u4E3A\u5408\u5E76\u8BED\u4E49\uFF08\u65B0\u952E\u8986\u76D6\u540C\u540D\u952E\uFF0C\u672A\u63D0\u53CA\u7684\u65E7\u952E\u4FDD\u7559\uFF09\u2014\u2014\u672C\u9879\u76EE\u540E\u53F0\u300C\u5BFC\u822A\u663E\u793A\u300D\u5F00\u5173\u5C31\u5B58\u5728 metadata.is_navigable\u3002
23673
+ translations \u4E3A upsert\uFF08\u540C\u8BED\u8A00\u5408\u5E76\u66F4\u65B0\uFF0C\u4E0D\u4EA7\u751F\u91CD\u590D\u884C\uFF09\u3002\u9ED8\u8BA4 dry_run\u3002`,
23674
+ schema: {
23675
+ id: external_exports.string().describe("\u7CFB\u5217 id / handle / \u6807\u9898"),
23676
+ title: external_exports.string().optional(),
23677
+ handle: external_exports.string().optional(),
23678
+ external_id: external_exports.string().optional(),
23679
+ metadata: external_exports.record(external_exports.string(), external_exports.any()).optional().describe("\u5408\u5E76\u8FDB\u73B0\u6709 metadata\uFF08\u4E0D\u6574\u4F53\u8986\u76D6\uFF09"),
23680
+ translations: external_exports.record(external_exports.string(), collectionTranslationShape).optional(),
23681
+ confirm: external_exports.boolean().default(false)
23682
+ },
23683
+ async run(input, { client: client2 }) {
23684
+ const collectionId = await client2.resolveCollectionId(input.id);
23685
+ if (!collectionId) return `\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230\u7CFB\u5217 "${input.id}"\uFF08\u7528 list_collections \u67E5\u770B\uFF09`;
23686
+ const patch = {};
23687
+ if (input.title) patch.title = input.title;
23688
+ if (input.handle) {
23689
+ const h = normalizeHandle(input.handle);
23690
+ if (!HANDLE_RE.test(h)) return `\u9519\u8BEF\uFF1A\u5F52\u4E00\u5316 handle "${h}" \u975E\u6CD5\u3002`;
23691
+ patch.handle = h;
23692
+ }
23693
+ if (input.external_id) patch.external_id = input.external_id;
23694
+ if (input.metadata && Object.keys(input.metadata).length) {
23695
+ const cur = await client2.getCollection(collectionId).catch(() => null);
23696
+ const existingMeta = (cur?.collection ?? cur)?.metadata || {};
23697
+ patch.metadata = { ...existingMeta, ...input.metadata };
23698
+ }
23699
+ const entries = toCollectionTranslations(input.translations);
23700
+ if (!input.confirm) {
23701
+ return { dry_run: true, will_update: { id: collectionId, ...patch }, translation_locales: entries.map((e) => e.locale_code) };
23702
+ }
23703
+ const data = await client2.updateCollection(collectionId, patch);
23704
+ let translationResult = null;
23705
+ if (entries.length) {
23706
+ try {
23707
+ translationResult = await upsertTranslations(client2, "product_collection", collectionId, entries);
23708
+ } catch (e) {
23709
+ return { updated: data, warning_translations: `\u7FFB\u8BD1\u5199\u5165\u5931\u8D25 \u2014\u2014 ${e?.message || e}` };
23710
+ }
23711
+ }
23712
+ return { updated: data, translations: translationResult };
23713
+ }
23714
+ },
23715
+ {
23716
+ name: "delete_collection",
23717
+ description: "\u5220\u9664\u4E00\u4E2A\u4EA7\u54C1\u7CFB\u5217 / \u96C6\u5408\uFF08DELETE /admin/collections/:id\uFF09\u3002id \u53EF\u4F20\u7CFB\u5217 id\u3001handle \u6216\u6807\u9898\u3002\u26A0\uFE0F \u5DF2\u6302\u5546\u54C1\u7684\u7CFB\u5217\u5220\u9664\u884C\u4E3A\u53D6\u51B3\u4E8E\u540E\u7AEF\u5DE5\u4F5C\u6D41\uFF0C\u9700\u5148\u786E\u8BA4\u3002\u9ED8\u8BA4 dry_run\u3002",
23718
+ schema: {
23719
+ id: external_exports.string().describe("\u7CFB\u5217 id / handle / \u6807\u9898"),
23720
+ confirm: external_exports.boolean().default(false)
23721
+ },
23722
+ async run(input, { client: client2 }) {
23723
+ const collectionId = await client2.resolveCollectionId(input.id);
23724
+ if (!collectionId) return `\u9519\u8BEF\uFF1A\u627E\u4E0D\u5230\u7CFB\u5217 "${input.id}"\uFF08\u7528 list_collections \u67E5\u770B\uFF09`;
23725
+ if (!input.confirm) {
23726
+ return { dry_run: true, will_delete: { id: collectionId, input: input.id }, note: "\u672A confirm\uFF0C\u4EC5\u9884\u89C8\u3002\u786E\u8BA4\u8BF7\u8BBE confirm=true\u3002" };
23727
+ }
23728
+ return client2.deleteCollection(collectionId);
23729
+ }
23730
+ }
23731
+ ];
23732
+
23230
23733
  // src/tools/ops.ts
23231
23734
  var opsTools = [
23232
23735
  {
@@ -23438,6 +23941,20 @@ var labelsShape = external_exports.object({
23438
23941
  sku: external_exports.string(),
23439
23942
  series: external_exports.string()
23440
23943
  });
23944
+ var optionShape = external_exports.object({
23945
+ title: external_exports.string().describe('\u9009\u9879\u6807\u9898\uFF0C\u5982 "Fiber Type" / "Handle Type"'),
23946
+ values: external_exports.array(external_exports.string().min(1)).min(1).describe("\u8BE5\u9009\u9879\u4E0B\u7684\u5168\u90E8\u53D6\u503C\uFF08\u53BB\u91CD\u540E\u5199\u5165\uFF09")
23947
+ });
23948
+ var variantSpecShape = external_exports.object({
23949
+ sku: external_exports.string().optional().describe("\u53D8\u4F53 SKU\uFF08\u5E93\u5B58/\u5C65\u7EA6\u5173\u952E\u6807\u8BC6\uFF0C\u5EFA\u8BAE\u5FC5\u586B\uFF09"),
23950
+ title: external_exports.string().optional().describe('\u53D8\u4F53\u6807\u9898\uFF0C\u7701\u7565\u65F6\u7531 options \u53D6\u503C\u62FC\u63A5\uFF08\u5982 "ALC / Penhold"\uFF09'),
23951
+ options: external_exports.record(external_exports.string(), external_exports.string()).describe('\u9009\u9879\u6807\u9898\u2192\u53D6\u503C\uFF0C\u5982 {"Fiber Type":"ALC","Handle Type":"Penhold"}'),
23952
+ price: external_exports.number().nonnegative().optional(),
23953
+ currency_code: external_exports.string().optional(),
23954
+ prices: external_exports.array(priceShape).optional(),
23955
+ manage_inventory: external_exports.boolean().optional(),
23956
+ initial_stock: stockShape.optional()
23957
+ });
23441
23958
  var productSpecShape = external_exports.object({
23442
23959
  handle: external_exports.string(),
23443
23960
  title: external_exports.string(),
@@ -23463,7 +23980,15 @@ var productSpecShape = external_exports.object({
23463
23980
  material: external_exports.string().optional(),
23464
23981
  manage_inventory: external_exports.boolean().optional(),
23465
23982
  initial_stock: stockShape.optional(),
23466
- content: external_exports.record(external_exports.string(), external_exports.array(blockShape)).optional()
23983
+ content: external_exports.record(external_exports.string(), external_exports.array(blockShape)).optional(),
23984
+ /**
23985
+ * 商品选项(多变体时必填/可推导)。与 variants 配合:每款商品可声明若干选项,
23986
+ * 每个变体用 options 映射指定其在各选项下的取值。省略时由 variants 自动推导。
23987
+ * ⚠️ 仅声明 options 而无 variants 不支持(单 SKU 商品无需选项)。
23988
+ */
23989
+ options: external_exports.array(optionShape).optional(),
23990
+ /** 多变体:每项为一个变体(含 options 映射 + 自身价格/SKU/库存)。与 options 配合。 */
23991
+ variants: external_exports.array(variantSpecShape).optional()
23467
23992
  });
23468
23993
  var optionsShape = external_exports.object({
23469
23994
  on_duplicate: external_exports.enum(["error", "skip", "update", "archive"]).default("update"),
@@ -23574,6 +24099,40 @@ function buildPrices(p) {
23574
24099
  if (p.price != null) return [{ amount: p.price, currency_code: p.currency_code || "MYR" }];
23575
24100
  return [];
23576
24101
  }
24102
+ function deriveOptions(variants) {
24103
+ const titleToValues = /* @__PURE__ */ new Map();
24104
+ for (const v of variants) {
24105
+ for (const [title, value] of Object.entries(v.options || {})) {
24106
+ const arr = titleToValues.get(title) || [];
24107
+ if (!arr.includes(value)) arr.push(value);
24108
+ titleToValues.set(title, arr);
24109
+ }
24110
+ }
24111
+ return [...titleToValues.entries()].map(([title, values]) => ({ title, values }));
24112
+ }
24113
+ function optionSignature(v) {
24114
+ const entries = Object.entries(v.options || {}).sort((a, b) => a[0].localeCompare(b[0]));
24115
+ return entries.map(([k, val]) => `${k}=${val}`).join("|");
24116
+ }
24117
+ function optionSignatureFromApi(variant, optionTitleById) {
24118
+ const rec = {};
24119
+ for (const o of variant.options || []) {
24120
+ const title = o?.option_id ? optionTitleById.get(String(o.option_id)) : void 0;
24121
+ if (title && o?.value != null) rec[title] = String(o.value);
24122
+ }
24123
+ return optionSignature(rec);
24124
+ }
24125
+ function collectMissingOptionValues(currentOptions, specOptions) {
24126
+ const out = [];
24127
+ for (const so of specOptions) {
24128
+ const cur = (currentOptions || []).find((o) => String(o?.title) === so.title);
24129
+ if (!cur?.id) continue;
24130
+ const existing = new Set((cur.values || []).map((v) => String(v?.value)));
24131
+ const missing = [...new Set(so.values)].filter((v) => !existing.has(v));
24132
+ if (missing.length) out.push({ title: so.title, product_option_id: String(cur.id), values: missing });
24133
+ }
24134
+ return out;
24135
+ }
23577
24136
  function buildAutoContent(p, opts, imageUrl) {
23578
24137
  const labelsFor = (locale) => {
23579
24138
  const short = SHORT_OF[locale] || locale.split("-")[0];
@@ -23635,9 +24194,10 @@ async function buildPlan(ctx2, spec) {
23635
24194
  for (const p of spec.products) {
23636
24195
  const item = {
23637
24196
  handle: p.handle,
23638
- sku: p.sku,
24197
+ sku: p.sku || p.variants?.[0]?.sku,
23639
24198
  title: p.title,
23640
24199
  action: "create",
24200
+ variant_count: p.variants?.length || void 0,
23641
24201
  warnings: []
23642
24202
  };
23643
24203
  const block = (reason) => {
@@ -23647,6 +24207,23 @@ async function buildPlan(ctx2, spec) {
23647
24207
  if (!HANDLE_RE2.test(p.handle)) {
23648
24208
  block(`handle "${p.handle}" \u5F52\u4E00\u5316\u540E\u975E\u6CD5\uFF0C\u8DF3\u8FC7\u8BE5\u6B3E`);
23649
24209
  }
24210
+ if (p.variants?.length) {
24211
+ const optTitles = new Set((p.options || deriveOptions(p.variants)).map((o) => o.title));
24212
+ for (const v of p.variants) {
24213
+ if (!v.options || !Object.keys(v.options).length) {
24214
+ block(`\u53D8\u4F53 ${v.sku || "(\u65E0SKU)"} \u7F3A\u5C11 options \u6620\u5C04\uFF0C\u8DF3\u8FC7\u8BE5\u6B3E`);
24215
+ break;
24216
+ }
24217
+ const keys = Object.keys(v.options).sort().join(",");
24218
+ const expected = [...optTitles].sort().join(",");
24219
+ if (keys !== expected) {
24220
+ block(`\u53D8\u4F53 ${v.sku || "(\u65E0SKU)"} \u7684 options \u952E [${keys}] \u4E0E\u5546\u54C1\u9009\u9879 [${expected}] \u4E0D\u4E00\u81F4\uFF0C\u8DF3\u8FC7\u8BE5\u6B3E`);
24221
+ break;
24222
+ }
24223
+ }
24224
+ } else if (p.options?.length) {
24225
+ block("\u4EC5\u58F0\u660E options \u4F46\u65E0 variants\uFF1A\u5355 SKU \u5546\u54C1\u65E0\u9700\u9009\u9879\uFF0C\u591A\u53D8\u4F53\u5FC5\u987B\u540C\u65F6\u7ED9 variants");
24226
+ }
23650
24227
  const missing = required2.filter((l) => !p.translations?.[l]?.title);
23651
24228
  if (missing.length) item.warnings.push(`\u7F3A\u8BED\u8A00 title: ${missing.join(", ")}`);
23652
24229
  for (const img of p.images || []) {
@@ -23654,7 +24231,7 @@ async function buildPlan(ctx2, spec) {
23654
24231
  block(`\u56FE\u7247\u4E0D\u5B58\u5728: ${img}\uFF0C\u8DF3\u8FC7\u8BE5\u6B3E`);
23655
24232
  }
23656
24233
  }
23657
- if (!buildPrices(p).length) item.warnings.push("\u672A\u7ED9\u4EF7\u683C");
24234
+ if (!p.variants?.length && !buildPrices(p).length) item.warnings.push("\u672A\u7ED9\u4EF7\u683C");
23658
24235
  const unknownChannels = (p.sales_channels || []).filter((n) => !channelMap.has(n));
23659
24236
  if (unknownChannels.length) {
23660
24237
  block(`\u627E\u4E0D\u5230\u6E20\u9053: ${unknownChannels.join(", ")}\uFF0C\u8DF3\u8FC7\u8BE5\u6B3E`);
@@ -23669,15 +24246,36 @@ async function buildPlan(ctx2, spec) {
23669
24246
  } catch (e) {
23670
24247
  item.warnings.push(`handle \u67E5\u91CD\u5931\u8D25\uFF1A${(e instanceof Error ? e.message : String(e)).slice(0, 100)}`);
23671
24248
  }
23672
- if (!existing && p.sku) {
24249
+ if (!existing && item.sku) {
23673
24250
  try {
23674
- const d = await client2.listProducts({ q: p.sku, limit: 10 });
24251
+ const d = await client2.listProducts({ q: item.sku, limit: 10 });
23675
24252
  existing = (d?.products || []).find(
23676
- (x) => (x.variants || []).some((v) => v.sku === p.sku)
24253
+ (x) => (x.variants || []).some((v) => v.sku === item.sku)
23677
24254
  ) || null;
23678
24255
  } catch {
23679
24256
  }
23680
24257
  }
24258
+ if (existing && p.variants?.length && item.action !== "blocked") {
24259
+ const specOptions = p.options && p.options.length ? p.options : deriveOptions(p.variants);
24260
+ const specTitles = [...new Set(specOptions.map((o) => o.title))].sort();
24261
+ const curTitles = [
24262
+ ...new Set(
24263
+ (existing.options || []).map((o) => String(o?.title || "")).filter(Boolean)
24264
+ )
24265
+ ].sort();
24266
+ if (curTitles.join("|") !== specTitles.join("|")) {
24267
+ block(
24268
+ `\u5DF2\u5B58\u5728\u5546\u54C1 ${existing.id} \u7684\u9009\u9879\u7ED3\u6784 [${curTitles.join(", ") || "\u65E0"}] \u4E0E spec [${specTitles.join(", ")}] \u4E0D\u4E00\u81F4\uFF0C\u4E0D\u652F\u6301\u539F\u5730\u6539\u9020\uFF1B\u8BF7\u5148\u4EBA\u5DE5\u8C03\u6574\u9009\u9879\uFF0C\u6216\u7528 on_duplicate=archive \u4E0B\u67B6\u65E7\u6B3E\u540E\u65B0\u5EFA`
24269
+ );
24270
+ } else if (existing.options) {
24271
+ const missingValues = collectMissingOptionValues(existing.options, specOptions);
24272
+ if (missingValues.length) {
24273
+ item.warnings.push(
24274
+ `\u5C06\u65B0\u589E\u9009\u9879\u53D6\u503C\uFF1A${missingValues.map((m) => `${m.title}=${m.values.join("/")}`).join("; ")}`
24275
+ );
24276
+ }
24277
+ }
24278
+ }
23681
24279
  const strategy = opts?.on_duplicate ?? "update";
23682
24280
  if (existing) {
23683
24281
  item.existing_id = existing.id;
@@ -23692,7 +24290,8 @@ async function buildPlan(ctx2, spec) {
23692
24290
  else if (strategy === "archive") item.action = "archive+create";
23693
24291
  else item.action = "update";
23694
24292
  }
23695
- if ((item.action === "create" || item.action === "archive+create") && (p.manage_inventory ?? true) && !(p.initial_stock ?? opts?.default_initial_stock)) {
24293
+ const anyVariantStock = !!p.variants?.some((v) => v.initial_stock);
24294
+ if ((item.action === "create" || item.action === "archive+create") && (p.manage_inventory ?? true) && !(p.initial_stock ?? opts?.default_initial_stock) && !anyVariantStock) {
23696
24295
  item.warnings.push("\u672A\u7ED9 initial_stock\uFF0C\u521B\u5EFA\u540E 0 \u5E93\u5B58=\u524D\u53F0\u7F3A\u8D27");
23697
24296
  }
23698
24297
  items.push(item);
@@ -23701,11 +24300,12 @@ async function buildPlan(ctx2, spec) {
23701
24300
  }
23702
24301
  async function executeItem(ctx2, p, item, plan, opts) {
23703
24302
  const { client: client2 } = ctx2;
24303
+ const warnings = [...item.warnings];
23704
24304
  const summary = {
23705
24305
  handle: p.handle,
23706
24306
  sku: p.sku || null,
23707
24307
  action: item.action,
23708
- warnings: item.warnings
24308
+ warnings
23709
24309
  };
23710
24310
  if (item.action === "skip" || item.action === "blocked") {
23711
24311
  summary.skipped_reason = item.action === "skip" ? "on_duplicate=skip" : "plan blocked";
@@ -23750,10 +24350,62 @@ async function executeItem(ctx2, p, item, plan, opts) {
23750
24350
  patch.images = Array.from(/* @__PURE__ */ new Set([...existingUrls, ...imageUrls])).map((u) => ({ url: u }));
23751
24351
  }
23752
24352
  await client2.updateProduct(productId, patch);
23753
- if (prices.length) {
24353
+ if (p.variants?.length) {
24354
+ const curVariants = current.variants || [];
24355
+ const optionTitleById = /* @__PURE__ */ new Map();
24356
+ for (const o of current.options || []) {
24357
+ if (o?.id && o?.title) optionTitleById.set(String(o.id), String(o.title));
24358
+ }
24359
+ const specOptions = p.options && p.options.length ? p.options : deriveOptions(p.variants);
24360
+ const missingValues = collectMissingOptionValues(current.options, specOptions);
24361
+ if (missingValues.length) {
24362
+ await client2.addProductOptionValues(
24363
+ productId,
24364
+ missingValues.map((m) => ({
24365
+ product_option_id: m.product_option_id,
24366
+ add: m.values.map((value) => ({ value }))
24367
+ }))
24368
+ );
24369
+ warnings.push(
24370
+ `\u5DF2\u65B0\u589E\u9009\u9879\u53D6\u503C\uFF1A${missingValues.map((m) => `${m.title}=${m.values.join("/")}`).join("; ")}`
24371
+ );
24372
+ }
24373
+ const createdSignatures = /* @__PURE__ */ new Set();
24374
+ for (const v of p.variants) {
24375
+ const vPrices = buildPrices(v).length ? buildPrices(v) : prices;
24376
+ if (!vPrices.length) continue;
24377
+ const sig = optionSignature(v);
24378
+ const match = v.sku ? curVariants.find((x) => x.sku === v.sku) : sig ? curVariants.find((x) => optionSignatureFromApi(x, optionTitleById) === sig) : void 0;
24379
+ if (match) {
24380
+ await client2.updateProductPrices(productId, match.id, vPrices);
24381
+ } else {
24382
+ if (!v.sku) {
24383
+ if (!sig) {
24384
+ warnings.push("\u53D8\u4F53\u65E2\u65E0 SKU \u4E5F\u65E0\u6CD5\u6309\u9009\u9879\u5339\u914D\uFF0C\u8DF3\u8FC7\u8865\u5EFA");
24385
+ continue;
24386
+ }
24387
+ if (createdSignatures.has(sig) || curVariants.some((x) => optionSignatureFromApi(x, optionTitleById) === sig)) {
24388
+ continue;
24389
+ }
24390
+ createdSignatures.add(sig);
24391
+ }
24392
+ await client2.updateProduct(productId, {
24393
+ variants: [
24394
+ {
24395
+ title: v.title || Object.values(v.options).join(" / "),
24396
+ options: v.options,
24397
+ prices: vPrices,
24398
+ manage_inventory: v.manage_inventory ?? p.manage_inventory ?? true,
24399
+ ...v.sku ? { sku: v.sku } : {}
24400
+ }
24401
+ ]
24402
+ });
24403
+ }
24404
+ }
24405
+ } else if (prices.length) {
23754
24406
  const v = (current.variants || [])[0];
23755
24407
  if (v) await client2.updateProductPrices(productId, v.id, prices);
23756
- else summary.warnings = [...item.warnings, "\u5546\u54C1\u6CA1\u6709\u53D8\u4F53\uFF0C\u4EF7\u683C\u672A\u66F4\u65B0"];
24408
+ else warnings.push("\u5546\u54C1\u6CA1\u6709\u53D8\u4F53\uFF0C\u4EF7\u683C\u672A\u66F4\u65B0");
23757
24409
  }
23758
24410
  for (const name of p.sales_channels || []) {
23759
24411
  const cid = plan.channelMap.get(name);
@@ -23764,13 +24416,13 @@ async function executeItem(ctx2, p, item, plan, opts) {
23764
24416
  }
23765
24417
  }
23766
24418
  } else {
24419
+ const isMulti = !!(p.variants && p.variants.length);
23767
24420
  const payload = {
23768
24421
  title: p.title,
23769
24422
  handle: p.handle,
23770
24423
  status: p.status ?? opts?.default_status ?? "draft",
23771
24424
  subtitle: p.subtitle,
23772
24425
  description: p.description,
23773
- options: [{ title: "Default", values: ["Default"] }],
23774
24426
  ...physical
23775
24427
  };
23776
24428
  if (p.metadata) payload.metadata = p.metadata;
@@ -23778,16 +24430,35 @@ async function executeItem(ctx2, p, item, plan, opts) {
23778
24430
  const channelIds = (p.sales_channels || []).map((n) => plan.channelMap.get(n)).filter(Boolean);
23779
24431
  if (channelIds.length) payload.sales_channels = channelIds.map((id) => ({ id }));
23780
24432
  if (collectionId) payload.collection_id = collectionId;
23781
- if (prices.length || p.sku) {
23782
- payload.variants = [
23783
- {
23784
- title: "Default",
23785
- options: { Default: "Default" },
23786
- prices,
23787
- manage_inventory: p.manage_inventory ?? true,
23788
- ...p.sku ? { sku: p.sku } : {}
23789
- }
23790
- ];
24433
+ if (isMulti) {
24434
+ const options = (p.options && p.options.length ? p.options : deriveOptions(p.variants)).map((o) => ({
24435
+ title: o.title,
24436
+ values: [...new Set(o.values)]
24437
+ }));
24438
+ payload.options = options;
24439
+ payload.variants = p.variants.map((v) => {
24440
+ const vPrices = buildPrices(v).length ? buildPrices(v) : prices;
24441
+ return {
24442
+ title: v.title || Object.values(v.options).join(" / "),
24443
+ options: v.options,
24444
+ ...vPrices.length || v.sku ? { prices: vPrices } : {},
24445
+ manage_inventory: v.manage_inventory ?? p.manage_inventory ?? true,
24446
+ ...v.sku ? { sku: v.sku } : {}
24447
+ };
24448
+ });
24449
+ } else {
24450
+ payload.options = [{ title: "Default", values: ["Default"] }];
24451
+ if (prices.length || p.sku) {
24452
+ payload.variants = [
24453
+ {
24454
+ title: "Default",
24455
+ options: { Default: "Default" },
24456
+ prices,
24457
+ manage_inventory: p.manage_inventory ?? true,
24458
+ ...p.sku ? { sku: p.sku } : {}
24459
+ }
24460
+ ];
24461
+ }
23791
24462
  }
23792
24463
  const data = await client2.createProduct(payload);
23793
24464
  productId = data?.product?.id || data?.id;
@@ -23811,7 +24482,22 @@ async function executeItem(ctx2, p, item, plan, opts) {
23811
24482
  summary.translations = `${r.created} created / ${r.updated} updated`;
23812
24483
  }
23813
24484
  const effectiveStock = item.action === "update" ? p.initial_stock : p.initial_stock ?? opts?.default_initial_stock;
23814
- if (effectiveStock) {
24485
+ if (p.variants?.length) {
24486
+ let stocked = 0;
24487
+ for (const v of p.variants) {
24488
+ const vStock = v.initial_stock ?? effectiveStock;
24489
+ if (!vStock || !v.sku) continue;
24490
+ await applyProductStock(ctx2, {
24491
+ productId,
24492
+ sku: v.sku,
24493
+ locationId: vStock.location_id,
24494
+ quantity: vStock.quantity,
24495
+ manageInventory: v.manage_inventory ?? p.manage_inventory ?? true
24496
+ });
24497
+ stocked++;
24498
+ }
24499
+ if (stocked) summary.stock = `${stocked}/${p.variants.length} \u53D8\u4F53\u5DF2\u5EFA\u4ED3`;
24500
+ } else if (effectiveStock) {
23815
24501
  await applyProductStock(ctx2, {
23816
24502
  productId,
23817
24503
  sku: p.sku,
@@ -23845,7 +24531,14 @@ async function executeItem(ctx2, p, item, plan, opts) {
23845
24531
  }
23846
24532
  summary.content_locales = contentLocales;
23847
24533
  summary.images = imageUrls.length;
23848
- summary.prices = prices.map((x) => `${x.currency_code}:${x.amount}`);
24534
+ if (p.variants?.length) {
24535
+ summary.variants = p.variants.map((v) => ({
24536
+ sku: v.sku ?? null,
24537
+ prices: buildPrices(v).map((x) => `${x.currency_code}:${x.amount}`)
24538
+ }));
24539
+ } else {
24540
+ summary.prices = prices.map((x) => `${x.currency_code}:${x.amount}`);
24541
+ }
23849
24542
  return summary;
23850
24543
  }
23851
24544
  async function runBatchImport(ctx2, rawSpec, runOpts = {}) {
@@ -23872,6 +24565,7 @@ async function runBatchImport(ctx2, rawSpec, runOpts = {}) {
23872
24565
  handle: i.handle,
23873
24566
  sku: i.sku || null,
23874
24567
  action: i.action,
24568
+ variants: i.variant_count ?? 1,
23875
24569
  warnings: i.warnings
23876
24570
  })),
23877
24571
  blocked: blockedItems.length,
@@ -23928,6 +24622,8 @@ var batchTools = [
23928
24622
  name: "batch_import_products",
23929
24623
  description: `\u3010\u6279\u91CF\u5F55\u5165\u9996\u9009\u3011\u4E00\u6B21\u5BFC\u5165\u591A\u6B3E\u5B8C\u6574\u5546\u54C1\uFF1A\u67E5\u91CD \u2192 \u56FE\u7247\u4E0A\u4F20 \u2192 \u5546\u54C1\u4E0E\u591A\u5E01\u79CD\u4EF7\u683C \u2192 \u56DB\u8BED\u8A00\u7FFB\u8BD1 \u2192 \u5E93\u5B58 \u2192 \u9500\u552E\u6E20\u9053 \u2192 \u5404\u8BED\u8A00\u8BE6\u60C5\u9875\u5BCC\u5185\u5BB9 \u2192 \u6458\u8981\u56DE\u8BFB\u3002
23930
24624
  spec \u4E3A\u58F0\u660E\u5F0F JSON\uFF08\u5BF9\u8C61\u3001JSON \u5B57\u7B26\u4E32\u6216 spec_path \u6587\u4EF6\u8DEF\u5F84\uFF09\uFF0C\u5B57\u6BB5\u4E0E create_product \u57FA\u672C\u4E00\u81F4\uFF0C\u53E6\u53EF\u5E26 content(locale\u2192blocks) \u6216 options.auto_content=true \u81EA\u52A8\u751F\u6210\u5BCC\u5185\u5BB9\u3002
24625
+ \u26A0\uFE0F \u652F\u6301\u591A\u53D8\u4F53\uFF1A\u6BCF\u6B3E\u53EF\u5E26 options\uFF08\u5546\u54C1\u9009\u9879\uFF0C\u5982 "Fiber Type"/"Handle Type"\uFF09\u4E0E variants\uFF08\u6BCF\u4E2A\u53D8\u4F53\u542B options \u6620\u5C04 + \u5404\u81EA SKU/\u4EF7\u683C/\u5E93\u5B58\uFF09\uFF0C\u53EF\u5EFA\u6A21\u300CALC\xD7CS\u300D\u8FD9\u7C7B\u591A\u89C4\u683C\u7EC4\u5408\uFF1B\u7701\u7565 options/variants \u65F6\u9000\u5316\u4E3A\u5355\u53D8\u4F53\uFF08\u517C\u5BB9\u65E7\u884C\u4E3A\uFF09\u3002variants \u7684 options \u952E\u987B\u4E0E\u5546\u54C1 options \u6807\u9898\u4E00\u81F4\u3002
24626
+ \u5BF9\u5DF2\u6709\u5546\u54C1\u539F\u5730\u8865\u53D8\u4F53\u8981\u6C42\u5176\u9009\u9879\u6807\u9898\u96C6\u5408\u4E0E spec \u5B8C\u5168\u4E00\u81F4\uFF08\u7F3A\u7684\u53D6\u503C\u4F1A\u5148\u8865\uFF09\uFF0C\u5426\u5219\u9884\u68C0\u963B\u65AD\uFF08\u5EFA\u8BAE on_duplicate=archive \u4E0B\u67B6\u540E\u65B0\u5EFA\uFF09\u3002
23931
24627
  options.on_duplicate: update(\u9ED8\u8BA4\uFF0C\u6309 handle/SKU \u5E42\u7B49 upsert) | skip | error | archive(\u65E7\u6B3E\u4E0B\u67B6\u540E\u65B0\u5EFA)\u3002
23932
24628
  \u9ED8\u8BA4 dry_run\uFF1A\u53EA\u56DE\u6BCF\u6B3E\u4E00\u884C\u6458\u8981 + warnings + confirm_token\uFF0C\u4E0D\u5199\u5E93\uFF1B\u786E\u8BA4\u540E\u7528 confirm=true \u5E76\u539F\u6837\u5E26\u56DE confirm_token \u624D\u6267\u884C\u3002
23933
24629
  \u65B0\u5EFA\u5546\u54C1\u9ED8\u8BA4 status=draft\uFF08skill \u786C\u89C4\u5219\uFF1A\u4E0D\u76F4\u63A5\u4E0A\u67B6\uFF09\uFF0C\u662F\u5426\u4E0A\u67B6\u7531 spec \u663E\u5F0F\u58F0\u660E\u3002
@@ -23956,14 +24652,186 @@ options.default_initial_stock \u4E5F\u53EA\u4F5C\u7528\u4E8E\u65B0\u5EFA\uFF0C\u
23956
24652
  }
23957
24653
  ];
23958
24654
 
24655
+ // src/tools/csv-import.ts
24656
+ import { readFileSync as readFileSync5, existsSync as existsSync5 } from "node:fs";
24657
+ var stripBom2 = (s) => s.replace(/^\uFEFF/, "");
24658
+ function parseCsv(text) {
24659
+ const rows = [];
24660
+ let row = [];
24661
+ let field = "";
24662
+ let inQuotes = false;
24663
+ for (let i = 0; i < text.length; i++) {
24664
+ const c = text[i];
24665
+ if (inQuotes) {
24666
+ if (c === '"') {
24667
+ if (text[i + 1] === '"') {
24668
+ field += '"';
24669
+ i++;
24670
+ } else {
24671
+ inQuotes = false;
24672
+ }
24673
+ } else {
24674
+ field += c;
24675
+ }
24676
+ } else {
24677
+ if (c === '"') {
24678
+ inQuotes = true;
24679
+ } else if (c === ",") {
24680
+ row.push(field);
24681
+ field = "";
24682
+ } else if (c === "\n" || c === "\r") {
24683
+ if (c === "\r" && text[i + 1] === "\n") i++;
24684
+ row.push(field);
24685
+ rows.push(row);
24686
+ row = [];
24687
+ field = "";
24688
+ } else {
24689
+ field += c;
24690
+ }
24691
+ }
24692
+ }
24693
+ if (field.length > 0 || row.length > 0) {
24694
+ row.push(field);
24695
+ rows.push(row);
24696
+ }
24697
+ return rows.filter((r) => r.length > 1 || r.length === 1 && r[0].trim() !== "");
24698
+ }
24699
+ function lintCsv(text, filename) {
24700
+ const warnings = [];
24701
+ if (text.charCodeAt(0) === 65279) warnings.push("\u6587\u4EF6\u5E26 UTF-8 BOM\uFF0CMedusa \u89E3\u6790\u53EF\u80FD\u62A5\u9519\uFF0C\u5EFA\u8BAE\u53BB BOM \u540E\u91CD\u5B58");
24702
+ const rows = parseCsv(text);
24703
+ if (rows.length < 2) {
24704
+ warnings.push("CSV \u884C\u6570 < 2\uFF08\u81F3\u5C11\u5E94\u6709\u8868\u5934 + 1 \u884C\u6570\u636E\uFF09");
24705
+ return warnings;
24706
+ }
24707
+ const header = rows[0].map((h) => h.trim());
24708
+ const expected = ["Product Handle", "Variant SKU", "Product Status", "Variant Price MYR", "Variant Price IDR"];
24709
+ const missing = expected.filter((c) => !header.includes(c));
24710
+ if (missing.length) warnings.push(`\u7F3A\u5C11\u5FC5\u586B\u5217\uFF1A${missing.join(", ")}`);
24711
+ const ncol = header.length;
24712
+ const ragged = rows.slice(1).filter((r) => r.length !== ncol).length;
24713
+ if (ragged > 0) warnings.push(`\u6709 ${ragged} \u884C\u6570\u636E\u5217\u6570(${ncol === 0 ? "?" : ""}) \u4E0E\u8868\u5934(${ncol}) \u4E0D\u4E00\u81F4\uFF08\u53EF\u80FD\u591A\u4F59/\u7F3A\u5931\u5217\uFF0CMedusa \u4F1A\u9519\u4F4D\u6216\u62A5\u9519\uFF09`);
24714
+ if (!header.includes("Product Handle")) {
24715
+ } else {
24716
+ const hi = header.indexOf("Product Handle");
24717
+ const ti = header.indexOf("Product Title");
24718
+ const byHandle = /* @__PURE__ */ new Map();
24719
+ for (const r of rows.slice(1)) {
24720
+ const hd = (r[hi] || "").trim();
24721
+ const tt = (r[ti] || "").trim();
24722
+ if (!hd || !tt) continue;
24723
+ const set = byHandle.get(hd) || /* @__PURE__ */ new Set();
24724
+ set.add(tt);
24725
+ byHandle.set(hd, set);
24726
+ }
24727
+ const conflicting = [...byHandle.entries()].filter(([, titles]) => titles.size > 1);
24728
+ if (conflicting.length) {
24729
+ warnings.push(`\u540C\u4E00 Handle \u5BF9\u5E94\u591A\u4E2A Product Title\uFF1A${conflicting.slice(0, 3).map(([h, t]) => `${h}(${[...t].join(" / ")})`).join("; ")}`);
24730
+ }
24731
+ }
24732
+ const numericCols = header.filter((h) => /^Variant Price |^Product (Weight|Length|Width|Height)$|^Variant (Weight|Length|Width|Height)$/.test(h));
24733
+ const boolCols = header.filter((h) => /Discountable|^Variant (Manage Inventory|Allow Backorder)$/.test(h));
24734
+ for (const r of rows.slice(1)) {
24735
+ for (const c of numericCols) {
24736
+ const v = (r[header.indexOf(c)] || "").trim();
24737
+ if (v && Number.isNaN(Number(v))) {
24738
+ warnings.push(`\u5217 "${c}" \u51FA\u73B0\u975E\u6570\u5B57\u503C "${v.slice(0, 40)}"\uFF08\u7591\u4F3C\u5217\u9519\u4F4D/\u503C\u4E32\u4F4D\uFF09`);
24739
+ }
24740
+ }
24741
+ for (const c of boolCols) {
24742
+ const v = (r[header.indexOf(c)] || "").trim().toUpperCase();
24743
+ if (v && v !== "TRUE" && v !== "FALSE") {
24744
+ warnings.push(`\u5217 "${c}" \u51FA\u73B0\u975E\u5E03\u5C14\u503C "${v.slice(0, 40)}"\uFF08\u7591\u4F3C\u5217\u9519\u4F4D/\u503C\u4E32\u4F4D\uFF09`);
24745
+ }
24746
+ }
24747
+ }
24748
+ const stringNumericCols = header.filter((h) => /HS Code|Barcode|MID Code/i.test(h));
24749
+ for (const r of rows.slice(1)) {
24750
+ for (const c of stringNumericCols) {
24751
+ const v = (r[header.indexOf(c)] || "").trim();
24752
+ if (v && /^[\d.]+$/.test(v)) {
24753
+ warnings.push(`\u5217 "${c}" \u7684\u7EAF\u6570\u5B57\u503C "${v}" \u4F1A\u88AB Medusa \u89E3\u6790\u4E3A number \u800C\u62A5\u9519\uFF08schema \u8981 string\uFF09\uFF1B\u5EFA\u8BAE\u8BE5\u5217\u7559\u7A7A\uFF0C\u5BFC\u5165\u540E\u7528 JSON API \u8865\u503C`);
24754
+ }
24755
+ }
24756
+ }
24757
+ return warnings;
24758
+ }
24759
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
24760
+ async function runTriggerCsvImport(ctx2, csvPath, confirm, pollTimeoutMs) {
24761
+ const { client: client2 } = ctx2;
24762
+ if (!existsSync5(csvPath)) return { error: `CSV \u6587\u4EF6\u4E0D\u5B58\u5728: ${csvPath}` };
24763
+ const raw = readFileSync5(csvPath);
24764
+ const text = stripBom2(raw.toString("utf8"));
24765
+ const lint = lintCsv(text, csvPath);
24766
+ const uploaded = await client2.importProductsCsv(raw, csvPath.split("/").pop() || "products.csv");
24767
+ const out = {
24768
+ uploaded: true,
24769
+ lint,
24770
+ transaction_id: uploaded.transaction_id,
24771
+ summary: uploaded.summary,
24772
+ dry_run: !confirm,
24773
+ note: confirm ? "\u5DF2\u786E\u8BA4\uFF0C\u540E\u53F0\u6B63\u5728\u6279\u91CF\u5BFC\u5165\uFF1B\u4E0B\u9762\u8F6E\u8BE2\u6267\u884C\u72B6\u6001\u3002" : "\u672A confirm\uFF1ACSV \u5DF2\u4E0A\u4F20\u5E76\u6821\u9A8C\uFF0C\u4F46\u5C1A\u672A\u5199\u5165\u4EFB\u4F55\u5546\u54C1\u3002\u786E\u8BA4\u8BF7\u7528 confirm=true \u5E26\u540C\u4E00 csv_path\u3002"
24774
+ };
24775
+ if (!confirm) return out;
24776
+ await client2.confirmProductImport(uploaded.transaction_id);
24777
+ out.confirmed = true;
24778
+ const TERMINAL_STATES = /* @__PURE__ */ new Set(["done", "failed", "reverted"]);
24779
+ let status = "submitted";
24780
+ const deadline = Date.now() + pollTimeoutMs;
24781
+ while (Date.now() < deadline) {
24782
+ await sleep(3e3);
24783
+ try {
24784
+ const ex = await client2.getWorkflowExecution(uploaded.transaction_id);
24785
+ if (ex?.state) {
24786
+ status = ex.state;
24787
+ if (TERMINAL_STATES.has(status)) break;
24788
+ }
24789
+ } catch {
24790
+ break;
24791
+ }
24792
+ }
24793
+ out.status = status;
24794
+ if (status === "failed" || status === "reverted") {
24795
+ out.error = `\u5BFC\u5165\u5DE5\u4F5C\u6D41\u72B6\u6001\u4E3A ${status}\uFF0C\u8BF7\u5230\u540E\u53F0 Products \u2192 Import \u67E5\u770B\u8BE5\u6279\u6B21\u9519\u8BEF\u8BE6\u60C5`;
24796
+ }
24797
+ out.note = status === "done" ? "\u5BFC\u5165\u5DE5\u4F5C\u6D41\u5DF2\u5B8C\u6210\uFF1B\u8BF7\u5230\u540E\u53F0\u6838\u5BF9\u5546\u54C1\uFF08\u6CE8\u610F\u539F\u751F\u5BFC\u5165\u4E0D\u542B\u56DB\u8BED/\u5BCC\u5185\u5BB9/\u5E93\u5B58\uFF0C\u9700\u53E6\u884C\u8865\u9F50\uFF09\u3002" : status === "failed" || status === "reverted" ? "\u5BFC\u5165\u5DE5\u4F5C\u6D41\u5931\u8D25/\u5DF2\u56DE\u6EDA\uFF0C\u672A\u5199\u5165\u6216\u5DF2\u64A4\u9500\u90E8\u5206\u5546\u54C1\uFF1B\u8BF7\u5230\u540E\u53F0\u6838\u5BF9\u5E76\u4FEE\u6B63 CSV \u540E\u91CD\u8BD5\u3002" : "\u5DF2\u63D0\u4EA4\u786E\u8BA4\uFF0C\u5BFC\u5165\u4ECD\u5728\u540E\u53F0\u6267\u884C\uFF08\u8F6E\u8BE2\u8D85\u65F6\u6216\u72B6\u6001\u7AEF\u70B9\u6682\u4E0D\u53EF\u7528\uFF09\uFF1B\u8BF7\u7A0D\u540E\u5230\u540E\u53F0 Products \u6838\u5BF9\u7ED3\u679C\u3002";
24798
+ return out;
24799
+ }
24800
+ var csvImportTools = [
24801
+ {
24802
+ name: "trigger_native_csv_import",
24803
+ description: `\u3010\u539F\u751F CSV \u5BFC\u5165\u81EA\u52A8\u5316\u3011\u628A\u540E\u53F0 Products \u2192 Import \u7684 CSV \u901A\u9053\u5B8C\u5168\u81EA\u52A8\u5316\uFF0C\u56E0\u6B64**\u539F\u751F\u652F\u6301\u591A\u53D8\u4F53/\u591A\u9009\u9879**\uFF08CSV \u6A21\u677F\u7684 Variant Option 1/2/3 \u5217\uFF09\u3002
24804
+ \u8F93\u5165\u672C\u5730 CSV \u7EDD\u5BF9\u8DEF\u5F84\uFF08\u4E0E product-import-template.csv \u540C\u5217\u540D\uFF09\u3002
24805
+ \u4E24\u6B65\uFF1A\u2460 \u4E0A\u4F20 CSV \u5230 /admin/products/import \u62FF transaction_id + summary(\u5C06\u5EFA/\u66F4\u591A\u5C11\u6B3E)\uFF1B\u2461 \u663E\u5F0F confirm=true \u624D\u771F\u6B63\u5728\u540E\u53F0\u6279\u91CF\u5EFA/\u66F4\u5546\u54C1\uFF08Medusa \u5BFC\u5165\u5DE5\u4F5C\u6D41\u9ED8\u8BA4\u7B49\u5F85\u786E\u8BA4\uFF09\u3002
24806
+ \u9ED8\u8BA4 confirm=false\uFF1A\u4EC5\u4E0A\u4F20 + \u8F7B\u91CF lint + \u8FD4\u56DE summary\uFF0C**\u96F6\u526F\u4F5C\u7528**\uFF08\u4E0D\u521B\u5EFA\u4EFB\u4F55\u5546\u54C1\uFF09\uFF0C\u53EF\u5B89\u5168\u9884\u68C0 CSV\u3002
24807
+ \u26A0\uFE0F \u4E0E batch_import_products\uFF08MCP \u58F0\u660E\u5F0F JSON\uFF09\u662F\u4E24\u5957\u673A\u5236\uFF1B\u539F\u751F CSV \u5BFC\u5165**\u4E0D\u542B\u56DB\u8BED\u7FFB\u8BD1/\u5BCC\u5185\u5BB9/\u5E93\u5B58**\uFF0C\u5BFC\u5165\u540E\u9700\u5230\u7CFB\u7EDF\u5185\u6216\u518D\u7528\u5176\u5B83\u5DE5\u5177\u8865\u9F50\u3002
24808
+ \u26A0\uFE0F \u5199\u5165\u524D\u52A1\u5FC5\u786E\u8BA4 CSV \u6B63\u786E\uFF1Alint \u4F1A\u68C0\u67E5\u5217\u5BF9\u9F50/ BOM / \u5FC5\u586B\u5217 / \u91CD\u590D Handle\u3002`,
24809
+ schema: {
24810
+ csv_path: external_exports.string().describe("\u672C\u5730 CSV \u6587\u4EF6\u7EDD\u5BF9\u8DEF\u5F84\uFF08\u5217\u540D\u4E0E\u540E\u53F0 Products \u2192 Import \u6A21\u677F\u4E00\u81F4\uFF09"),
24811
+ confirm: external_exports.boolean().default(false).describe("true \u624D\u771F\u6B63\u89E6\u53D1\u540E\u53F0\u6279\u91CF\u5BFC\u5165\uFF1Bfalse \u4EC5\u4E0A\u4F20+\u6821\u9A8C\uFF08\u96F6\u526F\u4F5C\u7528\uFF09"),
24812
+ poll_timeout_ms: external_exports.number().int().positive().max(12e4).default(6e4).describe("confirm \u540E\u8F6E\u8BE2\u6267\u884C\u72B6\u6001\u7684\u6700\u957F\u7B49\u5F85\uFF08\u6BEB\u79D2\uFF09")
24813
+ },
24814
+ async run(input, ctx2) {
24815
+ try {
24816
+ return await runTriggerCsvImport(ctx2, input.csv_path, Boolean(input.confirm), input.poll_timeout_ms ?? 6e4);
24817
+ } catch (e) {
24818
+ return { error: `\u539F\u751F CSV \u5BFC\u5165\u5931\u8D25\uFF1A${e instanceof Error ? e.message : String(e)}` };
24819
+ }
24820
+ }
24821
+ }
24822
+ ];
24823
+
23959
24824
  // src/tools/index.ts
23960
24825
  var toolDefs = [
23961
24826
  ...contextTools,
23962
24827
  ...productTools,
24828
+ ...categoryTools,
24829
+ ...collectionTools,
23963
24830
  ...translationTools,
23964
24831
  ...stockTools,
23965
24832
  ...opsTools,
23966
24833
  ...batchTools,
24834
+ ...csvImportTools,
23967
24835
  ...docTools
23968
24836
  ];
23969
24837
 
@@ -23982,7 +24850,7 @@ function audit(auditFile, name, args, ok) {
23982
24850
 
23983
24851
  // src/cli.ts
23984
24852
  function isCliInvocation(argv2) {
23985
- return argv2[0] === "import" || argv2.some((a) => a.startsWith("--"));
24853
+ return argv2[0] === "import" || argv2[0] === "import-csv" || argv2.some((a) => a.startsWith("--"));
23986
24854
  }
23987
24855
  var USAGE = `derlux-admin-mcp CLI
23988
24856
 
@@ -23990,6 +24858,9 @@ var USAGE = `derlux-admin-mcp CLI
23990
24858
  import --spec <path> --dry-run \u9884\u89C8\u6574\u6279\u5BFC\u5165\uFF0C\u8F93\u51FA\u6458\u8981\u4E0E confirm_token\uFF08\u4E0D\u5199\u5E93\uFF09
23991
24859
  import --spec <path> --commit --token <confirm_token> [--verbose]
23992
24860
  \u6309 dry-run \u7684 spec \u6B63\u5F0F\u5199\u5165
24861
+ import-csv --path <csv> \u4E0A\u4F20\u539F\u751F CSV \u5230 /admin/products/import \u5E76\u6821\u9A8C\uFF08\u96F6\u526F\u4F5C\u7528\uFF0C\u4E0D\u5199\u5E93\uFF09
24862
+ import-csv --path <csv> --confirm [--timeout <ms>]
24863
+ \u4E0A\u4F20\u5E76\u786E\u8BA4\u89E6\u53D1\u540E\u53F0\u6279\u91CF\u5BFC\u5165\uFF08\u4F1A\u771F\u6B63\u5EFA/\u66F4\u5546\u54C1\uFF09
23993
24864
  --help \u663E\u793A\u672C\u5E2E\u52A9
23994
24865
 
23995
24866
  \u793A\u4F8B\uFF1A
@@ -24015,6 +24886,33 @@ async function runCli(argv2, ctx2) {
24015
24886
  `);
24016
24887
  return out.ok ? 0 : 1;
24017
24888
  }
24889
+ if (argv2[0] === "import-csv") {
24890
+ const args2 = argv2.slice(1);
24891
+ const path = argValue(args2, "--path");
24892
+ if (!path) {
24893
+ process.stderr.write("\u7F3A\u5C11 --path <csv>\n");
24894
+ return 1;
24895
+ }
24896
+ const confirm = args2.includes("--confirm");
24897
+ const timeout = (() => {
24898
+ const t = argValue(args2, "--timeout");
24899
+ const n = t ? Number(t) : NaN;
24900
+ return Number.isFinite(n) && n > 0 ? Math.min(n, 12e4) : 6e4;
24901
+ })();
24902
+ try {
24903
+ const out = await runTriggerCsvImport(ctx2, path, confirm, timeout);
24904
+ process.stdout.write(`${JSON.stringify(out, null, 2)}
24905
+ `);
24906
+ if (out.error) return 1;
24907
+ const status = out.status;
24908
+ if (confirm && (status === "failed" || status === "reverted")) return 1;
24909
+ return 0;
24910
+ } catch (e) {
24911
+ process.stderr.write(`CSV \u5BFC\u5165\u5931\u8D25\uFF1A${e instanceof Error ? e.message : String(e)}
24912
+ `);
24913
+ return 1;
24914
+ }
24915
+ }
24018
24916
  if (argv2[0] !== "import") {
24019
24917
  process.stderr.write(`\u672A\u77E5\u547D\u4EE4/\u53C2\u6570: ${argv2.join(" ")}
24020
24918
 
@@ -24070,10 +24968,10 @@ if (isCliInvocation(argv)) {
24070
24968
  process.exit(code);
24071
24969
  }
24072
24970
  process.stderr.write(
24073
- `[derlux-admin] v0.2.0 backend=${config2.backendUrl} account=${config2.adminEmail || "(\u672A\u914D\u7F6E)"} session_scope=${config2.sessionScope} tools=${toolDefs.length}
24971
+ `[derlux-admin] v0.2.3 backend=${config2.backendUrl} account=${config2.adminEmail || "(\u672A\u914D\u7F6E)"} session_scope=${config2.sessionScope} tools=${toolDefs.length}
24074
24972
  `
24075
24973
  );
24076
- var server = new McpServer({ name: "derlux-admin", version: "0.2.0" });
24974
+ var server = new McpServer({ name: "derlux-admin", version: "0.2.3" });
24077
24975
  function isToolSuccess(result) {
24078
24976
  if (!result || typeof result !== "object") return true;
24079
24977
  const r = result;