From 065102e35ea90f2f3a4b74a7bf9702cf27914aa1 Mon Sep 17 00:00:00 2001 From: WuYongJie Date: Sat, 7 Nov 2026 10:05:03 +0800 Subject: [PATCH] feat(store-account): add shop metadata and searchable filters --- .../migration.sql | 10 +++ furniture-3d-system/prisma/schema.prisma | 3 + .../backfill-store-account-metadata.ts | 44 ++++++++++ .../StoreAccountManagementView.tsx | 45 +++------- .../storeAccountTableColumns.test.ts | 49 +++++++++++ .../storeAccountTableColumns.ts | 56 ++++++++++++- .../src/lib/store-account-management.test.ts | 27 ++++++ .../src/lib/store-account-management.ts | 33 ++++++-- .../src/lib/store-account-metadata-filters.ts | 28 +++++++ .../lib/store-account-store-metadata.test.ts | 54 ++++++++++++ .../src/lib/store-account-store-metadata.ts | 83 +++++++++++++++++++ ...tore-account-management.repository.test.ts | 51 ++++++++++++ .../store-account-management.repository.ts | 9 +- .../store-account-metadata-filters.ts | 29 +++++++ .../store-account-metadata.repository.ts | 46 ++++++++++ .../store-account-list.service.test.ts | 58 +++++++++++-- .../services/store-account-list.service.ts | 19 ++++- ...store-account-metadata-backfill.service.ts | 18 ++++ 18 files changed, 611 insertions(+), 51 deletions(-) create mode 100644 furniture-3d-system/prisma/migrations/20261106103000_add_store_account_metadata/migration.sql create mode 100644 furniture-3d-system/scripts/backfill-store-account-metadata.ts create mode 100644 furniture-3d-system/src/app/supply-chain/database/store-account-management/storeAccountTableColumns.test.ts create mode 100644 furniture-3d-system/src/lib/store-account-metadata-filters.ts create mode 100644 furniture-3d-system/src/lib/store-account-store-metadata.test.ts create mode 100644 furniture-3d-system/src/lib/store-account-store-metadata.ts create mode 100644 furniture-3d-system/src/server/repositories/store-account-metadata-filters.ts create mode 100644 furniture-3d-system/src/server/repositories/store-account-metadata.repository.ts create mode 100644 furniture-3d-system/src/server/services/store-account-metadata-backfill.service.ts diff --git a/furniture-3d-system/prisma/migrations/20261106103000_add_store_account_metadata/migration.sql b/furniture-3d-system/prisma/migrations/20261106103000_add_store_account_metadata/migration.sql new file mode 100644 index 00000000..9ddf97e5 --- /dev/null +++ b/furniture-3d-system/prisma/migrations/20261106103000_add_store_account_metadata/migration.sql @@ -0,0 +1,10 @@ +ALTER TABLE "StoreAccount" + ADD COLUMN "storeOwnership" VARCHAR(16), + ADD COLUMN "storeAttribute" VARCHAR(16), + ADD COLUMN "shippingEnabled" BOOLEAN; + +ALTER TABLE "StoreAccount" + ADD CONSTRAINT "StoreAccount_storeOwnership_check" + CHECK ("storeOwnership" IS NULL OR "storeOwnership" IN ('内部', '外部')), + ADD CONSTRAINT "StoreAccount_storeAttribute_check" + CHECK ("storeAttribute" IS NULL OR "storeAttribute" IN ('真实店铺', '虚拟店铺')); diff --git a/furniture-3d-system/prisma/schema.prisma b/furniture-3d-system/prisma/schema.prisma index ce043d45..a78ed534 100644 --- a/furniture-3d-system/prisma/schema.prisma +++ b/furniture-3d-system/prisma/schema.prisma @@ -4530,6 +4530,9 @@ model StoreAccount { jstOrderService String @default("") accountGroupName String @default("") shopState Int? + storeOwnership String? @db.VarChar(16) + storeAttribute String? @db.VarChar(16) + shippingEnabled Boolean? subject String @default("") boundBankAccountNumberCiphertext String @default("") @db.Text createdById String? diff --git a/furniture-3d-system/scripts/backfill-store-account-metadata.ts b/furniture-3d-system/scripts/backfill-store-account-metadata.ts new file mode 100644 index 00000000..219bcaab --- /dev/null +++ b/furniture-3d-system/scripts/backfill-store-account-metadata.ts @@ -0,0 +1,44 @@ +import { config as loadDotenv } from "dotenv"; +import fs from "node:fs/promises"; +import path from "node:path"; + +loadDotenv({ path: ".env.local", override: false }); +loadDotenv(); + +async function main() { + const args = process.argv.slice(2); + const file = args.find((arg) => arg.startsWith("--file="))?.slice(7); + const output = args.find((arg) => arg.startsWith("--output="))?.slice(9); + const apply = args.includes("--apply"); + if (args.includes("--help")) { + console.log("Usage: tsx scripts/backfill-store-account-metadata.ts --file= [--output=] [--apply]"); + console.log("Preview by default. Fills only matched blank fields. Apply is restricted to a local database."); + return; + } + if (!file || args.some((arg) => !arg.startsWith("--file=") && !arg.startsWith("--output=") && arg !== "--apply")) { + throw new Error("请指定 --file=,可选 --output= 和 --apply"); + } + const db = new URL(process.env.DATABASE_URL ?? ""); + if (!["localhost", "127.0.0.1", "[::1]"].includes(db.hostname)) throw new Error("本地补数入口禁止连接非本机数据库"); + if (apply && !output) throw new Error("补数必须指定 --output 保存修改前后审计"); + const { previewStoreAccountMetadataBackfill } = await import("../src/server/services/store-account-metadata-backfill.service"); + const { storeAccountMetadataRepository } = await import("../src/server/repositories/store-account-metadata.repository"); + console.log("正在读取表格并核对现有店铺资料……"); + const plan = await previewStoreAccountMetadataBackfill(file); + const report = { apply, source: path.basename(file), database: { host: db.hostname, port: db.port, name: db.pathname.slice(1) }, + checkedAt: new Date().toISOString(), ...plan, appliedAccounts: 0 }; + if (output) { + await fs.mkdir(path.dirname(path.resolve(output)), { recursive: true }); + await fs.writeFile(output, JSON.stringify(report, null, 2) + "\n", "utf8"); + } + if (apply) { + console.log(`已核对${plan.summary.accounts}条账号,正在补充${plan.updates.length}条……`); + report.appliedAccounts = await storeAccountMetadataRepository.applyUpdates(plan.updates, path.basename(file)); + await fs.writeFile(output!, JSON.stringify(report, null, 2) + "\n", "utf8"); + } + console.log(JSON.stringify({ apply, summary: plan.summary, unmatchedStores: plan.unmatchedStores, + appliedAccounts: report.appliedAccounts, failed: 0 }, null, 2)); +} + +main().catch((error) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; }) + .finally(async () => { const { prisma } = await import("../src/lib/prisma"); await prisma.$disconnect(); }); diff --git a/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountManagementView.tsx b/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountManagementView.tsx index b310a335..8fa2abc2 100644 --- a/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountManagementView.tsx +++ b/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountManagementView.tsx @@ -1,6 +1,7 @@ "use client"; import { STORE_ACCOUNT_SHOP_DATE_COLUMNS } from "@/lib/store-account-shop-info"; +import { STORE_ACCOUNT_METADATA_COLUMNS, formatStoreAccountShipping } from "@/lib/store-account-store-metadata"; import { useEffect, @@ -42,12 +43,10 @@ import { getStoreAccountProfilePlatformForStoreName, STORE_ACCOUNT_FIELDS, STORE_ACCOUNT_AUTHORIZATION_COLUMN, - STORE_ACCOUNT_AUTHORIZATION_FILTER_OPTIONS, STORE_ACCOUNT_OWNER_STATUS_FILTER_OPTIONS, STORE_ACCOUNT_PROFILE_FIELDS, STORE_ACCOUNT_SHOP_STATE_COLUMN, STORE_ACCOUNT_PLATFORM_COLUMN, - STORE_ACCOUNT_EMPTY_PLATFORM_FILTER, } from "@/lib/store-account-management"; import { ColumnHeaderFilter } from "@/components/common/ColumnHeaderFilter"; import { StoreAccountBatchUpdateDialog } from "./StoreAccountBatchUpdateDialog"; @@ -64,9 +63,10 @@ import { import { useStoreAccountImport } from "./useStoreAccountImport"; import { STORE_ACCOUNT_HEADER_FILTER_KEYS, - fromStoreAccountHeaderFilterSelection, + getStoreAccountHeaderFilterOptions, + getStoreAccountHeaderFilterValue, + getStoreAccountHeaderFilterSelection, getStoreAccountHeaderFilterStateKey, - toStoreAccountHeaderFilterSelection, type StoreAccountHeaderFilterKey, type StoreAccountHeaderFilterOption, type StoreAccountTableColumn, @@ -160,6 +160,7 @@ export function StoreAccountManagementView({ ? [ field, STORE_ACCOUNT_SHOP_STATE_COLUMN, + ...STORE_ACCOUNT_METADATA_COLUMNS, ...STORE_ACCOUNT_SHOP_DATE_COLUMNS, STORE_ACCOUNT_AUTHORIZATION_COLUMN, ] @@ -253,12 +254,9 @@ export function StoreAccountManagementView({ options: readonly StoreAccountHeaderFilterOption[], ) => { const stateKey = getStoreAccountHeaderFilterStateKey(key); - const value = fromStoreAccountHeaderFilterSelection(selection, options); const nextFilters = { ...filters, - [stateKey]: key === "platform" && selection && !value - ? STORE_ACCOUNT_EMPTY_PLATFORM_FILTER - : value, + [stateKey]: getStoreAccountHeaderFilterValue(key, selection, options), }; setFilters(nextFilters); void load(nextFilters, 1, data.pageInfo.pageSize); @@ -266,27 +264,7 @@ export function StoreAccountManagementView({ const headerFilterOptions = ( key: StoreAccountHeaderFilterKey, - ): StoreAccountHeaderFilterOption[] => { - if (key === "shopState") { - return data.filterOptions.shopState.map((value) => ({ - value, - label: formatStoreAccountShopState(Number(value)), - })); - } - if (key === "authorizationStatus") { - return STORE_ACCOUNT_AUTHORIZATION_FILTER_OPTIONS.map((option) => ({ - value: option.value, - label: option.label, - })); - } - if (key === "accountType") { - return data.filterOptions.accountType.map((value) => ({ - value, - label: formatStoreAccountType(value), - })); - } - return data.filterOptions[key].map((value) => ({ value, label: value })); - }; + ) => getStoreAccountHeaderFilterOptions(key, data.filterOptions); const storeAccountImport = useStoreAccountImport({ onCompleted: () => load(filters, 1, data.pageInfo.pageSize), @@ -644,9 +622,8 @@ export function StoreAccountManagementView({ field.key as StoreAccountHeaderFilterKey, ).map((option) => option.label) } - selection={field.key === "platform" && !filters.platform - ? null - : toStoreAccountHeaderFilterSelection( + selection={getStoreAccountHeaderFilterSelection( + field.key as StoreAccountHeaderFilterKey, filters[ getStoreAccountHeaderFilterStateKey( field.key as StoreAccountHeaderFilterKey, @@ -719,6 +696,10 @@ export function StoreAccountManagementView({ formatStoreAccountShopState(row.shopState) ) : field.key === "openTime" || field.key === "renewalTime" ? ( row[field.key] || "-" + ) : field.key === "shippingEnabled" ? ( + formatStoreAccountShipping(row.shippingEnabled) + ) : field.key === "storeOwnership" || field.key === "storeAttribute" ? ( + row[field.key] || "-" ) : field.key === "authorizationStatus" ? ( formatStoreAccountAuthorizationStatus( row.authorizationStatus, diff --git a/furniture-3d-system/src/app/supply-chain/database/store-account-management/storeAccountTableColumns.test.ts b/furniture-3d-system/src/app/supply-chain/database/store-account-management/storeAccountTableColumns.test.ts new file mode 100644 index 00000000..74c705fe --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/database/store-account-management/storeAccountTableColumns.test.ts @@ -0,0 +1,49 @@ +import { + STORE_ACCOUNT_HEADER_FILTER_KEYS, + getStoreAccountHeaderFilterOptions, + getStoreAccountHeaderFilterSelection, + getStoreAccountHeaderFilterValue, + getStoreAccountHeaderFilterStateKey, +} from "./storeAccountTableColumns"; +import { + STORE_ACCOUNT_METADATA_BLANK_FILTER, + STORE_ACCOUNT_METADATA_FILTER_OPTIONS, + STORE_ACCOUNT_METADATA_NONE_FILTER, + type StoreAccountMetadataFilterKey, +} from "@/lib/store-account-metadata-filters"; +import type { StoreAccountPage } from "@/lib/store-account-management"; + +describe("store account metadata header filters", () => { + it.each(Object.keys(STORE_ACCOUNT_METADATA_FILTER_OPTIONS) as StoreAccountMetadataFilterKey[])( + "registers %s with its complete choices and maps it to its query key", + (key) => { + expect(STORE_ACCOUNT_HEADER_FILTER_KEYS.has(key)).toBe(true); + expect(getStoreAccountHeaderFilterStateKey(key)).toBe(key); + const options = getStoreAccountHeaderFilterOptions(key, {} as StoreAccountPage["filterOptions"]); + expect(options).toHaveLength(3); + expect(options[2]).toEqual({ value: STORE_ACCOUNT_METADATA_BLANK_FILTER, label: "未填写" }); + expect(getStoreAccountHeaderFilterSelection(key, "", options)).toBeNull(); + }, + ); + + const options = STORE_ACCOUNT_METADATA_FILTER_OPTIONS.shippingEnabled; + it("round-trips no-shipping and unknown as separate choices", () => { + const selection = { mode: "include" as const, values: ["否", "未填写"] }; + const value = getStoreAccountHeaderFilterValue("shippingEnabled", selection, options); + expect(value).toBe(`false,${STORE_ACCOUNT_METADATA_BLANK_FILTER}`); + expect(getStoreAccountHeaderFilterSelection("shippingEnabled", value, options)).toEqual(selection); + }); + + it("supports selecting all and then excluding a choice", () => { + expect(getStoreAccountHeaderFilterValue("shippingEnabled", { mode: "exclude", values: ["是"] }, options)) + .toBe(`false,${STORE_ACCOUNT_METADATA_BLANK_FILTER}`); + }); + + it("keeps selecting none separate from clearing the filter", () => { + expect(getStoreAccountHeaderFilterValue("shippingEnabled", { mode: "include", values: [] }, options)) + .toBe(STORE_ACCOUNT_METADATA_NONE_FILTER); + expect(getStoreAccountHeaderFilterSelection("shippingEnabled", STORE_ACCOUNT_METADATA_NONE_FILTER, options)) + .toEqual({ mode: "include", values: [] }); + expect(getStoreAccountHeaderFilterValue("shippingEnabled", null, options)).toBe(""); + }); +}); diff --git a/furniture-3d-system/src/app/supply-chain/database/store-account-management/storeAccountTableColumns.ts b/furniture-3d-system/src/app/supply-chain/database/store-account-management/storeAccountTableColumns.ts index 8eb62946..4b04b72f 100644 --- a/furniture-3d-system/src/app/supply-chain/database/store-account-management/storeAccountTableColumns.ts +++ b/furniture-3d-system/src/app/supply-chain/database/store-account-management/storeAccountTableColumns.ts @@ -1,10 +1,22 @@ import type { ColumnHeaderFilterSelection } from "@/lib/column-header-filters"; import { STORE_ACCOUNT_SHOP_DATE_COLUMNS } from "@/lib/store-account-shop-info"; +import { STORE_ACCOUNT_METADATA_COLUMNS } from "@/lib/store-account-store-metadata"; import { + STORE_ACCOUNT_METADATA_FILTER_OPTIONS, + STORE_ACCOUNT_METADATA_NONE_FILTER, + isStoreAccountMetadataFilterKey, + type StoreAccountMetadataFilterKey, +} from "@/lib/store-account-metadata-filters"; +import { + formatStoreAccountShopState, + formatStoreAccountType, + STORE_ACCOUNT_AUTHORIZATION_FILTER_OPTIONS, + STORE_ACCOUNT_EMPTY_PLATFORM_FILTER, STORE_ACCOUNT_FIELDS, STORE_ACCOUNT_SHOP_STATE_COLUMN, STORE_ACCOUNT_AUTHORIZATION_COLUMN, STORE_ACCOUNT_PLATFORM_COLUMN, + type StoreAccountPage, } from "@/lib/store-account-management"; export type StoreAccountTableColumn = @@ -12,7 +24,8 @@ export type StoreAccountTableColumn = | typeof STORE_ACCOUNT_SHOP_STATE_COLUMN | typeof STORE_ACCOUNT_AUTHORIZATION_COLUMN | typeof STORE_ACCOUNT_PLATFORM_COLUMN - | (typeof STORE_ACCOUNT_SHOP_DATE_COLUMNS)[number]; + | (typeof STORE_ACCOUNT_SHOP_DATE_COLUMNS)[number] + | (typeof STORE_ACCOUNT_METADATA_COLUMNS)[number]; export type StoreAccountHeaderFilterOption = { value: string; @@ -20,6 +33,7 @@ export type StoreAccountHeaderFilterOption = { }; export type StoreAccountHeaderFilterKey = + | StoreAccountMetadataFilterKey | "storeName" | "operationOwner" | "operationDepartmentHead" @@ -77,6 +91,9 @@ export const STORE_ACCOUNT_HEADER_FILTER_KEYS = new Set { return key === "operationOwner" ? "operationOwnerExact" : key; } + +export function getStoreAccountHeaderFilterOptions( + key: StoreAccountHeaderFilterKey, + filterOptions: StoreAccountPage["filterOptions"], +): StoreAccountHeaderFilterOption[] { + if (isStoreAccountMetadataFilterKey(key)) { + return [...STORE_ACCOUNT_METADATA_FILTER_OPTIONS[key]]; + } + if (key === "authorizationStatus") return [...STORE_ACCOUNT_AUTHORIZATION_FILTER_OPTIONS]; + return filterOptions[key].map((value) => ({ + value, + label: key === "shopState" ? formatStoreAccountShopState(Number(value)) + : key === "accountType" ? formatStoreAccountType(value) : value, + })); +} + +export function getStoreAccountHeaderFilterValue( + key: StoreAccountHeaderFilterKey, + selection: ColumnHeaderFilterSelection | null, + options: readonly StoreAccountHeaderFilterOption[], +) { + const value = fromStoreAccountHeaderFilterSelection(selection, options); + if (selection && !value) { + if (isStoreAccountMetadataFilterKey(key)) return STORE_ACCOUNT_METADATA_NONE_FILTER; + if (key === "platform") return STORE_ACCOUNT_EMPTY_PLATFORM_FILTER; + } + return value; +} + +export function getStoreAccountHeaderFilterSelection( + key: StoreAccountHeaderFilterKey, + value: string, + options: readonly StoreAccountHeaderFilterOption[], +) { + if (!value && (isStoreAccountMetadataFilterKey(key) || key === "platform")) return null; + return toStoreAccountHeaderFilterSelection(value, options); +} diff --git a/furniture-3d-system/src/lib/store-account-management.test.ts b/furniture-3d-system/src/lib/store-account-management.test.ts index 39233001..0d95287f 100644 --- a/furniture-3d-system/src/lib/store-account-management.test.ts +++ b/furniture-3d-system/src/lib/store-account-management.test.ts @@ -1,6 +1,7 @@ import { buildDepartedStoreAccountOwnerNames, formatStoreAccountLogValue, + formatStoreAccountShopState, formatStoreAccountType, getStoreAccountLogFieldLabel, getStoreAccountLogOperationLabel, @@ -8,8 +9,34 @@ import { normalizeStoreAccountLogChanges, resolveStoreAccountFieldVisibility, resolveStoreAccountOwnerAutofill, + STORE_ACCOUNT_SHOP_STATE_FILTER_OPTIONS, } from './store-account-management' +describe('store account state dictionary', () => { + const states = [ + { value: '0', label: '正常' }, + { value: '1', label: '开店中' }, + { value: '2', label: '变更中' }, + { value: '3', label: '已出售' }, + { value: '4', label: '出售中' }, + { value: '5', label: '关闭中' }, + { value: '6', label: '已关闭' }, + ] + + it('uses all seven official state codes for display and filter options', () => { + expect(STORE_ACCOUNT_SHOP_STATE_FILTER_OPTIONS).toEqual(states) + for (const { value, label } of states) { + expect(formatStoreAccountShopState(Number(value))).toBe(label) + } + }) + + it('keeps missing and future state codes distinguishable', () => { + expect(formatStoreAccountShopState(null)).toBe('-') + expect(formatStoreAccountShopState(undefined)).toBe('-') + expect(formatStoreAccountShopState(8)).toBe('状态8') + }) +}) + describe('store account type presentation', () => { it('keeps incomplete imported values visible without treating them as sub accounts', () => { expect(formatStoreAccountType('MAIN')).toBe('主账号') diff --git a/furniture-3d-system/src/lib/store-account-management.ts b/furniture-3d-system/src/lib/store-account-management.ts index bfb8871a..8f01bf5c 100644 --- a/furniture-3d-system/src/lib/store-account-management.ts +++ b/furniture-3d-system/src/lib/store-account-management.ts @@ -1,3 +1,5 @@ +import { STORE_ACCOUNT_METADATA_COLUMNS } from "./store-account-store-metadata"; + export const STORE_ACCOUNT_FIELD_KEYS = [ "storeName", "operationOwner", @@ -133,6 +135,9 @@ export const STORE_ACCOUNT_FILTER_KEYS = [ "platform", "accountGroupName", "shopState", + "storeOwnership", + "storeAttribute", + "shippingEnabled", "authorizationStatus", "createdAtGranularity", "createdAtValue", @@ -156,6 +161,9 @@ export const EMPTY_STORE_ACCOUNT_FILTERS: StoreAccountFilters = { platform: "", accountGroupName: "", shopState: "", + storeOwnership: "", + storeAttribute: "", + shippingEnabled: "", authorizationStatus: "", createdAtGranularity: "", createdAtValue: "", @@ -239,6 +247,10 @@ export type StoreAccountRow = { /** 源表日期;列表始终返回,非列表旧接口可省略。 */ openTime?: string | null; renewalTime?: string | null; + /** 表格补充的只读店铺资料;未匹配时为空。 */ + storeOwnership?: string | null; + storeAttribute?: string | null; + shippingEnabled?: boolean | null; authorizationStatus: StoreAccountAuthorizationStatus | null; createdAt: string; updatedAt: string; @@ -268,6 +280,9 @@ export type StoreAccountPage = { platform: string[]; accountType: string[]; shopState: string[]; + storeOwnership: string[]; + storeAttribute: string[]; + shippingEnabled: string[]; authorizationStatus: string[]; }; pageInfo: { @@ -338,18 +353,20 @@ export const STORE_ACCOUNT_AUTHORIZATION_COLUMN = { label: "授权状态", } as const; -// 公司报表库 rpt.fys_shopInfo.shopState 是数字码;0/6/3 的中文含义是与维度表 status 行数对照推断的,不是官方字典 +// 公司报表库 rpt.fys_shopInfo.shopState;按用户提供的字段字典展示。 export const STORE_ACCOUNT_SHOP_STATE_LABELS: Record = { 0: "正常", - 6: "已关闭", + 1: "开店中", + 2: "变更中", 3: "已出售", + 4: "出售中", + 5: "关闭中", + 6: "已关闭", }; -export const STORE_ACCOUNT_SHOP_STATE_FILTER_OPTIONS = [ - { value: "0", label: "正常" }, - { value: "6", label: "已关闭" }, - { value: "3", label: "已出售" }, -] as const; +export const STORE_ACCOUNT_SHOP_STATE_FILTER_OPTIONS = Object.entries( + STORE_ACCOUNT_SHOP_STATE_LABELS, +).map(([value, label]) => ({ value, label })); export const STORE_ACCOUNT_AUTHORIZATION_FILTER_OPTIONS = [ { value: "AUTHORIZED", label: "已授权" }, @@ -434,6 +451,8 @@ export function getStoreAccountLogOperationLabel(operation: string) { } export function getStoreAccountLogFieldLabel(field: string) { + const metadata = STORE_ACCOUNT_METADATA_COLUMNS.find((column) => column.key === field); + if (metadata) return metadata.label; if (isStoreAccountFieldKey(field)) return getStoreAccountFieldLabel(field); const [platform, profileKey] = field.split(".", 2); const profileField = STORE_ACCOUNT_PROFILE_FIELDS.find( diff --git a/furniture-3d-system/src/lib/store-account-metadata-filters.ts b/furniture-3d-system/src/lib/store-account-metadata-filters.ts new file mode 100644 index 00000000..b85d84d0 --- /dev/null +++ b/furniture-3d-system/src/lib/store-account-metadata-filters.ts @@ -0,0 +1,28 @@ +export const STORE_ACCOUNT_METADATA_BLANK_FILTER = "__UNFILLED__"; +export const STORE_ACCOUNT_METADATA_NONE_FILTER = "__NONE_SELECTED__"; + +const blankOption = { value: STORE_ACCOUNT_METADATA_BLANK_FILTER, label: "未填写" }; + +export const STORE_ACCOUNT_METADATA_FILTER_OPTIONS = { + storeOwnership: [ + { value: "内部", label: "内部" }, + { value: "外部", label: "外部" }, + blankOption, + ], + storeAttribute: [ + { value: "真实店铺", label: "真实店铺" }, + { value: "虚拟店铺", label: "虚拟店铺" }, + blankOption, + ], + shippingEnabled: [ + { value: "true", label: "是" }, + { value: "false", label: "否" }, + blankOption, + ], +} as const; + +export type StoreAccountMetadataFilterKey = keyof typeof STORE_ACCOUNT_METADATA_FILTER_OPTIONS; + +export function isStoreAccountMetadataFilterKey(key: string): key is StoreAccountMetadataFilterKey { + return Object.hasOwn(STORE_ACCOUNT_METADATA_FILTER_OPTIONS, key); +} diff --git a/furniture-3d-system/src/lib/store-account-store-metadata.test.ts b/furniture-3d-system/src/lib/store-account-store-metadata.test.ts new file mode 100644 index 00000000..04ab15b6 --- /dev/null +++ b/furniture-3d-system/src/lib/store-account-store-metadata.test.ts @@ -0,0 +1,54 @@ +import { + formatStoreAccountShipping, parseStoreAccountMetadataRows, planStoreAccountMetadataBackfill, + type StoreAccountMetadataRecord, +} from "./store-account-store-metadata"; + +const headers = ["店铺名称", "店铺状态", "店铺归属", "店铺属性", "是否发货", "店铺状态"]; +const cells = [headers, [" 店铺 ", "#N/A", "内部", "真实店铺", "否", "禁用"]]; +const blank = (id: string, storeName = "店铺"): StoreAccountMetadataRecord => ({ + id, storeName, storeOwnership: null, storeAttribute: null, shippingEnabled: null, +}); + +it("reads only the three metadata fields, preserving false and ignoring both state columns", () => { + const source = parseStoreAccountMetadataRows(cells); + expect(source).toEqual([{ storeName: "店铺", sourceRow: 2, storeOwnership: "内部", storeAttribute: "真实店铺", shippingEnabled: false }]); + expect(formatStoreAccountShipping(false)).toBe("否"); + expect(formatStoreAccountShipping(true)).toBe("是"); + expect(formatStoreAccountShipping(null)).toBe("-"); +}); + +it("fills every account of the exact store, and leaves unmatched or punctuation variants untouched", () => { + const source = parseStoreAccountMetadataRows(cells); + const plan = planStoreAccountMetadataBackfill(source, [blank("main"), blank("sub", " 店铺 "), blank("other", "店铺(作废)")]); + expect(plan.updates.map((row) => row.before.id)).toEqual(["main", "sub"]); + expect(plan.summary).toMatchObject({ matchedStores: 1, updatedAccounts: 2, unmatchedStores: 1 }); + expect(plan.unmatchedStores).toEqual(["店铺(作废)"]); +}); + +it("does not fuzzy-match parentheses or create stores found only in the spreadsheet", () => { + const source = parseStoreAccountMetadataRows([headers, ["店铺(作废)", "正常", "内部", "虚拟店铺", "是", "启用"]]); + expect(planStoreAccountMetadataBackfill(source, [blank("1", "店铺(作废)")]).summary) + .toMatchObject({ updatedAccounts: 0, unmatchedStores: 1, sourceOnlyStores: 1 }); +}); + +it("is idempotent and refuses to overwrite conflicting existing metadata", () => { + const source = parseStoreAccountMetadataRows(cells); + const populated = { ...blank("1"), storeOwnership: "内部", storeAttribute: "真实店铺", shippingEnabled: false }; + expect(planStoreAccountMetadataBackfill(source, [populated]).summary).toMatchObject({ updatedAccounts: 0, unchangedAccounts: 1 }); + expect(() => planStoreAccountMetadataBackfill(source, [{ ...populated, shippingEnabled: true }])).toThrow("冲突"); +}); + +it("rejects conflicting duplicate source names before planning any changes", () => { + const source = parseStoreAccountMetadataRows([...cells, ["店铺", "正常", "外部", "真实店铺", "否", "启用"]]); + expect(() => planStoreAccountMetadataBackfill(source, [blank("1")])).toThrow("资料冲突"); +}); + +it.each(["", "true", "未知"])("rejects invalid shipping input %s with its row number", (value) => { + expect(() => parseStoreAccountMetadataRows([headers, ["店铺", "正常", "内部", "真实店铺", value, "启用"]])).toThrow("第2行"); +}); + +it("rejects missing or duplicate required headers and empty sources", () => { + expect(() => parseStoreAccountMetadataRows([["店铺名称"]])).toThrow("店铺归属"); + expect(() => parseStoreAccountMetadataRows([[...headers, "是否发货"]])).toThrow("是否发货"); + expect(() => planStoreAccountMetadataBackfill([], [])).toThrow("没有可补充的数据"); +}); diff --git a/furniture-3d-system/src/lib/store-account-store-metadata.ts b/furniture-3d-system/src/lib/store-account-store-metadata.ts new file mode 100644 index 00000000..5d88e5b4 --- /dev/null +++ b/furniture-3d-system/src/lib/store-account-store-metadata.ts @@ -0,0 +1,83 @@ +export const STORE_ACCOUNT_METADATA_COLUMNS = [ + { key: "storeOwnership", label: "店铺归属" }, + { key: "storeAttribute", label: "店铺属性" }, + { key: "shippingEnabled", label: "是否发货" }, +] as const; + +export type StoreAccountMetadata = { + storeOwnership: string | null; + storeAttribute: string | null; + shippingEnabled: boolean | null; +}; + +export type StoreAccountMetadataSource = StoreAccountMetadata & { + storeName: string; + sourceRow: number; +}; + +export type StoreAccountMetadataRecord = StoreAccountMetadata & { + id: string; + storeName: string; +}; + +export function formatStoreAccountShipping(value: boolean | null | undefined) { + return value == null ? "-" : value ? "是" : "否"; +} + +export function parseStoreAccountMetadataRows(cells: string[][]): StoreAccountMetadataSource[] { + const headers = cells[0]?.map((value) => value.trim()) ?? []; + const labels = ["店铺名称", ...STORE_ACCOUNT_METADATA_COLUMNS.map((column) => column.label)]; + const indexes = labels.map((label) => { + const positions = headers.flatMap((header, index) => header === label ? [index] : []); + if (positions.length !== 1) throw new Error(`表头“${label}”必须且只能出现一次`); + return positions[0]; + }); + return cells.slice(1).flatMap((row, index) => { + if (row.every((value) => !value.trim())) return []; + const [storeName, storeOwnership, storeAttribute, shipping] = indexes.map((column) => (row[column] ?? "").trim()); + const sourceRow = index + 2; + if (!storeName || !["内部", "外部"].includes(storeOwnership) + || !["真实店铺", "虚拟店铺"].includes(storeAttribute) || !["是", "否"].includes(shipping)) { + throw new Error(`第${sourceRow}行店铺名称或三个资料字段无效`); + } + return [{ storeName, storeOwnership, storeAttribute, shippingEnabled: shipping === "是", sourceRow }]; + }); +} + +export function planStoreAccountMetadataBackfill( + source: StoreAccountMetadataSource[], records: StoreAccountMetadataRecord[], +) { + if (!source.length) throw new Error("表格没有可补充的数据"); + const byName = new Map(); + for (const row of source) { + const name = row.storeName.trim(); + const previous = byName.get(name); + if (previous && STORE_ACCOUNT_METADATA_COLUMNS.some(({ key }) => previous[key] !== row[key])) { + throw new Error(`第${previous.sourceRow}、${row.sourceRow}行店铺“${name}”资料冲突`); + } + byName.set(name, { ...row, storeName: name }); + } + const updates: Array<{ before: StoreAccountMetadataRecord; after: StoreAccountMetadata; sourceRow: number }> = []; + const matchedStores = new Set(); + const unmatchedStores = new Set(); + let unchangedAccounts = 0; + for (const record of records) { + const sourceRow = byName.get(record.storeName.trim()); + if (!sourceRow) { unmatchedStores.add(record.storeName); continue; } + matchedStores.add(record.storeName.trim()); + const after = Object.fromEntries(STORE_ACCOUNT_METADATA_COLUMNS.map(({ key }) => [key, sourceRow[key]])) as StoreAccountMetadata; + const changed = STORE_ACCOUNT_METADATA_COLUMNS.filter(({ key }) => record[key] !== after[key]); + // This command fills blanks only. Existing conflicting data needs separate review. + if (changed.some(({ key }) => record[key] != null && record[key] !== "")) { + throw new Error(`店铺“${record.storeName}”已有资料与表格冲突,未执行补数`); + } + if (!changed.length) { unchangedAccounts++; continue; } + updates.push({ before: record, after, sourceRow: sourceRow.sourceRow }); + } + return { + summary: { sourceStores: byName.size, accounts: records.length, matchedStores: matchedStores.size, + updatedAccounts: updates.length, unchangedAccounts, unmatchedStores: unmatchedStores.size, + sourceOnlyStores: [...byName.keys()].filter((name) => !matchedStores.has(name)).length }, + unmatchedStores: [...unmatchedStores].sort(), updates, + }; +} diff --git a/furniture-3d-system/src/server/repositories/__tests__/store-account-management.repository.test.ts b/furniture-3d-system/src/server/repositories/__tests__/store-account-management.repository.test.ts index 3b4865eb..765e3cc6 100644 --- a/furniture-3d-system/src/server/repositories/__tests__/store-account-management.repository.test.ts +++ b/furniture-3d-system/src/server/repositories/__tests__/store-account-management.repository.test.ts @@ -8,6 +8,8 @@ jest.mock('@/lib/prisma', () => ({ })) import { prisma } from '@/lib/prisma' +import { EMPTY_STORE_ACCOUNT_FILTERS } from '@/lib/store-account-management' +import { STORE_ACCOUNT_METADATA_BLANK_FILTER, STORE_ACCOUNT_METADATA_NONE_FILTER } from '@/lib/store-account-metadata-filters' import { buildStoreAccountCreatedAtFilter, StoreAccountManagementRepository } from '../store-account-management.repository' const mockPrisma = prisma as unknown as { @@ -25,6 +27,7 @@ describe('StoreAccountManagementRepository list ordering', () => { skip: 0, take: 50, filters: { + ...EMPTY_STORE_ACCOUNT_FILTERS, search: '', storeName: '', accountType: '', @@ -61,6 +64,7 @@ describe('StoreAccountManagementRepository list ordering', () => { skip: 0, take: 50, filters: { + ...EMPTY_STORE_ACCOUNT_FILTERS, search: '', storeName: '', accountType: '', @@ -83,3 +87,50 @@ describe('StoreAccountManagementRepository list ordering', () => { })) }) }) + +describe('store account metadata filtering', () => { + beforeEach(() => { + jest.clearAllMocks() + mockPrisma.storeAccount.findMany.mockResolvedValue([]) + mockPrisma.storeAccount.count.mockResolvedValue(0) + }) + + it.each([ + ['true', [{ shippingEnabled: true }]], + ['false', [{ shippingEnabled: false }]], + [STORE_ACCOUNT_METADATA_BLANK_FILTER, [{ shippingEnabled: null }]], + [`false,${STORE_ACCOUNT_METADATA_BLANK_FILTER}`, [{ shippingEnabled: false }, { shippingEnabled: null }]], + ])('keeps the shipping choice %s distinct and applies it to both rows and count', async (value, choices) => { + await new StoreAccountManagementRepository().listPage({ + skip: 20, take: 10, filters: { ...EMPTY_STORE_ACCOUNT_FILTERS, shippingEnabled: value }, + }) + const where = { AND: [{ OR: choices }] } + expect(mockPrisma.storeAccount.findMany).toHaveBeenCalledWith(expect.objectContaining({ where, skip: 20, take: 10 })) + expect(mockPrisma.storeAccount.count).toHaveBeenCalledWith({ where }) + }) + + it('combines columns with AND and values within a column with OR before a derived full scan', async () => { + await new StoreAccountManagementRepository().listAll({ filters: { + ...EMPTY_STORE_ACCOUNT_FILTERS, + storeOwnership: `内部;${STORE_ACCOUNT_METADATA_BLANK_FILTER}`, + storeAttribute: '虚拟店铺', shippingEnabled: 'false', + } }) + expect(mockPrisma.storeAccount.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { AND: [ + { OR: [{ storeOwnership: '内部' }, { storeOwnership: null }, { storeOwnership: '' }] }, + { OR: [{ storeAttribute: '虚拟店铺' }] }, + { OR: [{ shippingEnabled: false }] }, + ] } })) + }) + + it.each([STORE_ACCOUNT_METADATA_NONE_FILTER, 'invalid', '0'])('returns no matches for an explicit empty or invalid choice %s', async (value) => { + await new StoreAccountManagementRepository().listPage({ + skip: 0, take: 10, filters: { ...EMPTY_STORE_ACCOUNT_FILTERS, shippingEnabled: value }, + }) + expect(mockPrisma.storeAccount.count).toHaveBeenCalledWith({ where: { AND: [{ id: { in: [] } }] } }) + }) + + it('clears metadata conditions when the selections are reset', async () => { + await new StoreAccountManagementRepository().listPage({ skip: 0, take: 10, filters: { ...EMPTY_STORE_ACCOUNT_FILTERS } }) + expect(mockPrisma.storeAccount.count).toHaveBeenCalledWith({ where: undefined }) + }) +}) diff --git a/furniture-3d-system/src/server/repositories/store-account-management.repository.ts b/furniture-3d-system/src/server/repositories/store-account-management.repository.ts index 5e890fbb..dc4bd62d 100644 --- a/furniture-3d-system/src/server/repositories/store-account-management.repository.ts +++ b/furniture-3d-system/src/server/repositories/store-account-management.repository.ts @@ -1,5 +1,6 @@ import type { Prisma } from '@prisma/client' import { prisma } from '@/lib/prisma' +import { buildStoreAccountMetadataFilters } from './store-account-metadata-filters' import type { StoreAccountFilterKey, StoreAccountFilters, StoreAccountFieldPermissionUpdate } from '@/lib/store-account-management' export type StoreAccountRecord = { @@ -17,6 +18,9 @@ export type StoreAccountRecord = { jstOrderService: string accountGroupName: string shopState: number | null + storeOwnership?: string | null + storeAttribute?: string | null + shippingEnabled?: boolean | null subject: string boundBankAccountNumberCiphertext: string createdAt: Date @@ -67,6 +71,9 @@ const ACCOUNT_SELECT = { jstOrderService: true, accountGroupName: true, shopState: true, + storeOwnership: true, + storeAttribute: true, + shippingEnabled: true, subject: true, boundBankAccountNumberCiphertext: true, createdAt: true, @@ -143,7 +150,7 @@ export function buildStoreAccountCreatedAtFilter(filters: Pick> = [] + const and: Array> = [...buildStoreAccountMetadataFilters(filters)] if (filters.search) { const searchTokens = [...new Set(filters.search.split(/[\s,,;;]+/).map((value) => value.trim()).filter(Boolean))].slice(0, 100) and.push({ OR: searchTokens.flatMap((token) => [ diff --git a/furniture-3d-system/src/server/repositories/store-account-metadata-filters.ts b/furniture-3d-system/src/server/repositories/store-account-metadata-filters.ts new file mode 100644 index 00000000..9320efe9 --- /dev/null +++ b/furniture-3d-system/src/server/repositories/store-account-metadata-filters.ts @@ -0,0 +1,29 @@ +import type { Prisma } from "@prisma/client"; +import type { StoreAccountFilters } from "@/lib/store-account-management"; +import { + STORE_ACCOUNT_METADATA_BLANK_FILTER, + STORE_ACCOUNT_METADATA_FILTER_OPTIONS, + type StoreAccountMetadataFilterKey, +} from "@/lib/store-account-metadata-filters"; + +/** Each column is an OR; selected columns are combined with AND before pagination. */ +export function buildStoreAccountMetadataFilters(filters: StoreAccountFilters): Prisma.StoreAccountWhereInput[] { + return (Object.keys(STORE_ACCOUNT_METADATA_FILTER_OPTIONS) as StoreAccountMetadataFilterKey[]) + .flatMap((key): Prisma.StoreAccountWhereInput[] => { + const raw = filters[key]; + if (!raw) return []; + const selected = new Set(raw.split(/[,,;;]+/).map((value) => value.trim()).filter(Boolean)); + const choices = STORE_ACCOUNT_METADATA_FILTER_OPTIONS[key].filter((option) => selected.has(option.value)); + const or: Prisma.StoreAccountWhereInput[] = []; + for (const { value } of choices) { + if (value === STORE_ACCOUNT_METADATA_BLANK_FILTER) { + or.push({ [key]: null }); + if (key !== "shippingEnabled") or.push({ [key]: "" }); + } else { + or.push({ [key]: key === "shippingEnabled" ? value === "true" : value }); + } + } + // An explicit empty selection or invalid-only query must never remove the filter. + return [or.length ? { OR: or } : { id: { in: [] } }]; + }); +} diff --git a/furniture-3d-system/src/server/repositories/store-account-metadata.repository.ts b/furniture-3d-system/src/server/repositories/store-account-metadata.repository.ts new file mode 100644 index 00000000..2d43dbbe --- /dev/null +++ b/furniture-3d-system/src/server/repositories/store-account-metadata.repository.ts @@ -0,0 +1,46 @@ +import { prisma } from "@/lib/prisma"; +import { + STORE_ACCOUNT_METADATA_COLUMNS, + formatStoreAccountShipping, + type StoreAccountMetadataRecord, + type planStoreAccountMetadataBackfill, +} from "@/lib/store-account-store-metadata"; + +type Updates = ReturnType["updates"]; + +export const storeAccountMetadataRepository = { + async listAccounts(): Promise { + return prisma.storeAccount.findMany({ + select: { id: true, storeName: true, storeOwnership: true, storeAttribute: true, shippingEnabled: true }, + orderBy: { id: "asc" }, + }); + }, + + async applyUpdates(updates: Updates, sourceFile: string) { + if (!updates.length) return 0; + return prisma.$transaction(async (tx) => { + for (const { before, after } of updates) { + const result = await tx.storeAccount.updateMany({ + where: { id: before.id, storeName: before.storeName, + storeOwnership: before.storeOwnership, storeAttribute: before.storeAttribute, + shippingEnabled: before.shippingEnabled }, + data: after, + }); + if (result.count !== 1) throw new Error(`店铺“${before.storeName}”资料已变化,补数事务已取消`); + } + await tx.storeAccountChangeLog.createMany({ + data: updates.map(({ before, after, sourceRow }) => ({ + storeAccountId: before.id, storeName: before.storeName, + operation: "UPDATE", actorName: `店铺表格补数:${sourceFile} 第${sourceRow}行`, + changes: STORE_ACCOUNT_METADATA_COLUMNS.filter(({ key }) => before[key] !== after[key]).map(({ key }) => ({ + field: key, + previousValue: key === "shippingEnabled" && before[key] != null + ? formatStoreAccountShipping(before[key]) : before[key], + nextValue: key === "shippingEnabled" ? formatStoreAccountShipping(after[key]) : after[key], + })), + })), + }); + return updates.length; + }, { timeout: 120_000 }); + }, +}; diff --git a/furniture-3d-system/src/server/services/__tests__/store-account-list.service.test.ts b/furniture-3d-system/src/server/services/__tests__/store-account-list.service.test.ts index 21244c2e..d4c20d34 100644 --- a/furniture-3d-system/src/server/services/__tests__/store-account-list.service.test.ts +++ b/furniture-3d-system/src/server/services/__tests__/store-account-list.service.test.ts @@ -2,11 +2,7 @@ import { StoreAccountManagementService } from "../store-account-management.servi import { storeAccountShopInfoService } from "../store-account-shop-info.service"; jest.mock("../store-account-shop-info.service", () => ({ - storeAccountShopInfoService: { getShopInfoMap: jest.fn().mockResolvedValue(new Map([ - ["店铺一", { shopState: 6, openTime: "2020-01-02", renewalTime: "2026-11-06" }], - ["店铺二", { shopState: 0, openTime: null, renewalTime: null }], - ["店铺三", { shopState: 3, openTime: null, renewalTime: null }], - ])) }, + storeAccountShopInfoService: { getShopInfoMap: jest.fn() }, })); import type { StoreAccountManagementRepository, @@ -17,6 +13,7 @@ import { STORE_ACCOUNT_EMPTY_PLATFORM_FILTER, type StoreAccountFieldAccess, } from "@/lib/store-account-management"; +import { STORE_ACCOUNT_METADATA_BLANK_FILTER } from "@/lib/store-account-metadata-filters"; const user = { id: "admin-1", @@ -40,12 +37,18 @@ function record(id: string, storeName: string, owner = "负责人"): StoreAccoun } function setup() { + jest.mocked(storeAccountShopInfoService.getShopInfoMap).mockResolvedValue(new Map([ + ["店铺一", { shopState: 6, openTime: "2020-01-02", renewalTime: "2026-11-06", renewalType: null }], + ["店铺二", { shopState: 0, openTime: null, renewalTime: null, renewalType: null }], + ["店铺三", { shopState: 3, openTime: null, renewalTime: null, renewalType: null }], + ])); const allRows = [ record("1", " 店铺一 "), record("2", "店铺二"), record("3", "店铺三", "离职负责人"), record("4", "无匹配店"), ]; + Object.assign(allRows[0], { storeOwnership: "内部", storeAttribute: "真实店铺", shippingEnabled: false }); const repository = { listAll: jest.fn().mockResolvedValue(allRows), listPage: jest.fn().mockResolvedValue({ rows: allRows.slice(0, 2), total: 4 }), @@ -87,6 +90,22 @@ function setup() { describe("store account derived platform listing", () => { afterEach(() => jest.restoreAllMocks()); + it("exposes all metadata choices even when a choice has no matching records", async () => { + const { service } = setup(); + const page = await service.listPage({ user }); + expect(page.filterOptions.storeOwnership).toEqual(["内部", "外部", STORE_ACCOUNT_METADATA_BLANK_FILTER]); + expect(page.filterOptions.storeAttribute).toEqual(["真实店铺", "虚拟店铺", STORE_ACCOUNT_METADATA_BLANK_FILTER]); + expect(page.filterOptions.shippingEnabled).toEqual(["true", "false", STORE_ACCOUNT_METADATA_BLANK_FILTER]); + }); + + it.each(["", "0"])("forwards all metadata conditions to the repository with source state %s", async (shopState) => { + const { service, repository } = setup(); + const metadata = { storeOwnership: "内部", storeAttribute: "虚拟店铺", shippingEnabled: "false" }; + await service.listPage({ user, filters: { ...metadata, shopState } }); + const listing = shopState ? repository.listAll : repository.listPage; + expect(listing).toHaveBeenCalledWith(expect.objectContaining({ filters: expect.objectContaining({ ...metadata, shopState: "" }) })); + }); + it("returns no rows when the platform selection is empty", async () => { const { service } = setup(); const page = await service.listPage({ @@ -140,6 +159,13 @@ describe("store account derived platform listing", () => { expect(page.rows[1]).toMatchObject({ shopState: 0, openTime: null, renewalTime: null }); }); + it("returns saved metadata independently of source state and preserves no-shipping versus unknown", async () => { + const { service } = setup(); + const page = await service.listPage({ user }); + expect(page.rows[0]).toMatchObject({ shopState: 6, storeOwnership: "内部", storeAttribute: "真实店铺", shippingEnabled: false }); + expect(page.rows[1]).toMatchObject({ storeOwnership: null, storeAttribute: null, shippingEnabled: null }); + }); + it("filters source state before pagination and never prefilters stale database state", async () => { const { service, repository } = setup(); const page = await service.listPage({ user, filters: { shopState: "6,3" }, page: 2, pageSize: 1 }); @@ -151,10 +177,30 @@ describe("store account derived platform listing", () => { it("leaves unmatched source states empty instead of falling back to stored normal", async () => { const { service } = setup(); const page = await service.listPage({ user, filters: { platform: "京东,京东供销" } }); - expect(page.filterOptions.shopState).toEqual(["6", "0", "3"]); + expect(page.filterOptions.shopState).toEqual(["0", "1", "2", "3", "4", "5", "6"]); const getMap = jest.spyOn(storeAccountShopInfoService, "getShopInfoMap").mockResolvedValueOnce(new Map()); const emptySource = await service.listPage({ user }); expect(emptySource.rows.every((row) => row.shopState === null)).toBe(true); + expect(emptySource.filterOptions.shopState).toEqual(["0", "1", "2", "3", "4", "5", "6"]); getMap.mockRestore(); }); + + it.each(["1", "2", "4", "5"])("returns zero matches for absent state %s while preserving all state choices", async (shopState) => { + const { service } = setup(); + const page = await service.listPage({ user, filters: { shopState } }); + expect(page.rows).toEqual([]); + expect(page.pageInfo.total).toBe(0); + expect(page.filterOptions.shopState).toEqual(["0", "1", "2", "3", "4", "5", "6"]); + }); + + it.each([1, 2, 4, 5, 8])("returns and filters source state %s without changing its code", async (shopState) => { + const { service } = setup(); + jest.spyOn(storeAccountShopInfoService, "getShopInfoMap").mockResolvedValueOnce(new Map([ + ["店铺一", { shopState, openTime: null, renewalTime: null, renewalType: null }], + ])); + const page = await service.listPage({ user, filters: { shopState: String(shopState) } }); + expect(page.rows).toHaveLength(1); + expect(page.rows[0]).toMatchObject({ id: "1", shopState }); + expect(page.filterOptions.shopState).toContain(String(shopState)); + }); }); diff --git a/furniture-3d-system/src/server/services/store-account-list.service.ts b/furniture-3d-system/src/server/services/store-account-list.service.ts index dac3339c..ac1ecd04 100644 --- a/furniture-3d-system/src/server/services/store-account-list.service.ts +++ b/furniture-3d-system/src/server/services/store-account-list.service.ts @@ -1,5 +1,6 @@ import { STORE_ACCOUNT_AUTHORIZATION_FILTER_OPTIONS, + STORE_ACCOUNT_SHOP_STATE_FILTER_OPTIONS, resolveStoreAccountOwnerEmployment, type StoreAccountAuthorizationStatus, type StoreAccountFieldAccess, @@ -15,6 +16,7 @@ import type { storeAccountNotificationRepository } from "@/server/repositories/s import type { StoreAccountPlatformReader } from "./store-account-platform.service"; import type { StoreAccountAuthorizationReader } from "./store-account-authorization.service"; import { storeAccountShopInfoService, type StoreAccountShopInfoReader } from "./store-account-shop-info.service"; +import { STORE_ACCOUNT_METADATA_FILTER_OPTIONS } from "@/lib/store-account-metadata-filters"; type ListDependencies = { repository: StoreAccountManagementRepository; @@ -135,6 +137,9 @@ export async function listStoreAccountPage( row.shopState = source?.shopState ?? null; row.openTime = source?.openTime ?? null; row.renewalTime = source?.renewalTime ?? null; + row.storeOwnership = record.storeOwnership ?? null; + row.storeAttribute = record.storeAttribute ?? null; + row.shippingEnabled = record.shippingEnabled ?? null; if (ownerEmploymentForRows.departedNames.has(record.operationOwner.trim())) { row.operationOwnerDeparted = true; } @@ -155,10 +160,16 @@ export async function listStoreAccountPage( storeNames, filterOptions: { ...filterOptions, - shopState: [...new Set(storeNames.flatMap((name) => { - const state = shopInfoByName.get(name.trim())?.shopState; - return state == null ? [] : [String(state)]; - }))], + storeOwnership: STORE_ACCOUNT_METADATA_FILTER_OPTIONS.storeOwnership.map((option) => option.value), + storeAttribute: STORE_ACCOUNT_METADATA_FILTER_OPTIONS.storeAttribute.map((option) => option.value), + shippingEnabled: STORE_ACCOUNT_METADATA_FILTER_OPTIONS.shippingEnabled.map((option) => option.value), + shopState: [...new Set([ + ...STORE_ACCOUNT_SHOP_STATE_FILTER_OPTIONS.map((option) => option.value), + ...storeNames.flatMap((name) => { + const state = shopInfoByName.get(name.trim())?.shopState; + return state == null ? [] : [String(state)]; + }), + ])], platform: fieldAccess.profitCenter === "HIDDEN" ? [] : platforms, authorizationStatus: STORE_ACCOUNT_AUTHORIZATION_FILTER_OPTIONS.map( (option) => option.value, diff --git a/furniture-3d-system/src/server/services/store-account-metadata-backfill.service.ts b/furniture-3d-system/src/server/services/store-account-metadata-backfill.service.ts new file mode 100644 index 00000000..1da33989 --- /dev/null +++ b/furniture-3d-system/src/server/services/store-account-metadata-backfill.service.ts @@ -0,0 +1,18 @@ +import ExcelJS from "exceljs"; +import { planStoreAccountMetadataBackfill, parseStoreAccountMetadataRows } from "@/lib/store-account-store-metadata"; +import { storeAccountMetadataRepository } from "@/server/repositories/store-account-metadata.repository"; + +export async function previewStoreAccountMetadataBackfill(file: string) { + const workbook = new ExcelJS.Workbook(); + await workbook.xlsx.readFile(file); + if (workbook.worksheets.length !== 1) throw new Error("补数文件必须且只能包含一个工作表"); + const sheet = workbook.worksheets[0]; + const cells: string[][] = []; + for (let number = 1; number <= sheet.rowCount; number++) { + const row = sheet.getRow(number); + cells.push(Array.from({ length: sheet.columnCount }, (_, column) => row.getCell(column + 1).text)); + } + const source = parseStoreAccountMetadataRows(cells); + const records = await storeAccountMetadataRepository.listAccounts(); + return planStoreAccountMetadataBackfill(source, records); +}