From 74060d9e65d4417e5f038b6156e1fc9c0afe0f53 Mon Sep 17 00:00:00 2001 From: WuYongJie Date: Wed, 25 Nov 2026 11:26:20 +0800 Subject: [PATCH 1/2] feat(store-account): sync shop directory and persist exclusions --- .../import-store-account-exclusions.ts | 66 ++++++++ .../scripts/sync-store-account-directory.ts | 24 +++ .../store-account-management/[id]/route.ts | 2 + .../exclusions/route.ts | 13 ++ .../store-account-management/route.ts | 2 + .../StoreAccountBatchDeleteDialog.tsx | 2 +- .../StoreAccountEditorDialog.tsx | 16 ++ .../StoreAccountExclusionButton.tsx | 92 ++++++++++++ .../StoreAccountManagementView.tsx | 91 ++++++++--- .../StoreAccountSourceBadges.tsx | 21 +++ .../storeAccountTableColumns.test.ts | 12 ++ .../storeAccountTableColumns.ts | 27 +++- .../src/lib/store-account-exclusion.ts | 9 ++ .../src/lib/store-account-management.ts | 5 +- .../src/lib/store-account-metadata-filters.ts | 9 +- .../src/lib/store-account-store-metadata.ts | 10 ++ .../store-account-org-structure/client.ts | 9 +- ...tore-account-management.repository.test.ts | 142 ++++++++++++------ ...store-account-directory-sync.repository.ts | 98 ++++++++++++ .../store-account-directory.repository.ts | 78 ++++++++++ .../store-account-exclusion.repository.ts | 88 +++++++++++ .../store-account-management.repository.ts | 81 +++++++--- ...ore-account-directory-sync.service.test.ts | 88 +++++++++++ .../store-account-list.service.test.ts | 54 +++++-- .../store-account-directory-sync.service.ts | 90 +++++++++++ .../store-account-directory.service.ts | 58 +++++++ .../services/store-account-list.service.ts | 71 ++++++--- ...store-account-management-export.service.ts | 7 +- .../store-account-management.service.ts | 38 ++++- .../store-account-owner-options.service.ts | 2 +- .../store-account-platform.service.ts | 57 +++---- 31 files changed, 1179 insertions(+), 183 deletions(-) create mode 100644 furniture-3d-system/scripts/import-store-account-exclusions.ts create mode 100644 furniture-3d-system/scripts/sync-store-account-directory.ts create mode 100644 furniture-3d-system/src/app/api/supply-chain/store-account-management/exclusions/route.ts create mode 100644 furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountExclusionButton.tsx create mode 100644 furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountSourceBadges.tsx create mode 100644 furniture-3d-system/src/lib/store-account-exclusion.ts create mode 100644 furniture-3d-system/src/server/repositories/store-account-directory-sync.repository.ts create mode 100644 furniture-3d-system/src/server/repositories/store-account-directory.repository.ts create mode 100644 furniture-3d-system/src/server/repositories/store-account-exclusion.repository.ts create mode 100644 furniture-3d-system/src/server/services/__tests__/store-account-directory-sync.service.test.ts create mode 100644 furniture-3d-system/src/server/services/store-account-directory-sync.service.ts create mode 100644 furniture-3d-system/src/server/services/store-account-directory.service.ts diff --git a/furniture-3d-system/scripts/import-store-account-exclusions.ts b/furniture-3d-system/scripts/import-store-account-exclusions.ts new file mode 100644 index 00000000..745a3176 --- /dev/null +++ b/furniture-3d-system/scripts/import-store-account-exclusions.ts @@ -0,0 +1,66 @@ +import { createHash } from 'node:crypto' +import { loadEnvConfig } from '@next/env' +import * as XLSX from 'xlsx' + +function readWorkbookNames(filePath: string) { + const workbook = XLSX.readFile(filePath) + const sheet = workbook.Sheets[workbook.SheetNames[0]] + if (!sheet) throw new Error('附件没有工作表') + const [headers, ...rows] = XLSX.utils.sheet_to_json(sheet, { header: 1, blankrows: false }) + const column = headers?.findIndex((header) => String(header).trim() === '店铺名称') ?? -1 + if (column < 0) throw new Error('附件缺少「店铺名称」列') + const names = [...new Set(rows.map((row) => String(row[column] ?? '').trim()).filter(Boolean))].sort() + if (!names.length) throw new Error('附件没有店铺名称') + return names +} + +async function main() { + const [workbook, applyFlag, ...rest] = process.argv.slice(2) + if (!workbook || rest.length || (applyFlag && !/^--apply=[a-f0-9]{64}$/.test(applyFlag))) { + throw new Error('用法:tsx scripts/import-store-account-exclusions.ts <附件路径> [--apply=预览确认码]') + } + loadEnvConfig(process.cwd(), true) + const databaseUrl = new URL(process.env.DATABASE_URL ?? '') + if (!['localhost', '127.0.0.1', '[::1]'].includes(databaseUrl.hostname) + || /prod/i.test(databaseUrl.pathname) || process.env.NODE_ENV === 'production') { + throw new Error('本入口只处理本地预览数据库') + } + const workbookNames = readWorkbookNames(workbook) + const { prisma } = await import('../src/lib/prisma') + const { addStoreAccountExclusions, findLastManualStoreDeletions, readExcludedStoreNames } = + await import('../src/server/repositories/store-account-exclusion.repository') + try { + const result = await prisma.$transaction(async (tx) => { + const logEntries = await findLastManualStoreDeletions(tx) + const existing = await readExcludedStoreNames(tx) + const history = new Map(logEntries.map(entry => [entry.storeName, entry])) + const names = [...new Set([...workbookNames, ...history.keys()])].sort() + const previous = new Set(existing) + const added = names.filter(name => !previous.has(name)) + const workbookSet = new Set(workbookNames) + const [affected, currentAccounts] = await Promise.all([ + tx.storeAccount.findMany({ where: { storeName: { in: added } }, select: { id: true, storeName: true }, orderBy: { id: 'asc' } }), + tx.storeAccount.count(), + ]) + const confirmation = createHash('sha256').update(JSON.stringify({ + database: databaseUrl.host + databaseUrl.pathname, names, existing, affected, currentAccounts, + })).digest('hex') + if (applyFlag && applyFlag.slice('--apply='.length) !== confirmation) throw new Error('名单或账号已变化,请重新预览') + const entries = added.map(storeName => workbookSet.has(storeName) + ? { storeName, reason: 'workbook' as const } + : history.get(storeName)!) + const inserted = applyFlag ? await addStoreAccountExclusions(tx, entries) : 0 + return { workbookStores: workbookNames.length, manualDeletedStores: history.size, + currentAccounts, matchedAccountRows: affected.length, exclusionStores: existing.length + added.length, + insertCount: inserted, confirmation } + }, { isolationLevel: 'Serializable' }) + process.stdout.write(JSON.stringify(result, null, 2) + '\n') + } finally { + await prisma.$disconnect() + } +} + +main().catch((error: unknown) => { + console.error('导入排除库失败:' + (error instanceof Error ? error.message : String(error))) + process.exitCode = 1 +}) diff --git a/furniture-3d-system/scripts/sync-store-account-directory.ts b/furniture-3d-system/scripts/sync-store-account-directory.ts new file mode 100644 index 00000000..0a28b1f1 --- /dev/null +++ b/furniture-3d-system/scripts/sync-store-account-directory.ts @@ -0,0 +1,24 @@ +import { loadEnvConfig } from "@next/env"; + +async function main() { + const args = process.argv.slice(2); + const hierarchyOnly = args.includes("--hierarchy-only"); + const applyArgs = args.filter((arg) => /^--apply=[a-f0-9]{64}$/.test(arg)); + if (applyArgs.length > 1 || args.length !== Number(hierarchyOnly) + applyArgs.length) { + throw new Error("用法:tsx scripts/sync-store-account-directory.ts [--hierarchy-only] [--apply=预览确认码]"); + } + loadEnvConfig(process.cwd(), process.env.NODE_ENV !== "production"); + const { syncStoreAccountDirectory } = await import("../src/server/services/store-account-directory-sync.service"); + const { prisma } = await import("../src/lib/prisma"); + try { + const result = await syncStoreAccountDirectory(applyArgs[0]?.slice("--apply=".length), hierarchyOnly); + process.stdout.write(JSON.stringify(result, null, 2) + "\n"); + } finally { + await prisma.$disconnect(); + } +} + +main().catch((error: unknown) => { + console.error("店铺名单同步失败:" + (error instanceof Error ? error.message : String(error))); + process.exitCode = 1; +}); diff --git a/furniture-3d-system/src/app/api/supply-chain/store-account-management/[id]/route.ts b/furniture-3d-system/src/app/api/supply-chain/store-account-management/[id]/route.ts index 1befffde..9e49c5fe 100644 --- a/furniture-3d-system/src/app/api/supply-chain/store-account-management/[id]/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/store-account-management/[id]/route.ts @@ -3,6 +3,7 @@ import { z } from 'zod' import { ErrorCode } from '@/server/core/errors' import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' import { storeAccountManagementService } from '@/server/services/store-account-management.service' +import { STORE_ACCOUNT_ATTRIBUTES } from '@/lib/store-account-store-metadata' const storeProfileSchema = z.object({ merchantNumber: z.string().max(500).optional(), @@ -26,6 +27,7 @@ const updateSchema = z.object({ verificationContact: z.string().trim().max(240).optional(), jstOrderService: z.string().trim().max(240).optional(), accountGroupName: z.string().trim().max(240).optional(), + storeAttribute: z.enum(STORE_ACCOUNT_ATTRIBUTES).nullable().optional(), storeProfile: storeProfileSchema.optional(), }).strict() diff --git a/furniture-3d-system/src/app/api/supply-chain/store-account-management/exclusions/route.ts b/furniture-3d-system/src/app/api/supply-chain/store-account-management/exclusions/route.ts new file mode 100644 index 00000000..104aadd7 --- /dev/null +++ b/furniture-3d-system/src/app/api/supply-chain/store-account-management/exclusions/route.ts @@ -0,0 +1,13 @@ +import type { NextRequest } from 'next/server' +import { ErrorCode } from '@/server/core/errors' +import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' +import { storeAccountManagementService } from '@/server/services/store-account-management.service' + +export async function GET(request: NextRequest) { + return handleRequest(request, async (ctx) => { + const result = await storeAccountManagementService.listExclusions(ctx.user) + return result + ? jsonSuccess(result, 200, ctx.requestId) + : jsonError(ErrorCode.AUTH_PERMISSION_DENIED, '当前账号没有查看排除库的权限', 403, ctx.requestId) + }, { requireAuth: true }) +} diff --git a/furniture-3d-system/src/app/api/supply-chain/store-account-management/route.ts b/furniture-3d-system/src/app/api/supply-chain/store-account-management/route.ts index 0b4f9870..4e15e2b9 100644 --- a/furniture-3d-system/src/app/api/supply-chain/store-account-management/route.ts +++ b/furniture-3d-system/src/app/api/supply-chain/store-account-management/route.ts @@ -3,6 +3,7 @@ import { z } from 'zod' import { ErrorCode } from '@/server/core/errors' import { handleRequest, jsonError, jsonSuccess } from '@/server/core/response' import { EMPTY_STORE_ACCOUNT_FILTERS, STORE_ACCOUNT_FILTER_KEYS } from '@/lib/store-account-management' +import { STORE_ACCOUNT_ATTRIBUTES } from '@/lib/store-account-store-metadata' import { storeAccountManagementService } from '@/server/services/store-account-management.service' const storeProfileSchema = z.object({ @@ -27,6 +28,7 @@ const createSchema = z.object({ verificationContact: z.string().trim().max(240).optional(), jstOrderService: z.string().trim().max(240).optional(), accountGroupName: z.string().trim().max(240).optional(), + storeAttribute: z.enum(STORE_ACCOUNT_ATTRIBUTES).nullable().optional(), storeProfile: storeProfileSchema.optional(), }).strict() diff --git a/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountBatchDeleteDialog.tsx b/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountBatchDeleteDialog.tsx index 14d4c610..2edac123 100644 --- a/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountBatchDeleteDialog.tsx +++ b/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountBatchDeleteDialog.tsx @@ -80,7 +80,7 @@ export function StoreAccountBatchDeleteDialog({ 另有 {offPageCount} 条所选账号不在当前页,将一并删除。

)} -

删除后不可恢复,删除操作会记入账号日志。

+

删除后不可恢复。删掉一家店铺的最后一条账号后,该店铺会进入排除库。

+ setOpen(false)} title="排除库" size="large" variant="compact"> + {view.status === 'loading' &&

正在读取排除库…

} + {view.status === 'error' && ( +
+ {view.message} + +
+ )} + {view.status === 'ready' && ( +
+
+ setSearch(event.target.value)} + /> + 共 {visible.length} 家 +
+
+ + + + + + + + + + {visible.map((entry) => ( + + + + + + ))} + {visible.length === 0 && ( + + )} + +
店铺名称排除原因日期
{entry.storeName}{entry.reason === 'workbook' ? '名单导入' : '人工删除'}{dateFormat.format(new Date(entry.excludedAt))}
{search.trim() ? '没有匹配的店铺' : '暂无排除店铺'}
+
+
+ )} +
+ + ) +} 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 8fa2abc2..36464fb7 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_BLANK_FILTER_OPTION } from "@/lib/store-account-metadata-filters"; import { STORE_ACCOUNT_METADATA_COLUMNS, formatStoreAccountShipping } from "@/lib/store-account-store-metadata"; import { @@ -55,6 +56,8 @@ import { StoreAccountAuthorizationNoticeDialog } from "./StoreAccountAuthorizati import { StoreAccountImportProgress } from "./StoreAccountImportProgress"; import { StoreAccountLogDialog } from "./StoreAccountLogDialog"; import { StoreAccountExportMenu } from "./StoreAccountExportMenu"; +import { StoreAccountExclusionButton } from "./StoreAccountExclusionButton"; +import { StoreAccountSourceBadges } from "./StoreAccountSourceBadges"; import { StoreAccountEditorDialog, type StoreAccountDraft, @@ -63,6 +66,7 @@ import { import { useStoreAccountImport } from "./useStoreAccountImport"; import { STORE_ACCOUNT_HEADER_FILTER_KEYS, + STORE_ACCOUNT_SOURCE_COLUMN, getStoreAccountHeaderFilterOptions, getStoreAccountHeaderFilterValue, getStoreAccountHeaderFilterSelection, @@ -106,6 +110,7 @@ function formatOwnerCell(value: string, departed?: boolean) { function rowToDraft(row: StoreAccountRow): Draft { return { id: row.id, + originalStoreAttribute: row.storeAttributeOverride, storeName: row.storeName, operationOwner: row.operationOwner, operationDepartmentHead: row.operationDepartmentHead, @@ -154,7 +159,9 @@ export function StoreAccountManagementView({ const renderColumns = useMemo( () => visibleFields.flatMap((field): StoreAccountTableColumn[] => - field.key === "profitCenter" + field.key === "storeName" + ? [STORE_ACCOUNT_SOURCE_COLUMN, field] + : field.key === "profitCenter" ? [field, STORE_ACCOUNT_PLATFORM_COLUMN] : field.key === "accountType" ? [ @@ -186,6 +193,7 @@ export function StoreAccountManagementView({ () => data.rows.filter((row) => selectedIds.includes(row.id)), [data.rows, selectedIds], ); + const selectedRowToEdit = selectedIds.length === 1 ? selectedRowsOnPage[0] : undefined; const offPageSelectedCount = selectedIds.length - selectedRowsOnPage.length; useEffect(() => { @@ -285,6 +293,7 @@ export function StoreAccountManagementView({ (key !== "password" || value !== ""), ), ); + if (draft.storeAttribute !== undefined) body.storeAttribute = draft.storeAttribute; if ( Object.keys(profileValues).length > 0 && getStoreAccountProfilePlatformForStoreName(String(draft.storeName ?? "")) @@ -386,6 +395,7 @@ export function StoreAccountManagementView({
共 {data.pageInfo.total} 条 + {data.fieldAccess.storeName !== "HIDDEN" && } {canExport && } {canEdit && ( <> @@ -482,6 +492,7 @@ export function StoreAccountManagementView({ + )} - - +
+ + {canEdit && ( + + )} + +
@@ -690,7 +716,9 @@ export function StoreAccountManagementView({ )} {renderColumns.map((field) => ( ))}
- {field.key === "accountType" ? ( + {field.key === "sources" ? ( + + ) : field.key === "accountType" ? ( formatStoreAccountType(row.accountType) ) : field.key === "shopState" ? ( formatStoreAccountShopState(row.shopState) @@ -741,14 +769,6 @@ export function StoreAccountManagementView({ - {canEdit && ( - - )} {getStoreAccountProfilePlatformForStoreName( row.storeName, ) && ( @@ -1133,6 +1153,33 @@ const styles = ` /* 标题区已删除:工具条只剩右侧操作组,仍保持靠右 */ .store-account-toolbar { justify-content: flex-end; } .store-account-filters{position:relative;z-index:40;overflow:visible} +.store-account-filter-actions { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; +} +.store-account-filter-actions > button { + height: var(--wb-control-height); + border-radius: var(--wb-control-radius); + border-color: var(--wb-border); + font-size: 14px; +} +.store-account-filter-actions > .primary { + flex: 1; + min-width: 0; + padding: 0 6px; + white-space: nowrap; + background: var(--wb-accent) !important; + border-color: var(--wb-accent) !important; +} +.store-account-filter-actions > .primary:disabled { + opacity: .5; + cursor: not-allowed; +} +.store-account-filter-actions > .icon-button { + flex: none; +} .store-name-picker{position:relative;width:180px;flex:0 0 180px} .owner-status-picker{position:relative;width:130px;flex:0 0 130px} .owner-status-trigger{display:flex;width:100%;height:34px;align-items:center;justify-content:space-between;padding:0 9px;border:1px solid #d4d4d8;border-radius:5px;background:#fff;color:#71717a;font-size:12px;cursor:pointer} diff --git a/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountSourceBadges.tsx b/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountSourceBadges.tsx new file mode 100644 index 00000000..f8cea861 --- /dev/null +++ b/furniture-3d-system/src/app/supply-chain/database/store-account-management/StoreAccountSourceBadges.tsx @@ -0,0 +1,21 @@ +import { Badge } from "@/components/ui/Badge"; +import type { StoreAccountSource } from "@/lib/store-account-management"; + +const labels: Record = { + openingFlow: "开店流程", + jst: "聚水潭", +}; + +export function StoreAccountSourceBadges({ sources }: { sources?: readonly StoreAccountSource[] }) { + if (!sources?.length) return —; + + return ( + + {sources.map((source) => ( + + {labels[source]} + + ))} + + ); +} 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 index 74c705fe..178976a8 100644 --- 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 @@ -47,3 +47,15 @@ describe("store account metadata header filters", () => { expect(getStoreAccountHeaderFilterValue("shippingEnabled", null, options)).toBe(""); }); }); + +it("keeps blank status separate from normal and sends the blank selection to the listing query", () => { + const options = getStoreAccountHeaderFilterOptions("shopState", { shopState: ["0"] } as StoreAccountPage["filterOptions"]); + expect(options).toEqual([ + { value: STORE_ACCOUNT_METADATA_BLANK_FILTER, label: "未填写" }, + { value: "0", label: "正常" }, + ]); + const selected = { mode: "include" as const, values: ["未填写"] }; + const query = getStoreAccountHeaderFilterValue("shopState", selected, options); + expect(query).toBe(STORE_ACCOUNT_METADATA_BLANK_FILTER); + expect(getStoreAccountHeaderFilterSelection("shopState", query, options)).toEqual(selected); +}); 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 4b04b72f..342ff942 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 @@ -2,8 +2,10 @@ 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_BLANK_FILTER_OPTION, STORE_ACCOUNT_METADATA_FILTER_OPTIONS, STORE_ACCOUNT_METADATA_NONE_FILTER, + STORE_ACCOUNT_STORE_NAME_FILLED_FILTER, isStoreAccountMetadataFilterKey, type StoreAccountMetadataFilterKey, } from "@/lib/store-account-metadata-filters"; @@ -11,7 +13,6 @@ 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, @@ -19,7 +20,10 @@ import { type StoreAccountPage, } from "@/lib/store-account-management"; +export const STORE_ACCOUNT_SOURCE_COLUMN = { key: "sources", label: "数据来源" } as const; + export type StoreAccountTableColumn = + | typeof STORE_ACCOUNT_SOURCE_COLUMN | (typeof STORE_ACCOUNT_FIELDS)[number] | typeof STORE_ACCOUNT_SHOP_STATE_COLUMN | typeof STORE_ACCOUNT_AUTHORIZATION_COLUMN @@ -110,12 +114,15 @@ export function getStoreAccountHeaderFilterOptions( if (isStoreAccountMetadataFilterKey(key)) { return [...STORE_ACCOUNT_METADATA_FILTER_OPTIONS[key]]; } - if (key === "authorizationStatus") return [...STORE_ACCOUNT_AUTHORIZATION_FILTER_OPTIONS]; - return filterOptions[key].map((value) => ({ + if (key === "authorizationStatus") { + return [STORE_ACCOUNT_BLANK_FILTER_OPTION, ...STORE_ACCOUNT_AUTHORIZATION_FILTER_OPTIONS]; + } + const options = filterOptions[key].map((value) => ({ value, label: key === "shopState" ? formatStoreAccountShopState(Number(value)) : key === "accountType" ? formatStoreAccountType(value) : value, })); + return [STORE_ACCOUNT_BLANK_FILTER_OPTION, ...options]; } export function getStoreAccountHeaderFilterValue( @@ -123,11 +130,12 @@ export function getStoreAccountHeaderFilterValue( selection: ColumnHeaderFilterSelection | null, options: readonly StoreAccountHeaderFilterOption[], ) { + if ( + key === "storeName" && selection?.mode === "exclude" && + selection.values.length === 1 && selection.values[0] === STORE_ACCOUNT_BLANK_FILTER_OPTION.label + ) return STORE_ACCOUNT_STORE_NAME_FILLED_FILTER; 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; - } + if (selection && !value) return STORE_ACCOUNT_METADATA_NONE_FILTER; return value; } @@ -136,6 +144,9 @@ export function getStoreAccountHeaderFilterSelection( value: string, options: readonly StoreAccountHeaderFilterOption[], ) { - if (!value && (isStoreAccountMetadataFilterKey(key) || key === "platform")) return null; + if (!value) return null; + if (key === "storeName" && value === STORE_ACCOUNT_STORE_NAME_FILLED_FILTER) { + return { mode: "exclude" as const, values: [STORE_ACCOUNT_BLANK_FILTER_OPTION.label] }; + } return toStoreAccountHeaderFilterSelection(value, options); } diff --git a/furniture-3d-system/src/lib/store-account-exclusion.ts b/furniture-3d-system/src/lib/store-account-exclusion.ts new file mode 100644 index 00000000..da15aef3 --- /dev/null +++ b/furniture-3d-system/src/lib/store-account-exclusion.ts @@ -0,0 +1,9 @@ +export const STORE_ACCOUNT_EXCLUSION_PREFIX = 'store-account:exclusion:' + +export type StoreAccountExclusionReason = 'workbook' | 'manual-delete' + +export type StoreAccountExclusion = { + storeName: string + reason: StoreAccountExclusionReason + excludedAt: string +} diff --git a/furniture-3d-system/src/lib/store-account-management.ts b/furniture-3d-system/src/lib/store-account-management.ts index 00a3d42d..5ee5c35d 100644 --- a/furniture-3d-system/src/lib/store-account-management.ts +++ b/furniture-3d-system/src/lib/store-account-management.ts @@ -217,9 +217,12 @@ const STORE_ACCOUNT_LOG_OPERATION_LABELS: Record = { PROFILE_UPDATE: "修改店铺资料", }; +export type StoreAccountSource = "openingFlow" | "jst"; + export type StoreAccountRow = { id: string; storeName: string; + sources?: readonly StoreAccountSource[]; operationOwner: string; /** 店铺运营负责人已离职(内部账号存在但状态=离职)时为 true,列表显示为 名字(已离职) */ operationOwnerDeparted?: boolean; @@ -247,9 +250,9 @@ export type StoreAccountRow = { /** 源表日期;列表始终返回,非列表旧接口可省略。 */ openTime?: string | null; renewalTime?: string | null; - /** 表格补充的只读店铺资料;未匹配时为空。 */ storeOwnership?: string | null; storeAttribute?: string | null; + storeAttributeOverride?: string | null; shippingEnabled?: boolean | null; authorizationStatus: StoreAccountAuthorizationStatus | null; createdAt: string; diff --git a/furniture-3d-system/src/lib/store-account-metadata-filters.ts b/furniture-3d-system/src/lib/store-account-metadata-filters.ts index b85d84d0..67be40f9 100644 --- a/furniture-3d-system/src/lib/store-account-metadata-filters.ts +++ b/furniture-3d-system/src/lib/store-account-metadata-filters.ts @@ -1,23 +1,24 @@ export const STORE_ACCOUNT_METADATA_BLANK_FILTER = "__UNFILLED__"; export const STORE_ACCOUNT_METADATA_NONE_FILTER = "__NONE_SELECTED__"; +export const STORE_ACCOUNT_STORE_NAME_FILLED_FILTER = "__STORE_NAME_FILLED__"; -const blankOption = { value: STORE_ACCOUNT_METADATA_BLANK_FILTER, label: "未填写" }; +export const STORE_ACCOUNT_BLANK_FILTER_OPTION = { value: STORE_ACCOUNT_METADATA_BLANK_FILTER, label: "未填写" }; export const STORE_ACCOUNT_METADATA_FILTER_OPTIONS = { storeOwnership: [ { value: "内部", label: "内部" }, { value: "外部", label: "外部" }, - blankOption, + STORE_ACCOUNT_BLANK_FILTER_OPTION, ], storeAttribute: [ { value: "真实店铺", label: "真实店铺" }, { value: "虚拟店铺", label: "虚拟店铺" }, - blankOption, + STORE_ACCOUNT_BLANK_FILTER_OPTION, ], shippingEnabled: [ { value: "true", label: "是" }, { value: "false", label: "否" }, - blankOption, + STORE_ACCOUNT_BLANK_FILTER_OPTION, ], } as const; diff --git a/furniture-3d-system/src/lib/store-account-store-metadata.ts b/furniture-3d-system/src/lib/store-account-store-metadata.ts index 5d88e5b4..a28426b5 100644 --- a/furniture-3d-system/src/lib/store-account-store-metadata.ts +++ b/furniture-3d-system/src/lib/store-account-store-metadata.ts @@ -4,6 +4,16 @@ export const STORE_ACCOUNT_METADATA_COLUMNS = [ { key: "shippingEnabled", label: "是否发货" }, ] as const; +export const STORE_ACCOUNT_ATTRIBUTES = ["真实店铺", "虚拟店铺"] as const; +export type StoreAccountAttribute = (typeof STORE_ACCOUNT_ATTRIBUTES)[number]; + +export function resolveStoreAccountAttribute( + manual: string | null | undefined, + virtual: boolean | undefined, +) { + return manual || (virtual === undefined ? null : STORE_ACCOUNT_ATTRIBUTES[virtual ? 1 : 0]); +} + export type StoreAccountMetadata = { storeOwnership: string | null; storeAttribute: string | null; diff --git a/furniture-3d-system/src/server/integrations/store-account-org-structure/client.ts b/furniture-3d-system/src/server/integrations/store-account-org-structure/client.ts index 43899fe4..b36c54b9 100644 --- a/furniture-3d-system/src/server/integrations/store-account-org-structure/client.ts +++ b/furniture-3d-system/src/server/integrations/store-account-org-structure/client.ts @@ -3,6 +3,7 @@ const endpoint = "https://pddg.jiansuntuzhi.cn/api/external/org-structure/"; export type StoreAccountOrgOwner = { departmentOwner: string; generalOwner: string; + profitCenter?: string; }; function readName(value: unknown) { @@ -34,9 +35,13 @@ export async function fetchStoreAccountOrgOwners(): Promise ({ prisma: { + $transaction: jest.fn(), + systemConfig: { findMany: jest.fn(), createMany: jest.fn() }, + storeAccountChangeLog: { createMany: jest.fn() }, storeAccount: { findMany: jest.fn(), + deleteMany: jest.fn(), count: jest.fn(), }, }, @@ -9,13 +13,51 @@ jest.mock('@/lib/prisma', () => ({ import { prisma } from '@/lib/prisma' import { EMPTY_STORE_ACCOUNT_FILTERS } from '@/lib/store-account-management' +import { STORE_ACCOUNT_EXCLUSION_PREFIX } from '@/lib/store-account-exclusion' 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' +import { buildStoreAccountCreatedAtFilter, StoreAccountManagementRepository } from '../store-account-management.repository' const mockPrisma = prisma as unknown as { - storeAccount: { findMany: jest.Mock; count: jest.Mock } + $transaction: jest.Mock + systemConfig: { findMany: jest.Mock; createMany: jest.Mock } + storeAccountChangeLog: { createMany: jest.Mock } + storeAccount: { findMany: jest.Mock; count: jest.Mock; deleteMany: jest.Mock } } +beforeEach(() => mockPrisma.systemConfig.findMany.mockResolvedValue([])) + +it('filters excluded names before scoring the total or returning an explicitly selected export', async () => { + mockPrisma.systemConfig.findMany.mockResolvedValue([{ key: STORE_ACCOUNT_EXCLUSION_PREFIX + '已排除店铺' }]) + mockPrisma.storeAccount.findMany.mockResolvedValue([]) + mockPrisma.storeAccount.count.mockResolvedValue(0) + const repository = new StoreAccountManagementRepository() + const filter = { storeName: { notIn: ['已排除店铺'] } } + + await repository.listPage({ skip: 0, take: 50, filters: { ...EMPTY_STORE_ACCOUNT_FILTERS } }) + expect(mockPrisma.storeAccount.count).toHaveBeenLastCalledWith({ where: { AND: [filter] } }) + await repository.listForExport(['selected-id']) + expect(mockPrisma.storeAccount.findMany).toHaveBeenLastCalledWith(expect.objectContaining({ + where: { id: { in: ['selected-id'] }, ...filter }, + })) +}) + +it('stores the exclusion for a shop with no remaining account in the deletion transaction', async () => { + mockPrisma.$transaction.mockImplementation(callback => callback(mockPrisma)) + mockPrisma.storeAccount.deleteMany.mockResolvedValue({ count: 2 }) + mockPrisma.storeAccount.findMany.mockResolvedValue([{ storeName: '仍有主账号' }]) + mockPrisma.systemConfig.createMany.mockResolvedValue({ count: 1 }) + const logs = ['没有剩余账号', '仍有主账号'].map((storeName, i) => ({ + storeName, storeAccountId: String(i), operation: 'BATCH_DELETE', + actorId: 'user', actorName: '管理员', changes: [], + })) + await new StoreAccountManagementRepository().deleteManyWithLogs(['0', '1'], logs) + expect(mockPrisma.systemConfig.createMany).toHaveBeenCalledWith(expect.objectContaining({ + data: [expect.objectContaining({ + key: STORE_ACCOUNT_EXCLUSION_PREFIX + '没有剩余账号', value: { reason: 'manual-delete' }, + })], + })) +}) + describe('StoreAccountManagementRepository list ordering', () => { beforeEach(() => jest.clearAllMocks()) @@ -30,12 +72,12 @@ describe('StoreAccountManagementRepository list ordering', () => { ...EMPTY_STORE_ACCOUNT_FILTERS, search: '', storeName: '', - accountType: '', - operationOwner: '', - accountGroupName: '', - createdAtGranularity: '', - createdAtValue: '', - }, + accountType: '', + operationOwner: '', + accountGroupName: '', + createdAtGranularity: '', + createdAtValue: '', + }, })).resolves.toEqual({ rows: [], total: 0 }) expect(mockPrisma.storeAccount.findMany).toHaveBeenCalledWith(expect.objectContaining({ @@ -44,49 +86,49 @@ describe('StoreAccountManagementRepository list ordering', () => { orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], })) }) - - it.each([ - ['year', '2026', '2025-12-31T16:00:00.000Z', '2026-12-31T16:00:00.000Z'], - ['month', '2026-08', '2026-07-31T16:00:00.000Z', '2026-08-31T16:00:00.000Z'], - ['day', '2026-08-31', '2026-08-30T16:00:00.000Z', '2026-08-31T16:00:00.000Z'], - ])('builds the %s Shanghai business date range', (granularity, value, start, end) => { - expect(buildStoreAccountCreatedAtFilter({ - createdAtGranularity: granularity, - createdAtValue: value, - })).toEqual({ gte: new Date(start), lt: new Date(end) }) - }) - - it('adds the selected creation date range to the database query', async () => { - mockPrisma.storeAccount.findMany.mockResolvedValue([]) - mockPrisma.storeAccount.count.mockResolvedValue(0) - - await new StoreAccountManagementRepository().listPage({ - skip: 0, - take: 50, - filters: { + + it.each([ + ['year', '2026', '2025-12-31T16:00:00.000Z', '2026-12-31T16:00:00.000Z'], + ['month', '2026-08', '2026-07-31T16:00:00.000Z', '2026-08-31T16:00:00.000Z'], + ['day', '2026-08-31', '2026-08-30T16:00:00.000Z', '2026-08-31T16:00:00.000Z'], + ])('builds the %s Shanghai business date range', (granularity, value, start, end) => { + expect(buildStoreAccountCreatedAtFilter({ + createdAtGranularity: granularity, + createdAtValue: value, + })).toEqual({ gte: new Date(start), lt: new Date(end) }) + }) + + it('adds the selected creation date range to the database query', async () => { + mockPrisma.storeAccount.findMany.mockResolvedValue([]) + mockPrisma.storeAccount.count.mockResolvedValue(0) + + await new StoreAccountManagementRepository().listPage({ + skip: 0, + take: 50, + filters: { ...EMPTY_STORE_ACCOUNT_FILTERS, - search: '', - storeName: '', - accountType: '', - operationOwner: '', - accountGroupName: '', - createdAtGranularity: 'day', - createdAtValue: '2026-08-31', - }, - }) - - expect(mockPrisma.storeAccount.findMany).toHaveBeenCalledWith(expect.objectContaining({ - where: { - AND: [{ - createdAt: { - gte: new Date('2026-08-30T16:00:00.000Z'), - lt: new Date('2026-08-31T16:00:00.000Z'), - }, - }], - }, - })) - }) -}) + search: '', + storeName: '', + accountType: '', + operationOwner: '', + accountGroupName: '', + createdAtGranularity: 'day', + createdAtValue: '2026-08-31', + }, + }) + + expect(mockPrisma.storeAccount.findMany).toHaveBeenCalledWith(expect.objectContaining({ + where: { + AND: [{ + createdAt: { + gte: new Date('2026-08-30T16:00:00.000Z'), + lt: new Date('2026-08-31T16:00:00.000Z'), + }, + }], + }, + })) + }) +}) describe('store account metadata filtering', () => { beforeEach(() => { diff --git a/furniture-3d-system/src/server/repositories/store-account-directory-sync.repository.ts b/furniture-3d-system/src/server/repositories/store-account-directory-sync.repository.ts new file mode 100644 index 00000000..25d5abf2 --- /dev/null +++ b/furniture-3d-system/src/server/repositories/store-account-directory-sync.repository.ts @@ -0,0 +1,98 @@ +import { prisma } from "@/lib/prisma"; +import type { Prisma } from "@prisma/client"; +import { readExcludedStoreNames, storeAccountExclusionWhere } from "./store-account-exclusion.repository"; + +export const storeAccountDirectoryFields = [ + "operationOwner", "operationDepartmentHead", "operationDirector", "profitCenter", +] as const; + +const select = { + id: true, + storeName: true, + operationOwner: true, + operationDepartmentHead: true, + operationDirector: true, + profitCenter: true, + updatedAt: true, +} satisfies Prisma.StoreAccountSelect; + +export type DirectoryAccount = Prisma.StoreAccountGetPayload<{ select: typeof select }>; +type DirectoryFields = Pick; +type UpdateGroup = { ids: string[]; changes: Partial }; +type SyncChange = { + previous: DirectoryAccount; + next: DirectoryFields; +}; +export type DirectoryMutation = { + expected: DirectoryAccount[]; + excludedNames: string[]; + add: Array; + update: SyncChange[]; + remove: DirectoryAccount[]; +}; + +type DirectoryClient = Pick; + +async function snapshot(client: DirectoryClient) { + const excludedNames = await readExcludedStoreNames(client); + const accounts = await client.storeAccount.findMany({ + where: storeAccountExclusionWhere(excludedNames), select, orderBy: { id: "asc" }, + }); + return { accounts, excludedNames }; +} + +export const storeAccountDirectorySyncRepository = { + snapshot: () => prisma.$transaction(snapshot, { isolationLevel: "RepeatableRead" }), + async apply(plan: DirectoryMutation) { + await prisma.$transaction(async (tx) => { + const { accounts: current, excludedNames } = await snapshot(tx); + if (JSON.stringify(excludedNames) !== JSON.stringify(plan.excludedNames)) { + throw new Error("预览后店铺排除库有变化,请重新预览"); + } + if (JSON.stringify(current) !== JSON.stringify(plan.expected)) { + throw new Error("预览后店铺账号有变化,请重新预览"); + } + const inserted = plan.add.length === 0 ? [] : await tx.storeAccount.createManyAndReturn({ + data: plan.add.map((row) => ({ ...row, account: "", accountType: "" })), + select: { id: true, storeName: true }, + }); + const grouped = new Map(); + for (const { previous, next } of plan.update) { + const changes = Object.fromEntries(storeAccountDirectoryFields.flatMap((field) => + previous[field] === next[field] ? [] : [[field, next[field]] as const], + )); + const key = JSON.stringify(changes); + const group: UpdateGroup = grouped.get(key) ?? { ids: [], changes }; + group.ids.push(previous.id); + grouped.set(key, group); + } + for (const { ids, changes } of grouped.values()) { + await tx.storeAccount.updateMany({ where: { id: { in: ids } }, data: changes }); + } + if (plan.remove.length > 0) { + await tx.storeAccount.deleteMany({ where: { id: { in: plan.remove.map((row) => row.id) } } }); + } + const data = [ + ...inserted.map((row) => ({ ...row, operation: "CREATE", changes: [] })), + ...plan.update.map(({ previous, next }) => ({ + id: previous.id, + storeName: previous.storeName, + operation: "UPDATE", + changes: storeAccountDirectoryFields.flatMap((field) => + previous[field] === next[field] ? [] : [{ field, previousValue: previous[field], nextValue: next[field] }], + ), + })), + ...plan.remove.map((row) => ({ ...row, operation: "DELETE", changes: [] })), + ]; + if (data.length > 0) { + await tx.storeAccountChangeLog.createMany({ data: data.map((row) => ({ + storeAccountId: row.id, + storeName: row.storeName, + operation: row.operation, + actorName: "店铺来源同步", + changes: row.changes, + })) }); + } + }, { isolationLevel: "Serializable", timeout: 30_000 }); + }, +}; diff --git a/furniture-3d-system/src/server/repositories/store-account-directory.repository.ts b/furniture-3d-system/src/server/repositories/store-account-directory.repository.ts new file mode 100644 index 00000000..ca406b24 --- /dev/null +++ b/furniture-3d-system/src/server/repositories/store-account-directory.repository.ts @@ -0,0 +1,78 @@ +import { createShopPlatformConnectionConfig } from "./store-account-platform.repository"; + +export type StoreAccountDirectoryRow = { + storeName: string; + platform: string | null; + shopHead: string | null; + virtualShop: boolean | null; +}; + +type StoreAccountFlowDirectoryRow = StoreAccountDirectoryRow & { hasOpeningFlow: boolean }; + +const jstQuery = ` +WITH shops AS ( + SELECT LTRIM(RTRIM(shop_name)) AS storeName, NULLIF(LTRIM(RTRIM(shop_site)), '') AS platform, + ROW_NUMBER() OVER ( + PARTITION BY CONVERT(nvarchar(4000), LTRIM(RTRIM(shop_name))) COLLATE Latin1_General_100_BIN2 + ORDER BY CASE WHEN NULLIF(LTRIM(RTRIM(shop_site)), '') IS NULL THEN 1 ELSE 0 END, + COALESCE(updateTime, createTime) DESC, Id DESC) AS rn + FROM __SCHEMA__.[jst_shopInfo] WHERE NULLIF(LTRIM(RTRIM(shop_name)), '') IS NOT NULL +) +SELECT storeName, platform, NULL AS shopHead, NULL AS virtualShop FROM shops WHERE rn = 1 +`; + +const flowQuery = ` +WITH flows AS ( + SELECT LTRIM(RTRIM(d.erpShopName)) AS storeName, + NULLIF(LTRIM(RTRIM(d.platform)), N'') AS platform, + NULLIF(LTRIM(RTRIM(d.shopHead)), N'') AS shopHead, d.isvirtualShop AS virtualShop, + CASE WHEN d.flowType = 8 THEN 1 ELSE 0 END AS isOpeningFlow, + COALESCE(f.flowType, d.flowType) AS flowType, + COALESCE(f.applyTime, d.applyTime, d.createTime) AS appliedAt, + f.Id AS masterId, d.Id AS detailId + FROM __SCHEMA__.[fys_shopInfo_flow] d + LEFT JOIN __SCHEMA__.[flow_flow] f ON f.flowId = d.flowId + WHERE NULLIF(LTRIM(RTRIM(d.erpShopName)), N'') IS NOT NULL +), ranked AS ( + SELECT *, + ROW_NUMBER() OVER (PARTITION BY storeName COLLATE Latin1_General_100_BIN2 + ORDER BY appliedAt DESC, masterId DESC, detailId DESC) AS latest, + ROW_NUMBER() OVER (PARTITION BY storeName COLLATE Latin1_General_100_BIN2 + ORDER BY CASE WHEN flowType IN (8, 9) THEN 0 ELSE 1 END, + appliedAt DESC, masterId DESC, detailId DESC) AS ownerLatest, + ROW_NUMBER() OVER (PARTITION BY storeName COLLATE Latin1_General_100_BIN2 + ORDER BY CASE WHEN platform IS NULL THEN 1 ELSE 0 END, + appliedAt DESC, masterId DESC, detailId DESC) AS platformLatest + FROM flows +) +SELECT storeName COLLATE Latin1_General_100_BIN2 AS storeName, + CAST(MAX(isOpeningFlow) AS bit) AS hasOpeningFlow, + MAX(CASE WHEN platformLatest = 1 THEN platform END) AS platform, + MAX(CASE WHEN ownerLatest = 1 AND flowType IN (8, 9) THEN shopHead END) AS shopHead, + CAST(MAX(CASE WHEN latest = 1 THEN CAST(virtualShop AS int) END) AS bit) AS virtualShop +FROM ranked GROUP BY storeName COLLATE Latin1_General_100_BIN2 +`; + +export async function readStoreAccountDirectorySources() { + const config = createShopPlatformConnectionConfig(); + if (!config) throw new Error("店铺报表库连接未配置"); + const schema = (process.env.JST_REPORT_DB_HOST?.trim() + ? process.env.JST_REPORT_DB_SCHEMA + : process.env.JST_PLANNING_SQLSERVER_SCHEMA || process.env.JST_SQLSERVER_SCHEMA)?.trim() || "rpt"; + if (!/^[A-Za-z0-9_]+$/.test(schema)) throw new Error("无效的报表库架构名"); + + const driverName = "mssql"; + const imported = await import(driverName); + const driver = imported.default ?? imported; + const pool = new driver.ConnectionPool({ ...config, options: { ...(config.options as object), readOnlyIntent: true } }); + const source = "[" + schema + "]"; + try { + await pool.connect(); + const [jst, flow] = await Promise.all( + [jstQuery, flowQuery].map(query => pool.request().query(query.replaceAll("__SCHEMA__", source))), + ); + return { jst: jst.recordset as StoreAccountDirectoryRow[], flow: flow.recordset as StoreAccountFlowDirectoryRow[] }; + } finally { + await pool.close(); + } +} diff --git a/furniture-3d-system/src/server/repositories/store-account-exclusion.repository.ts b/furniture-3d-system/src/server/repositories/store-account-exclusion.repository.ts new file mode 100644 index 00000000..75b336a3 --- /dev/null +++ b/furniture-3d-system/src/server/repositories/store-account-exclusion.repository.ts @@ -0,0 +1,88 @@ +import type { Prisma } from '@prisma/client' +import { prisma } from '@/lib/prisma' +import { + STORE_ACCOUNT_EXCLUSION_PREFIX as prefix, + type StoreAccountExclusion, + type StoreAccountExclusionReason, +} from '@/lib/store-account-exclusion' +import { AppError, ErrorCode } from '@/server/core/errors' + +type ConfigClient = Pick + +export function storeAccountExclusionWhere(names: readonly string[]): Pick | undefined { + return names.length ? { storeName: { notIn: [...names] } } : undefined +} + +async function readNames(client: ConfigClient) { + const rows = await client.systemConfig.findMany({ + where: { key: { startsWith: prefix } }, + select: { key: true }, + orderBy: { key: 'asc' }, + }) + return rows.map(({ key }) => key.slice(prefix.length)) +} + +let pending: Promise | undefined + +export function readExcludedStoreNames(client?: ConfigClient): Promise { + if (client) return readNames(client) + pending ??= readNames(prisma).finally(() => { pending = undefined }) + return pending +} + +export async function assertStoreNameAvailable(client: ConfigClient, storeName: string) { + const excluded = await client.systemConfig.findUnique({ + where: { key: prefix + storeName.trim() }, + select: { key: true }, + }) + if (excluded) throw new AppError(ErrorCode.VALIDATION_FAILED, `店铺「${storeName}」已在排除库中`) +} + +export async function addStoreAccountExclusions( + client: ConfigClient, + entries: ReadonlyArray<{ storeName: string; reason: StoreAccountExclusionReason; excludedAt?: Date }>, +) { + if (!entries.length) return 0 + const { count } = await client.systemConfig.createMany({ + data: entries.map(({ storeName, reason, excludedAt }) => ({ + key: prefix + storeName.trim(), + value: { reason }, + description: '店铺账号管理排除库', + ...(excludedAt ? { createdAt: excludedAt } : {}), + })), + skipDuplicates: true, + }) + return count +} + +export async function listStoreAccountExclusions(): Promise { + const rows = await prisma.systemConfig.findMany({ + where: { key: { startsWith: prefix } }, + select: { key: true, value: true, createdAt: true }, + orderBy: [{ createdAt: 'desc' }, { key: 'asc' }], + }) + return rows.flatMap(({ key, value, createdAt }) => { + if (!value || typeof value !== 'object' || Array.isArray(value)) return [] + const { reason } = value + if (reason !== 'workbook' && reason !== 'manual-delete') return [] + return [{ storeName: key.slice(prefix.length), reason, excludedAt: createdAt.toISOString() }] + }) +} + +export async function findLastManualStoreDeletions(client: Pick) { + const [logs, accounts] = await Promise.all([ + client.storeAccountChangeLog.groupBy({ + by: ['storeName'], + where: { operation: 'BATCH_DELETE' }, + _max: { createdAt: true }, + }), + client.storeAccount.findMany({ select: { storeName: true }, distinct: ['storeName'] }), + ]) + const active = new Set(accounts.map(({ storeName }) => storeName.trim())) + return logs.flatMap(({ storeName, _max }) => { + const name = storeName.trim() + return name && _max.createdAt && !active.has(name) + ? [{ storeName: name, reason: 'manual-delete' as const, excludedAt: _max.createdAt }] + : [] + }) +} 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 dc4bd62d..15b48449 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,6 +1,10 @@ import type { Prisma } from '@prisma/client' import { prisma } from '@/lib/prisma' import { buildStoreAccountMetadataFilters } from './store-account-metadata-filters' +import { + addStoreAccountExclusions, assertStoreNameAvailable, listStoreAccountExclusions, + readExcludedStoreNames, storeAccountExclusionWhere, +} from './store-account-exclusion.repository' import type { StoreAccountFilterKey, StoreAccountFilters, StoreAccountFieldPermissionUpdate } from '@/lib/store-account-management' export type StoreAccountRecord = { @@ -149,8 +153,9 @@ export function buildStoreAccountCreatedAtFilter(filters: Pick> = [...buildStoreAccountMetadataFilters(filters)] + if (excluded) and.push(excluded) 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) => [ @@ -196,8 +201,10 @@ function buildWhere(filters: StoreAccountFilters) { } export class StoreAccountManagementRepository { + listExclusions = listStoreAccountExclusions + async listPage(params: { skip: number; take: number; filters: StoreAccountFilters }) { - const where = buildWhere(params.filters) + const where = buildWhere(params.filters, storeAccountExclusionWhere(await readExcludedStoreNames())) const [rows, total] = await Promise.all([ prisma.storeAccount.findMany({ where, select: ACCOUNT_SELECT, orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], skip: params.skip, take: params.take }), prisma.storeAccount.count({ where }), @@ -206,7 +213,7 @@ export class StoreAccountManagementRepository { } async listAll(params: { filters: StoreAccountFilters }) { - const where = buildWhere(params.filters) + const where = buildWhere(params.filters, storeAccountExclusionWhere(await readExcludedStoreNames())) return prisma.storeAccount.findMany({ where, select: ACCOUNT_SELECT, @@ -216,6 +223,7 @@ export class StoreAccountManagementRepository { async listStoreNames() { const rows = await prisma.storeAccount.findMany({ + where: storeAccountExclusionWhere(await readExcludedStoreNames()), select: { storeName: true }, distinct: ['storeName'], orderBy: { storeName: 'asc' }, @@ -225,6 +233,7 @@ export class StoreAccountManagementRepository { async listFilterOptions() { const rows = await prisma.storeAccount.findMany({ + where: storeAccountExclusionWhere(await readExcludedStoreNames()), select: { storeName: true, operationOwner: true, @@ -249,12 +258,14 @@ export class StoreAccountManagementRepository { } async findById(id: string) { - return prisma.storeAccount.findUnique({ where: { id }, select: ACCOUNT_SELECT }) + const excluded = storeAccountExclusionWhere(await readExcludedStoreNames()) + return prisma.storeAccount.findUnique({ where: { id, ...excluded }, select: ACCOUNT_SELECT }) } async findByKey(params: { storeName: string; accountType: string; account: string }) { + const excluded = storeAccountExclusionWhere(await readExcludedStoreNames()) return prisma.storeAccount.findUnique({ - where: { storeName_accountType_account: params }, + where: { storeName_accountType_account: params, ...excluded }, select: ACCOUNT_SELECT, }) } @@ -274,18 +285,28 @@ export class StoreAccountManagementRepository { verificationContact?: string jstOrderService?: string accountGroupName?: string + storeAttribute?: string | null actorId: string }) { const { actorId, ...values } = data - return prisma.storeAccount.create({ data: { ...values, passwordCiphertext: values.passwordCiphertext ?? '', boundBankAccountNumberCiphertext: values.boundBankAccountNumberCiphertext ?? '', createdById: actorId, updatedById: actorId }, select: ACCOUNT_SELECT }) + return prisma.$transaction(async (tx) => { + await assertStoreNameAvailable(tx, values.storeName) + return tx.storeAccount.create({ data: { ...values, passwordCiphertext: values.passwordCiphertext ?? '', boundBankAccountNumberCiphertext: values.boundBankAccountNumberCiphertext ?? '', createdById: actorId, updatedById: actorId }, select: ACCOUNT_SELECT }) + }, { isolationLevel: 'Serializable' }) } - async update(id: string, data: Record & { updatedById: string }) { - return prisma.storeAccount.update({ where: { id }, data, select: ACCOUNT_SELECT }) + async update(id: string, data: Prisma.StoreAccountUpdateInput & { updatedById: string }) { + return prisma.$transaction(async (tx) => { + const excluded = storeAccountExclusionWhere(await readExcludedStoreNames(tx)) + const name = typeof data.storeName === 'string' ? data.storeName : data.storeName?.set + if (name) await assertStoreNameAvailable(tx, name) + return tx.storeAccount.update({ where: { id, ...excluded }, data, select: ACCOUNT_SELECT }) + }, { isolationLevel: 'Serializable' }) } async listByIds(ids: string[]) { - return prisma.storeAccount.findMany({ where: { id: { in: ids } }, select: ACCOUNT_SELECT }) + const excluded = storeAccountExclusionWhere(await readExcludedStoreNames()) + return prisma.storeAccount.findMany({ where: { id: { in: ids }, ...excluded }, select: ACCOUNT_SELECT }) } async deleteManyWithLogs( @@ -300,17 +321,28 @@ export class StoreAccountManagementRepository { }>, ) { if (ids.length === 0) return - await prisma.$transaction([ - ...logs.map((log) => - prisma.storeAccountChangeLog.create({ data: { ...log, changes: log.changes as object } }), - ), - prisma.storeAccount.deleteMany({ where: { id: { in: ids } } }), - ]) + await prisma.$transaction(async (tx) => { + const excluded = await readExcludedStoreNames(tx) + const deleted = await tx.storeAccount.deleteMany({ where: { id: { in: ids }, ...storeAccountExclusionWhere(excluded) } }) + if (deleted.count !== ids.length) throw new Error('账号记录已变化,请刷新后重试') + await tx.storeAccountChangeLog.createMany({ data: logs.map((log) => ({ ...log, changes: log.changes as object })) }) + const names = [...new Set(logs.map(({ storeName }) => storeName).filter(Boolean))] + const remaining = await tx.storeAccount.findMany({ + where: { storeName: { in: names } }, + select: { storeName: true }, + distinct: ['storeName'], + }) + const active = new Set(remaining.map(({ storeName }) => storeName)) + await addStoreAccountExclusions(tx, names.filter(name => !active.has(name)).map(storeName => ({ + storeName, reason: 'manual-delete', + }))) + }, { isolationLevel: 'Serializable' }) } async listForExport(ids?: string[]) { + const excluded = storeAccountExclusionWhere(await readExcludedStoreNames()) return prisma.storeAccount.findMany({ - where: ids ? { id: { in: ids } } : undefined, + where: ids ? { id: { in: ids }, ...excluded } : excluded, select: ACCOUNT_SELECT, orderBy: [{ storeName: 'asc' }, { account: 'asc' }], }) @@ -318,6 +350,7 @@ export class StoreAccountManagementRepository { async listForShopStateSync() { return prisma.storeAccount.findMany({ + where: storeAccountExclusionWhere(await readExcludedStoreNames()), select: { id: true, storeName: true, shopState: true }, orderBy: { id: 'asc' }, }) @@ -334,6 +367,7 @@ export class StoreAccountManagementRepository { } async listProfiles(storeName: string) { + if ((await readExcludedStoreNames()).includes(storeName.trim())) return [] return prisma.storeAccountStoreProfile.findMany({ where: { storeName }, select: PROFILE_SELECT, @@ -376,12 +410,15 @@ export class StoreAccountManagementRepository { values: Record actorId: string }) { - return prisma.storeAccount.upsert({ - where: { storeName_accountType_account: { storeName: data.storeName, accountType: data.accountType, account: data.account } }, - create: { ...data.values, storeName: data.storeName, accountType: data.accountType, account: data.account, createdById: data.actorId, updatedById: data.actorId }, - update: { ...data.values, updatedById: data.actorId }, - select: ACCOUNT_SELECT, - }) + return prisma.$transaction(async (tx) => { + await assertStoreNameAvailable(tx, data.storeName) + return tx.storeAccount.upsert({ + where: { storeName_accountType_account: { storeName: data.storeName, accountType: data.accountType, account: data.account } }, + create: { ...data.values, storeName: data.storeName, accountType: data.accountType, account: data.account, createdById: data.actorId, updatedById: data.actorId }, + update: { ...data.values, updatedById: data.actorId }, + select: ACCOUNT_SELECT, + }) + }, { isolationLevel: 'Serializable' }) } async createLog(data: { storeAccountId: string | null; storeName: string; operation: string; actorId: string; actorName: string; changes: unknown }) { diff --git a/furniture-3d-system/src/server/services/__tests__/store-account-directory-sync.service.test.ts b/furniture-3d-system/src/server/services/__tests__/store-account-directory-sync.service.test.ts new file mode 100644 index 00000000..a58ad0df --- /dev/null +++ b/furniture-3d-system/src/server/services/__tests__/store-account-directory-sync.service.test.ts @@ -0,0 +1,88 @@ +import { readStoreAccountDirectorySources } from "@/server/repositories/store-account-directory.repository"; +import { planStoreAccountDirectorySync } from "../store-account-directory-sync.service"; +import { loadStoreAccountDirectory } from "../store-account-directory.service"; + +jest.mock("@/lib/prisma", () => ({ prisma: {} })); +jest.mock("@/server/repositories/store-account-directory.repository", () => ({ + readStoreAccountDirectorySources: jest.fn(), +})); + +it("只有开店流程能单独加入名单,聚水潭已有店铺仍可从其他流程取字段", async () => { + const jstRow = { storeName: " 聚水潭店铺 ", platform: null, shopHead: null, virtualShop: null }; + const flowRow = { platform: "流程平台", shopHead: "流程负责人", virtualShop: false }; + jest.mocked(readStoreAccountDirectorySources).mockResolvedValueOnce({ + jst: [jstRow, { ...jstRow, storeName: "仅聚水潭", platform: "聚水潭平台" }, { ...jstRow, storeName: "两个来源" }], + flow: [ + { ...flowRow, storeName: "仅开店流程", hasOpeningFlow: true }, + { ...flowRow, storeName: "仅变更流程", hasOpeningFlow: false }, + { ...flowRow, storeName: "聚水潭店铺", hasOpeningFlow: false }, + { ...flowRow, storeName: "两个来源", hasOpeningFlow: true }, + ], + }); + + const directory = await loadStoreAccountDirectory(); + expect([...directory.keys()].sort()).toEqual(["两个来源", "仅开店流程", "仅聚水潭", "聚水潭店铺"]); + expect(directory.get("聚水潭店铺")).toEqual({ ...flowRow, storeName: "聚水潭店铺", sources: ["jst"] }); + expect(directory.get("仅开店流程")?.sources).toEqual(["openingFlow"]); + expect(directory.get("两个来源")?.sources).toEqual(["openingFlow", "jst"]); + expect(directory.get("仅聚水潭")?.platform).toBe("聚水潭平台"); +}); + +const existing = { + id: "existing", + storeName: "原有店铺", + operationOwner: "原负责人", + operationDepartmentHead: "原部门负责人", + operationDirector: "原总监", + profitCenter: "原利润中心", + updatedAt: new Date("2026-11-24T00:00:00Z"), +}; + +const owners = new Map([ + ["原负责人", { departmentOwner: "接口部门负责人", generalOwner: "", profitCenter: "接口利润中心" }], + ["流程负责人", { departmentOwner: "流程负责人的上级", generalOwner: "流程负责人的总监", profitCenter: "流程负责人的利润中心" }], +]); + +describe("店铺同步的组织架构匹配", () => { + it("从两个来源过滤排除店铺,并保留已经移入排除库的原账号", () => { + const directory = new Map(["附件店铺", "人工删除店铺", "正常新增"].map((storeName) => [storeName, { + storeName, shopHead: null, platform: null, virtualShop: null, + }])); + const archived = { ...existing, storeName: "附件店铺" }; + const { plan } = planStoreAccountDirectorySync(directory, owners, [archived], ["附件店铺", "人工删除店铺"]); + expect(plan.add.map(({ storeName }) => storeName)).toEqual(["正常新增"]); + expect(plan.expected).toEqual([]); + expect(plan.remove).toEqual([]); + expect(plan.update).toEqual([]); + }); + + it("按最终负责人匹配已有店铺和新增店铺", () => { + const directory = new Map(["原有店铺", "新增店铺"].map((storeName) => [storeName, { + storeName, shopHead: "流程负责人", platform: null, virtualShop: null, + }])); + const { plan } = planStoreAccountDirectorySync(directory, owners, [existing]); + expect(plan.update[0].next).toEqual({ + operationOwner: "流程负责人", + operationDepartmentHead: "流程负责人的上级", + operationDirector: "流程负责人的总监", + profitCenter: "流程负责人的利润中心", + }); + expect(plan.add).toEqual([{ storeName: "新增店铺", ...plan.update[0].next }]); + }); + + it("只回填组织上下级时按字段保底,并保留未命中人员的资料", () => { + const unmatched = { ...existing, id: "unmatched", storeName: "其他店铺", operationOwner: "接口没有的人" }; + const { plan } = planStoreAccountDirectorySync(null, owners, [existing, unmatched]); + expect(plan.add).toEqual([]); + expect(plan.remove).toEqual([]); + expect(plan.update).toEqual([{ + previous: existing, + next: { + operationOwner: "原负责人", + operationDepartmentHead: "接口部门负责人", + operationDirector: "原总监", + profitCenter: "原利润中心", + }, + }]); + }); +}); 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 d4c20d34..e038e494 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 @@ -73,10 +73,13 @@ function setup() { { id: "1", name: "负责人", email: "", status: "ACTIVE", businessRoles: [], dingtalkUserId: null }, { id: "2", name: "离职负责人", email: "", status: "INACTIVE", businessRoles: [], dingtalkUserId: null }, ]) }, - { getPlatformMap: jest.fn().mockResolvedValue(new Map([ - ["店铺一", "京东"], ["店铺二", "京东供销"], ["店铺三", "京东"], - ["源库独有店", "抖音小店"], - ])) }, + { + getPlatformMap: jest.fn().mockResolvedValue(new Map([ + ["店铺一", "京东"], ["店铺二", "京东供销"], ["店铺三", "京东"], + ["源库独有店", "抖音小店"], + ])), + getVirtualShopMap: jest.fn().mockResolvedValue(new Map([["店铺一", true], ["店铺二", true], ["店铺三", false]])), + }, ); const access = Object.fromEntries( STORE_ACCOUNT_FIELDS.map((field) => [field.key, "READONLY"]), @@ -98,12 +101,21 @@ describe("store account derived platform listing", () => { 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) => { + it("filters the effective attribute before pagination and leaves other metadata filters in the repository", async () => { 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: "" }) })); + const page = await service.listPage({ user, pageSize: 1, filters: { ...metadata, shopState: "0" } }); + expect(repository.listAll).toHaveBeenCalledWith(expect.objectContaining({ + filters: expect.objectContaining({ ...metadata, shopState: "", storeAttribute: "" }), + })); + expect(page.rows).toMatchObject([{ id: "2", storeAttribute: "虚拟店铺", storeAttributeOverride: null }]); + expect(page.pageInfo.total).toBe(1); + const manual = await service.listPage({ user, filters: { storeAttribute: "真实店铺" } }); + expect(manual.rows.map(({ id, storeAttributeOverride }) => ({ id, storeAttributeOverride }))).toEqual([ + { id: "1", storeAttributeOverride: "真实店铺" }, { id: "3", storeAttributeOverride: null }, + ]); + const unspecified = await service.listPage({ user, filters: { storeAttribute: STORE_ACCOUNT_METADATA_BLANK_FILTER } }); + expect(unspecified.rows.map((row) => row.id)).toEqual(["4"]); }); it("returns no rows when the platform selection is empty", async () => { @@ -115,6 +127,30 @@ describe("store account derived platform listing", () => { expect(page.pageInfo.total).toBe(0); }); + it("includes blank stored values alongside selected names and applies both filters before pagination", async () => { + const { service, repository } = setup(); + const rows = await repository.listAll(); + rows[0].operationDepartmentHead = "部门甲"; + rows[1].operationDepartmentHead = " "; + rows[2].operationDepartmentHead = "部门乙"; + const page = await service.listPage({ + user, page: 2, pageSize: 1, filters: { + operationDepartmentHead: `部门甲,${STORE_ACCOUNT_METADATA_BLANK_FILTER}`, + }, + }); + expect(page.rows.map((row) => row.id)).toEqual(["2"]); + expect(page.pageInfo.total).toBe(3); + }); + + it("keeps unknown source states distinct from normal state and unreported authorization distinct from unauthorized", async () => { + const { service } = setup(); + const blank = STORE_ACCOUNT_METADATA_BLANK_FILTER; + const states = await service.listPage({ user, filters: { shopState: `0,${blank}` } }); + expect(states.rows.map((row) => row.shopState)).toEqual([0, null]); + const missing = await service.listPage({ user, filters: { authorizationStatus: blank, platform: blank } }); + expect(missing.rows.map((row) => row.id)).toEqual(["4"]); + }); + it("filters exact platforms before pagination and counts all matching rows", async () => { const { service, repository } = setup(); const page = await service.listPage({ user, page: 2, pageSize: 1, filters: { platform: "京东" } }); @@ -163,7 +199,7 @@ describe("store account derived platform listing", () => { 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 }); + expect(page.rows[1]).toMatchObject({ storeOwnership: null, storeAttribute: "虚拟店铺", storeAttributeOverride: null, shippingEnabled: null }); }); it("filters source state before pagination and never prefilters stale database state", async () => { diff --git a/furniture-3d-system/src/server/services/store-account-directory-sync.service.ts b/furniture-3d-system/src/server/services/store-account-directory-sync.service.ts new file mode 100644 index 00000000..abe82da2 --- /dev/null +++ b/furniture-3d-system/src/server/services/store-account-directory-sync.service.ts @@ -0,0 +1,90 @@ +import { createHash } from "node:crypto"; +import { fetchStoreAccountOrgOwners, type StoreAccountOrgOwner } from "@/server/integrations/store-account-org-structure/client"; +import type { StoreAccountDirectoryRow } from "@/server/repositories/store-account-directory.repository"; +import { + storeAccountDirectoryFields, + storeAccountDirectorySyncRepository, + type DirectoryAccount, + type DirectoryMutation, +} from "@/server/repositories/store-account-directory-sync.repository"; +import { filterStoreAccountDirectory, loadStoreAccountDirectory } from "./store-account-directory.service"; + +export function planStoreAccountDirectorySync( + directory: ReadonlyMap | null, + owners: ReadonlyMap, + accounts: DirectoryAccount[], + excludedNames: string[] = [], +) { + if (directory?.size === 0 || owners.size === 0) throw new Error("店铺名单或组织架构未返回数据"); + directory = directory && filterStoreAccountDirectory(directory, excludedNames); + const excluded = new Set(excludedNames); + const activeAccounts = accounts.filter(account => !excluded.has(account.storeName.trim())); + const plan: DirectoryMutation = { expected: activeAccounts, excludedNames, add: [], update: [], remove: [] }; + const existing = new Set(); + for (const account of activeAccounts) { + const name = account.storeName.trim(); + existing.add(name); + const row = directory?.get(name); + if (directory && !row) { + plan.remove.push(account); + continue; + } + const operationOwner = row?.shopHead || account.operationOwner; + const owner = owners.get(operationOwner.trim()); + const next = { + operationOwner, + operationDepartmentHead: owner?.departmentOwner || account.operationDepartmentHead, + operationDirector: owner?.generalOwner || account.operationDirector, + profitCenter: directory ? owner?.profitCenter || account.profitCenter : account.profitCenter, + }; + if (storeAccountDirectoryFields.some((field) => next[field] !== account[field])) { + plan.update.push({ previous: account, next }); + } + } + for (const name of [...(directory?.keys() ?? [])].sort()) { + if (existing.has(name)) continue; + const operationOwner = directory?.get(name)?.shopHead ?? ""; + const owner = owners.get(operationOwner.trim()); + plan.add.push({ + storeName: name, + operationOwner, + operationDepartmentHead: owner?.departmentOwner ?? "", + operationDirector: owner?.generalOwner ?? "", + profitCenter: owner?.profitCenter ?? "", + }); + } + const removedNames = [...new Set(plan.remove.map((row) => row.storeName.trim()))].sort(); + return { + plan, + confirmation: createHash("sha256").update(JSON.stringify({ hierarchyOnly: !directory, plan })).digest("hex"), + summary: { + sourceStores: directory?.size ?? null, + currentAccounts: activeAccounts.length, + retainedStores: directory ? directory.size - plan.add.length : existing.size, + addedStores: plan.add.length, + removedStores: removedNames.length, + removedAccounts: plan.remove.length, + updatedOwners: plan.update.filter(({ previous, next }) => previous.operationOwner !== next.operationOwner).length, + updatedDepartmentHeads: plan.update.filter(({ previous, next }) => previous.operationDepartmentHead !== next.operationDepartmentHead).length, + updatedDirectors: plan.update.filter(({ previous, next }) => previous.operationDirector !== next.operationDirector).length, + updatedProfitCenters: plan.update.filter(({ previous, next }) => previous.profitCenter !== next.profitCenter).length, + updatedAccounts: plan.update.length, + removedNames, + }, + }; +} + +export async function syncStoreAccountDirectory(confirmation?: string, hierarchyOnly = false) { + const [directory, owners, { accounts, excludedNames }] = await Promise.all([ + hierarchyOnly ? null : loadStoreAccountDirectory(), + fetchStoreAccountOrgOwners(), + storeAccountDirectorySyncRepository.snapshot(), + ]); + if (!owners) throw new Error("组织架构接口未配置"); + const result = planStoreAccountDirectorySync(directory, owners, accounts, excludedNames); + if (confirmation !== undefined) { + if (confirmation !== result.confirmation) throw new Error("同步方案已变化,请重新预览"); + await storeAccountDirectorySyncRepository.apply(result.plan); + } + return { ...result.summary, confirmation: result.confirmation, applied: confirmation !== undefined }; +} diff --git a/furniture-3d-system/src/server/services/store-account-directory.service.ts b/furniture-3d-system/src/server/services/store-account-directory.service.ts new file mode 100644 index 00000000..dc22aae1 --- /dev/null +++ b/furniture-3d-system/src/server/services/store-account-directory.service.ts @@ -0,0 +1,58 @@ +import type { StoreAccountSource } from "@/lib/store-account-management"; +import { readExcludedStoreNames } from "@/server/repositories/store-account-exclusion.repository"; +import { + readStoreAccountDirectorySources, + type StoreAccountDirectoryRow, +} from "@/server/repositories/store-account-directory.repository"; + +type DirectoryEntry = StoreAccountDirectoryRow & { sources: readonly StoreAccountSource[] }; + +export async function loadStoreAccountDirectory() { + const { jst, flow } = await readStoreAccountDirectorySources(); + if (!jst.length || !flow.length) throw new Error("店铺来源未返回完整名单"); + const directory = new Map(); + const fieldsByFlowName = new Map(); + for (const { hasOpeningFlow, ...source } of flow) { + const storeName = source.storeName.trim(); + const fields = { ...source, storeName }; + fieldsByFlowName.set(storeName, fields); + if (hasOpeningFlow) directory.set(storeName, { ...fields, sources: ["openingFlow"] }); + } + for (const row of jst) { + const storeName = row.storeName.trim(); + const fromFlow = fieldsByFlowName.get(storeName); + directory.set(storeName, { + ...(fromFlow ?? row), storeName, platform: row.platform ?? fromFlow?.platform ?? null, + sources: directory.has(storeName) ? ["openingFlow", "jst"] : ["jst"], + }); + } + directory.delete(""); + return directory; +} + +let cache: { value: Awaited>; expiresAt: number } | undefined; +let pending: ReturnType | undefined; + +async function getCachedDirectory() { + if (cache && cache.expiresAt > Date.now()) return cache.value; + pending ??= loadStoreAccountDirectory().then(value => { + cache = { value, expiresAt: Date.now() + 300_000 }; + return value; + }).catch(() => { + console.warn("[store-account-directory] 店铺来源不可用"); + const value = cache?.value ?? new Map(); + cache = { value, expiresAt: Date.now() + 60_000 }; + return value; + }).finally(() => { pending = undefined }); + return pending; +} + +export function filterStoreAccountDirectory(directory: ReadonlyMap, excludedNames: readonly string[]) { + const excluded = new Set(excludedNames); + return new Map([...directory].filter(([name]) => !excluded.has(name))); +} + +export async function getStoreAccountDirectory() { + const [directory, excludedNames] = await Promise.all([getCachedDirectory(), readExcludedStoreNames()]); + return filterStoreAccountDirectory(directory, excludedNames); +} 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 ac1ecd04..a2a25f31 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 @@ -16,7 +16,13 @@ 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"; +import { + STORE_ACCOUNT_METADATA_BLANK_FILTER, + STORE_ACCOUNT_METADATA_FILTER_OPTIONS, + STORE_ACCOUNT_METADATA_NONE_FILTER, + STORE_ACCOUNT_STORE_NAME_FILLED_FILTER, +} from "@/lib/store-account-metadata-filters"; +import { resolveStoreAccountAttribute } from "@/lib/store-account-store-metadata"; type ListDependencies = { repository: StoreAccountManagementRepository; @@ -38,6 +44,20 @@ function splitFilterValues(value: string) { return [...new Set(value.split(/[,,;;]+/).map((item) => item.trim()).filter(Boolean))]; } +const storedHeaderFields = { + storeName: "storeName", + operationOwnerExact: "operationOwner", + operationDepartmentHead: "operationDepartmentHead", + operationDirector: "operationDirector", + profitCenter: "profitCenter", + accountType: "accountType", +} as const; + +function matchesSelection(selection: readonly string[], value: string | number | null | undefined) { + return selection.length === 0 || + selection.includes(String(value ?? "").trim() || STORE_ACCOUNT_METADATA_BLANK_FILTER); +} + export async function listStoreAccountPage( { repository, authorizationReader, platformReader, ownerUserReader, shopInfoReader = storeAccountShopInfoService }: ListDependencies, @@ -45,18 +65,27 @@ export async function listStoreAccountPage( ): Promise { const authorizationFilter = splitFilterValues(filters.authorizationStatus); const platformFilter = splitFilterValues(filters.platform); - const hasAuthorizationFilter = authorizationFilter.length > 0; - const hasPlatformFilter = platformFilter.length > 0; const shopStateFilter = splitFilterValues(filters.shopState); - const hasShopStateFilter = shopStateFilter.length > 0; // The stored state can lag the source. Never prefilter by that stored value. - const repositoryFilters = { ...filters, shopState: "" }; + const repositoryFilters = { ...filters, shopState: "", storeAttribute: "" }; + const attributeFilter = splitFilterValues(filters.storeAttribute); + const storedBlankSelections = Object.entries(storedHeaderFields).flatMap(([queryKey, field]) => { + const key = queryKey as keyof typeof storedHeaderFields; + const selected = splitFilterValues(filters[key]); + const noSelection = selected.includes(STORE_ACCOUNT_METADATA_NONE_FILTER); + const filledNames = key === "storeName" && filters.storeName === STORE_ACCOUNT_STORE_NAME_FILLED_FILTER; + if (!noSelection && !filledNames && !selected.includes(STORE_ACCOUNT_METADATA_BLANK_FILTER)) return []; + repositoryFilters[key] = ""; + return [{ field, selected, noSelection, filledNames }]; + }); const ownerStatusFilter = filters.operationOwnerStatus.trim(); const hasOwnerStatusFilter = ownerStatusFilter === "DEPARTED" || ownerStatusFilter === "ACTIVE"; // Derived filters must run before pagination to keep totals and pages accurate. - const needsFullScan = hasAuthorizationFilter || hasOwnerStatusFilter || hasPlatformFilter || hasShopStateFilter; - const [result, storeNames, filterOptions, platformByStoreName, shopInfoByName] = await Promise.all([ + const needsFullScan = hasOwnerStatusFilter || [ + authorizationFilter, platformFilter, shopStateFilter, attributeFilter, storedBlankSelections, + ].some((selection) => selection.length > 0); + const [result, storeNames, filterOptions, platformByStoreName, shopInfoByName, virtualByName, sourcesByName] = await Promise.all([ needsFullScan ? repository.listAll({ filters: repositoryFilters }).then((rows) => ({ rows, total: rows.length })) : repository.listPage({ @@ -68,7 +97,11 @@ export async function listStoreAccountPage( repository.listFilterOptions(), platformReader.getPlatformMap(), shopInfoReader.getShopInfoMap(), + platformReader.getVirtualShopMap?.() ?? new Map(), + fieldAccess.storeName === "HIDDEN" ? undefined : platformReader.getSourceMap?.(), ]); + const attributeFor = (record: StoreAccountRecord) => + resolveStoreAccountAttribute(record.storeAttribute, virtualByName.get(record.storeName.trim())); const authorizationStatusByStoreName = await authorizationReader.getStatusMap( result.rows.map((record) => record.storeName), ); @@ -85,16 +118,15 @@ export async function listStoreAccountPage( : null; const filteredRows = needsFullScan ? result.rows.filter((record) => { - const sourceState = shopInfoByName.get(record.storeName.trim())?.shopState; - if (hasShopStateFilter && (sourceState == null || !shopStateFilter.includes(String(sourceState)))) return false; - if ( - hasPlatformFilter && - !platformFilter.includes(platformByStoreName.get(record.storeName.trim()) ?? "") - ) return false; - if (hasAuthorizationFilter) { - const status = authorizationStatusByStoreName.get(record.storeName.trim()); - if (!status || !authorizationFilter.includes(status)) return false; - } + const storeName = record.storeName.trim(); + const matchesStored = storedBlankSelections.every(({ field, selected, noSelection, filledNames }) => + !noSelection && (filledNames ? Boolean(storeName) : matchesSelection(selected, record[field])), + ); + if (!matchesStored || + !matchesSelection(attributeFilter, attributeFor(record)) || + !matchesSelection(shopStateFilter, shopInfoByName.get(storeName)?.shopState) || + !matchesSelection(platformFilter, platformByStoreName.get(storeName)) || + !matchesSelection(authorizationFilter, authorizationStatusByStoreName.get(storeName))) return false; if (hasOwnerStatusFilter && ownerEmployment) { if (ownerStatusFilter === "DEPARTED") { const hit = [record.operationOwner, record.operationDepartmentHead, record.operationDirector] @@ -134,11 +166,14 @@ export async function listStoreAccountPage( ? "" : platformByStoreName.get(record.storeName.trim()) ?? ""; const source = shopInfoByName.get(record.storeName.trim()); + const sources = sourcesByName?.get(record.storeName.trim()); + if (sources?.length) row.sources = sources; 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.storeAttributeOverride = record.storeAttribute || null; + row.storeAttribute = attributeFor(record); row.shippingEnabled = record.shippingEnabled ?? null; if (ownerEmploymentForRows.departedNames.has(record.operationOwner.trim())) { row.operationOwnerDeparted = true; diff --git a/furniture-3d-system/src/server/services/store-account-management-export.service.ts b/furniture-3d-system/src/server/services/store-account-management-export.service.ts index 494b0ada..9dd23a4b 100644 --- a/furniture-3d-system/src/server/services/store-account-management-export.service.ts +++ b/furniture-3d-system/src/server/services/store-account-management-export.service.ts @@ -7,7 +7,7 @@ import { formatStoreAccountShopState, formatStoreAccountAuthorizationStatus, } from '@/lib/store-account-management' -import { formatStoreAccountShipping } from '@/lib/store-account-store-metadata' +import { formatStoreAccountShipping, resolveStoreAccountAttribute } from '@/lib/store-account-store-metadata' import { storeAccountPlatformService, type StoreAccountPlatformReader } from './store-account-platform.service' import { storeAccountShopInfoService, type StoreAccountShopInfoReader } from './store-account-shop-info.service' import { storeAccountAuthorizationService, type StoreAccountAuthorizationReader } from './store-account-authorization.service' @@ -105,10 +105,11 @@ export class StoreAccountManagementExportService { this.fieldAccessReader.getFieldAccess(input.user), this.passwordAccessReader.resolveScope(input.user), ]) - const [platformByName, shopInfoByName, authorizationByName] = await Promise.all([ + const [platformByName, shopInfoByName, authorizationByName, virtualByName] = await Promise.all([ this.platformReader.getPlatformMap(), this.shopInfoReader.getShopInfoMap(), this.authorizationReader.getStatusMap(rows.map((row) => row.storeName)), + this.platformReader.getVirtualShopMap?.() ?? new Map(), ]) const workbook = new ExcelJS.Workbook() workbook.creator = input.user.name @@ -136,7 +137,7 @@ export class StoreAccountManagementExportService { accountType: formatAccountType(row.accountType), shopState: formatStoreAccountShopState(shopInfo?.shopState), storeOwnership: row.storeOwnership || '-', - storeAttribute: row.storeAttribute || '-', + storeAttribute: resolveStoreAccountAttribute(row.storeAttribute, virtualByName.get(storeName)) ?? '-', shippingEnabled: formatStoreAccountShipping(row.shippingEnabled), openTime: shopInfo?.openTime || '-', renewalTime: shopInfo?.renewalTime || '-', diff --git a/furniture-3d-system/src/server/services/store-account-management.service.ts b/furniture-3d-system/src/server/services/store-account-management.service.ts index 33f06b4f..0d652a0d 100644 --- a/furniture-3d-system/src/server/services/store-account-management.service.ts +++ b/furniture-3d-system/src/server/services/store-account-management.service.ts @@ -61,6 +61,7 @@ import { type StoreAccountPlatformReader, } from "./store-account-platform.service"; import { listStoreAccountPage } from "./store-account-list.service"; +import { resolveStoreAccountAttribute, STORE_ACCOUNT_ATTRIBUTES } from "@/lib/store-account-store-metadata"; import { cleanStoreAccountValue as clean, normalizeStoreAccountType as normalizeType, @@ -265,11 +266,23 @@ export class StoreAccountManagementService { throw new AppError(ErrorCode.PRODUCT_NOT_FOUND, "店铺账号不存在"); const passwordView = await this.getPasswordViewContext(user, access); return { - row: this.toRow(record, passwordView.rowAccess, passwordView.scope), + row: { + ...this.toRow(record, passwordView.rowAccess, passwordView.scope), + storeAttribute: resolveStoreAccountAttribute( + record.storeAttribute, + record.storeAttribute ? undefined : (await this.platformReader.getVirtualShopMap?.())?.get(record.storeName.trim()), + ), + }, fieldAccess: passwordView.rowAccess, }; } + async listExclusions(user: AuthUser) { + const { target, access } = await this.getFieldAccess(user); + if (!target.view || access.storeName === "HIDDEN") return null; + return { items: await this.repository.listExclusions() }; + } + async create(input: Record, user: AuthUser) { const { target, access } = await this.getFieldAccess(user); if (!target.edit) @@ -277,8 +290,10 @@ export class StoreAccountManagementService { ErrorCode.AUTH_PERMISSION_DENIED, "当前账号没有编辑店铺账号的权限", ); - const values = await new StoreAccountValuesService(this.ownerOptionReader) - .prepareValues(input, access, "create"); + const values = { + ...await new StoreAccountValuesService(this.ownerOptionReader).prepareValues(input, access, "create"), + ...this.storeAttributeChange(input.storeAttribute), + }; if ( await this.repository.findByKey({ storeName: values.storeName, @@ -316,8 +331,10 @@ export class StoreAccountManagementService { const current = await this.repository.findById(clean(id, 80)); if (!current) throw new AppError(ErrorCode.PRODUCT_NOT_FOUND, "店铺账号不存在"); - const values = await new StoreAccountValuesService(this.ownerOptionReader) - .prepareValues(input, access, "update"); + const values = { + ...await new StoreAccountValuesService(this.ownerOptionReader).prepareValues(input, access, "update"), + ...this.storeAttributeChange(input.storeAttribute), + }; if (Object.keys(values).length === 0) throw new AppError( ErrorCode.VALIDATION_REQUIRED_FIELD, @@ -979,12 +996,21 @@ export class StoreAccountManagementService { jstOrderService: value("jstOrderService", record.jstOrderService), accountGroupName: value("accountGroupName", record.accountGroupName), shopState: record.shopState, + storeAttributeOverride: record.storeAttribute || null, authorizationStatus, createdAt: record.createdAt.toISOString(), updatedAt: record.updatedAt.toISOString(), }; } + private storeAttributeChange(value: unknown) { + if (value === undefined) return {}; + if (value === null || value === STORE_ACCOUNT_ATTRIBUTES[0] || value === STORE_ACCOUNT_ATTRIBUTES[1]) { + return { storeAttribute: value }; + } + throw new AppError(ErrorCode.VALIDATION_INVALID_FORMAT, "请选择有效的店铺属性"); + } + private changeSet( previous: Record, values: Record, @@ -1007,7 +1033,7 @@ export class StoreAccountManagementService { { field, previousValue: isSecret ? (old ? "已设置" : "未设置") : (old ?? ""), - nextValue: isSecret ? (next ? "已设置" : "未设置") : next, + nextValue: isSecret ? (next ? "已设置" : "未设置") : (next ?? ""), }, ]; }); diff --git a/furniture-3d-system/src/server/services/store-account-owner-options.service.ts b/furniture-3d-system/src/server/services/store-account-owner-options.service.ts index 29d142ef..370334f2 100644 --- a/furniture-3d-system/src/server/services/store-account-owner-options.service.ts +++ b/furniture-3d-system/src/server/services/store-account-owner-options.service.ts @@ -39,7 +39,7 @@ export class StoreAccountOwnerOptionsService implements StoreAccountOwnerOptionR operationOwner: name, departmentOwner: owner.departmentOwner || prior?.departmentOwner || "", generalOwner: owner.generalOwner || prior?.generalOwner || "", - profitCenter: prior?.profitCenter ?? "", + profitCenter: owner.profitCenter || prior?.profitCenter || "", }); } return { items: Array.from(byName.values()) }; diff --git a/furniture-3d-system/src/server/services/store-account-platform.service.ts b/furniture-3d-system/src/server/services/store-account-platform.service.ts index 7743eec0..2e9e69ec 100644 --- a/furniture-3d-system/src/server/services/store-account-platform.service.ts +++ b/furniture-3d-system/src/server/services/store-account-platform.service.ts @@ -1,17 +1,6 @@ -import { - storeAccountPlatformRepository, - type PlatformSourceRow, -} from "@/server/repositories/store-account-platform.repository"; - -const CACHE_TTL_MS = 5 * 60 * 1000; -const FAILURE_CACHE_TTL_MS = 60 * 1000; - -let cachedPlatforms: { - expiresAt: number; - value: Map; -} | null = null; - -let pendingPlatforms: Promise> | null = null; +import type { StoreAccountSource } from "@/lib/store-account-management"; +import type { PlatformSourceRow } from "@/server/repositories/store-account-platform.repository"; +import { getStoreAccountDirectory } from "./store-account-directory.service"; function normalizeStoreName(value: unknown) { return String(value ?? "").trim(); @@ -34,33 +23,29 @@ export function buildPlatformMap(rows: readonly PlatformSourceRow[]) { ); } - export type StoreAccountPlatformReader = { getPlatformMap(): Promise>; + getVirtualShopMap?(): Promise>; + getSourceMap?(): Promise>; }; export const storeAccountPlatformService: StoreAccountPlatformReader = { async getPlatformMap() { - if (cachedPlatforms && cachedPlatforms.expiresAt > Date.now()) { - return cachedPlatforms.value; - } - if (pendingPlatforms) return pendingPlatforms; - pendingPlatforms = (async () => { - let value = new Map(); - let ttl = CACHE_TTL_MS; - try { - value = buildPlatformMap(await storeAccountPlatformRepository.listPlatforms()); - } catch { - console.warn("[store-account-platform] 报表库查询失败,平台暂为空值"); - ttl = FAILURE_CACHE_TTL_MS; - } - cachedPlatforms = { expiresAt: Date.now() + ttl, value }; - return value; - })(); - try { - return await pendingPlatforms; - } finally { - pendingPlatforms = null; - } + const directory = await getStoreAccountDirectory(); + const values = new Map(); + for (const [name, row] of directory) if (row.platform) values.set(name, row.platform); + return values; + }, + + async getVirtualShopMap() { + const directory = await getStoreAccountDirectory(); + const values = new Map(); + for (const [name, row] of directory) if (row.virtualShop != null) values.set(name, row.virtualShop); + return values; + }, + + async getSourceMap() { + const directory = await getStoreAccountDirectory(); + return new Map([...directory].map(([name, row]) => [name, row.sources])); }, }; From 00feaf476419254a6c742d8a2c04bf25de9a3d28 Mon Sep 17 00:00:00 2001 From: apple Date: Wed, 25 Nov 2026 11:58:59 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(production-stop-demands):=20=E6=B8=85?= =?UTF-8?q?=E9=99=A40=E7=BA=A7=E7=A1=AE=E8=AE=A4=E5=B9=B6=E9=87=8D?= =?UTF-8?q?=E8=B7=AF=E7=94=B1=E5=8E=86=E5=8F=B2=E5=BE=85=E7=A1=AE=E8=AE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- furniture-3d-system/package.json | 1 + ...ay-production-stop-stage0-confirmations.ts | 670 ++++++++++++++++++ .../product-stop-detail.repository.ts | 5 - .../production-stop-demands.repository.ts | 6 +- ...duction-stop-notifications.service.test.ts | 66 +- .../production-stop-notifications.service.ts | 68 +- 6 files changed, 745 insertions(+), 71 deletions(-) create mode 100644 furniture-3d-system/scripts/replay-production-stop-stage0-confirmations.ts diff --git a/furniture-3d-system/package.json b/furniture-3d-system/package.json index 1e2b8838..df90e1d0 100644 --- a/furniture-3d-system/package.json +++ b/furniture-3d-system/package.json @@ -43,6 +43,7 @@ "backfill:production-stop-archive-snapshot": "tsx scripts/backfill-production-stop-archive-snapshot.ts", "audit:production-stop-owner-coverage": "tsx scripts/backfill-production-stop-archive-snapshot.ts --fail-on-pending-missing-owners", "replay:production-stop-confirmation-workflow": "tsx scripts/replay-production-stop-confirmation-workflow.ts", + "replay:production-stop-stage0-confirmations": "tsx scripts/replay-production-stop-stage0-confirmations.ts", "dispatch:production-stop-confirmation-warnings": "tsx scripts/dispatch-production-stop-confirmation-warnings.ts", "run:product-sabc": "tsx scripts/run-product-sabc.ts", "compare:product-sabc-xlsx": "tsx scripts/compare-product-sabc-xlsx.ts", diff --git a/furniture-3d-system/scripts/replay-production-stop-stage0-confirmations.ts b/furniture-3d-system/scripts/replay-production-stop-stage0-confirmations.ts new file mode 100644 index 00000000..c9f71021 --- /dev/null +++ b/furniture-3d-system/scripts/replay-production-stop-stage0-confirmations.ts @@ -0,0 +1,670 @@ +/** + * 正式站历史 stage=0 停产待确认单按新规则重新路由并推送。 + * + * 默认 dry-run: + * npx tsx scripts/replay-production-stop-stage0-confirmations.ts + * + * 指定条码预演: + * npx tsx scripts/replay-production-stop-stage0-confirmations.ts \ + * --barcodes=BG001436N66V01,BG001435N66V01 + * + * 正式执行: + * npx tsx scripts/replay-production-stop-stage0-confirmations.ts \ + * --apply --confirm=replay-production-stop-stage0-confirmations + */ +import 'dotenv/config' +import { mkdir, writeFile } from 'node:fs/promises' +import { dirname, resolve } from 'node:path' +import { + OperationLogAction, + OperationLogStatus, +} from '@prisma/client' +import { + resolveProductionStopConfirmationDeadlineDetails, + type ProductionStopConfirmationWorkflowNode, +} from '../src/lib/production-stop-demands' +import { splitProductionStopOwnerNames } from '../src/lib/production-stop-confirmation-workflow' +import { prisma } from '../src/lib/prisma' +import { productionStopDemandRepository } from '../src/server/repositories/production-stop-demands.repository' +import { closeSupplyChainArchiveReadPool } from '../src/server/repositories/supply-chain-archive-read-pool' +import { productionStopFlowRepository } from '../src/server/repositories/production-stop-flow.repository' +import { operationLogService } from '../src/server/services/operation-log.service' +import { productionStopNotificationsService } from '../src/server/services/production-stop-notifications.service' +import { resolveProductionStopLiveRoutingOwnersByBarcodes } from '../src/server/services/production-stop-owner-resolver' + +const APPLY_CONFIRMATION = 'replay-production-stop-stage0-confirmations' + +type ActiveUser = { + id: string + name: string + dingtalkUserId: string | null + dingtalkUnionId: string | null +} + +type ExistingVote = { + approverId: string + approverName: string + decision: string + confirmationStage: number +} + +type RoutingFallback = { + originalUserId: string + originalUserName: string + fallbackUserId: string + fallbackUserName: string +} + +type DemandPlan = { + demandId: string + demandNo: string + barcodes: string[] + existingVotes: ExistingVote[] + ownerNames: { + opsDeptHead: string[] + opsDirector: string[] + shopBusinessUnitHead: string[] + fallback: string[] + } + routeBranch: 'ZERO_VOTE' | 'NON_DIRECTOR_VOTE' | 'DIRECTOR_VOTE' + targetNode: string + targetStage: number + recipients: string[] + routingFallbacks: RoutingFallback[] + targetStatus: 'PENDING' | 'AGREED' + targetDemandStatus: 'PENDING_CONFIRMATION' | 'CONFIRMED_WAIT_FLOW' + targetDeadline: string + targetDeadlineNote: string + reason: string + blockingReason: string +} + +type ApplyResult = { + processed: number + pendingPushes: number + sent: number + failed: number + confirmedWaitFlow: number + failures: Array<{ demandNo: string; error: string }> +} + +function argumentValue(name: string) { + const prefix = `--${name}=` + return process.argv.find((argument) => argument.startsWith(prefix))?.slice(prefix.length) +} + +function normalizeName(value: unknown) { + return String(value ?? '').trim().toLocaleLowerCase('zh-CN') +} + +function uniqueNames(values: readonly string[]) { + return splitProductionStopOwnerNames(values) +} + +function isDingtalkBound(user: ActiveUser | undefined) { + return Boolean(user?.dingtalkUserId || user?.dingtalkUnionId) +} + +async function resolveSalesShopOwnersByBarcode(barcodes: readonly string[]) { + const shops = await prisma.supplyChainProductStopShopPerformance.findMany({ + where: { barcode: { in: [...barcodes] } }, + select: { + barcode: true, + shopName: true, + netQty: true, + realPerformance: true, + }, + }) + const salesShops = shops.filter((row) => ( + Number(row.netQty) !== 0 || Number(row.realPerformance) !== 0 + )) + const storeNames = [...new Set(salesShops.map((row) => row.shopName.trim()).filter(Boolean))] + const accounts = storeNames.length + ? await prisma.storeAccount.findMany({ + where: { storeName: { in: storeNames } }, + select: { + id: true, + storeName: true, + accountType: true, + operationDirector: true, + updatedAt: true, + }, + }) + : [] + const accountByStore = new Map() + for (const account of [...accounts].sort((left, right) => ( + (left.accountType === 'MAIN' ? 0 : 1) - (right.accountType === 'MAIN' ? 0 : 1) + || right.updatedAt.getTime() - left.updatedAt.getTime() + || right.id.localeCompare(left.id) + ))) { + const key = normalizeName(account.storeName) + if (!accountByStore.has(key) && account.operationDirector.trim()) { + accountByStore.set(key, account) + } + } + const result = new Map() + for (const shop of salesShops) { + const barcode = shop.barcode.trim().toUpperCase() + const director = accountByStore.get(normalizeName(shop.shopName))?.operationDirector ?? '' + if (!barcode || !director.trim()) continue + const current = result.get(barcode) ?? [] + if (!current.some((name) => normalizeName(name) === normalizeName(director))) { + current.push(director.trim()) + } + result.set(barcode, current) + } + return result +} + +function evaluateNode( + node: ProductionStopConfirmationWorkflowNode | null, + ownerNames: readonly string[], + usersByName: ReadonlyMap, + fallbackUser: ActiveUser | null, +) { + const names = uniqueNames(ownerNames) + if (!node || !names.length) return null + const knownUsers = names + .map((name) => usersByName.get(normalizeName(name))) + .filter((user): user is ActiveUser => Boolean(user)) + if (!knownUsers.length) return null + const boundUsers = knownUsers.filter(isDingtalkBound) + const unboundUsers = knownUsers.filter((user) => !isDingtalkBound(user)) + if (unboundUsers.length && !fallbackUser) { + return { + node, + recipients: [] as string[], + routingFallbacks: [] as RoutingFallback[], + blockingReason: `${node.name}的确认人 ${unboundUsers.map((user) => user.name).join('、')} 未绑定钉钉,且兜底确认人不可用`, + } + } + const recipients = uniqueNames([ + ...boundUsers.map((user) => user.name), + ...(unboundUsers.length && fallbackUser ? [fallbackUser.name] : []), + ]) + return { + node, + recipients, + routingFallbacks: unboundUsers.map((user) => ({ + originalUserId: user.id, + originalUserName: user.name, + fallbackUserId: fallbackUser!.id, + fallbackUserName: fallbackUser!.name, + })), + blockingReason: '', + } +} + +function firstEvaluated( + nodes: Array, + owners: string[][], + usersByName: ReadonlyMap, + fallbackUser: ActiveUser | null, +) { + for (let index = 0; index < nodes.length; index += 1) { + const evaluated = evaluateNode(nodes[index], owners[index] ?? [], usersByName, fallbackUser) + if (evaluated) return evaluated + } + return null +} + +async function planReplay() { + const allowedBarcodes = new Set( + (argumentValue('barcodes') ?? '') + .split(',') + .map((value) => value.trim().toUpperCase()) + .filter(Boolean), + ) + const rows = await prisma.productionStopDemand.findMany({ + where: { + confirmationStatus: 'PENDING', + confirmationStage: 0, + }, + select: { + id: true, + demandNo: true, + submittedAt: true, + confirmationVotes: { + select: { + approverId: true, + approverName: true, + decision: true, + confirmationStage: true, + }, + orderBy: [{ respondedAt: 'asc' }, { id: 'asc' }], + }, + items: { + select: { barcode: true }, + orderBy: { createdAt: 'asc' }, + }, + }, + orderBy: [{ submittedAt: 'asc' }, { demandNo: 'asc' }], + }) + const demands = allowedBarcodes.size + ? rows.filter((row) => row.items.some((item) => ( + allowedBarcodes.has(item.barcode.trim().toUpperCase()) + ))) + : rows + const barcodes = [...new Set(demands.flatMap((demand) => ( + demand.items.map((item) => item.barcode.trim().toUpperCase()).filter(Boolean) + )))] + const [liveOwners, shopOwners, workflowNodes, workCalendar] = await Promise.all([ + resolveProductionStopLiveRoutingOwnersByBarcodes(barcodes), + resolveSalesShopOwnersByBarcode(barcodes), + productionStopDemandRepository.listConfirmationWorkflowNodes(), + productionStopDemandRepository.listWorkCalendarDays(), + ]) + const activeNodes = workflowNodes.filter((node) => node.isActive) + const stageOneNode = activeNodes.find((node) => node.confirmerRole === 'OPS_DEPT_HEAD') ?? null + const stageTwoNode = activeNodes.find((node) => node.confirmerRole === 'OPS_DIRECTOR') ?? null + const stageThreeNode = activeNodes.find((node) => ( + node.confirmerRole === 'OTHER_SHOP_BUSINESS_UNIT_HEADS' + )) ?? null + const fallbackNode = activeNodes.find((node) => node.confirmerRole === 'FIXED_APPROVER') ?? null + const allOwnerNames = [...new Set(demands.flatMap((demand) => { + const names: string[] = [] + for (const item of demand.items) { + const barcode = item.barcode.trim().toUpperCase() + const live = liveOwners.get(barcode) + names.push( + ...(live?.opsDeptHead ?? []), + ...(live?.opsDirector ?? []), + ...(shopOwners.get(barcode) ?? []), + ) + } + if (fallbackNode?.fixedApproverName) names.push(fallbackNode.fixedApproverName) + return names + }))] + const users = await prisma.user.findMany({ + where: { + name: { in: allOwnerNames }, + status: 'ACTIVE', + }, + select: { + id: true, + name: true, + dingtalkUserId: true, + dingtalkUnionId: true, + }, + }) + const usersByName = new Map(users.map((user) => [normalizeName(user.name), user])) + const fallbackNames = uniqueNames([fallbackNode?.fixedApproverName ?? '']) + const fallbackUser = fallbackNames + .map((name) => usersByName.get(normalizeName(name))) + .find((user): user is ActiveUser => Boolean(user) && isDingtalkBound(user)) ?? null + const plans: DemandPlan[] = [] + + for (const demand of demands) { + const ownerNames = { + opsDeptHead: [] as string[], + opsDirector: [] as string[], + shopBusinessUnitHead: [] as string[], + fallback: fallbackNames, + } + for (const item of demand.items) { + const barcode = item.barcode.trim().toUpperCase() + const live = liveOwners.get(barcode) + ownerNames.opsDeptHead.push(...(live?.opsDeptHead ?? [])) + ownerNames.opsDirector.push(...(live?.opsDirector ?? [])) + ownerNames.shopBusinessUnitHead.push(...(shopOwners.get(barcode) ?? [])) + } + ownerNames.opsDeptHead = uniqueNames(ownerNames.opsDeptHead) + ownerNames.opsDirector = uniqueNames(ownerNames.opsDirector) + const directorSet = new Set(ownerNames.opsDirector.map(normalizeName)) + ownerNames.shopBusinessUnitHead = uniqueNames(ownerNames.shopBusinessUnitHead) + .filter((name) => !directorSet.has(normalizeName(name))) + + const votes = demand.confirmationVotes + const nonDirectorVotes = votes.filter((vote) => ( + !directorSet.has(normalizeName(vote.approverName)) + )) + const routeBranch = votes.length === 0 + ? 'ZERO_VOTE' as const + : nonDirectorVotes.length > 0 + ? 'NON_DIRECTOR_VOTE' as const + : 'DIRECTOR_VOTE' as const + + let selected: ReturnType = null + let reason = '' + let blockingReason = '' + if (routeBranch === 'ZERO_VOTE') { + selected = firstEvaluated( + [stageOneNode, stageTwoNode, stageThreeNode], + [ownerNames.opsDeptHead, ownerNames.opsDirector, ownerNames.shopBusinessUnitHead], + usersByName, + fallbackUser, + ) + if (!selected) { + if (fallbackUser && stageThreeNode) { + selected = { + node: stageThreeNode, + recipients: [fallbackUser.name], + routingFallbacks: [], + blockingReason: '', + } + reason = '历史票为0,一至三级均无有效负责人,推送兜底确认人' + } else { + blockingReason = '历史票为0,但一至三级和兜底均无可用确认人' + } + } else { + reason = `历史票为0,按一级→二级→三级选择 ${selected.node.name}` + } + } else if (routeBranch === 'NON_DIRECTOR_VOTE') { + selected = firstEvaluated( + [stageOneNode, stageTwoNode, stageThreeNode], + [ownerNames.opsDeptHead, ownerNames.opsDirector, ownerNames.shopBusinessUnitHead], + usersByName, + fallbackUser, + ) + if (selected) { + reason = `历史确认人包含非运营总负责人,按一级→二级→三级选择 ${selected.node.name}` + } else { + reason = '历史确认人包含非运营总负责人,一至三级均无有效确认人,直接进入已确认待走流程' + } + } else { + selected = evaluateNode( + stageThreeNode, + ownerNames.shopBusinessUnitHead, + usersByName, + fallbackUser, + ) + if (selected) { + reason = '历史确认票均来自运营总负责人,直接进入三级需求确认' + } else { + reason = '历史确认票均来自运营总负责人,三级无有效有销量店铺负责人,直接进入已确认待走流程' + } + } + + if (selected?.blockingReason) { + blockingReason = selected.blockingReason + selected = null + } + const targetNode = selected?.node ?? stageThreeNode + const targetStatus = selected ? 'PENDING' as const : 'AGREED' as const + const schedule = selected + ? resolveProductionStopConfirmationDeadlineDetails( + new Date(), + [{ timeNode: selected.node.timeNode, delayDays: selected.node.delayDays }], + workCalendar, + ) + : null + if (targetStatus === 'PENDING' && !selected?.recipients.length) { + blockingReason = blockingReason || `${selected?.node.name ?? '目标节点'}没有可推送确认人` + } + plans.push({ + demandId: demand.id, + demandNo: demand.demandNo, + barcodes: demand.items.map((item) => item.barcode), + existingVotes: votes, + ownerNames, + routeBranch, + targetNode: selected?.node.name ?? targetNode?.name ?? '', + targetStage: targetNode?.sortOrder ?? 0, + recipients: selected?.recipients ?? [], + routingFallbacks: selected?.routingFallbacks ?? [], + targetStatus, + targetDemandStatus: targetStatus === 'AGREED' + ? 'CONFIRMED_WAIT_FLOW' + : 'PENDING_CONFIRMATION', + targetDeadline: schedule?.deadline ? schedule.deadline.toISOString() : '', + targetDeadlineNote: schedule?.note ?? '', + reason, + blockingReason: targetStatus === 'PENDING' ? blockingReason : '', + }) + } + + return { plans, usersByName, fallbackUser } +} + +async function writeBackup(plans: readonly DemandPlan[]) { + const demandIds = plans.map((plan) => plan.demandId) + const [demands, votes, warnings, assignments] = await Promise.all([ + prisma.productionStopDemand.findMany({ where: { id: { in: demandIds } } }), + prisma.productionStopDemandConfirmationVote.findMany({ + where: { demandId: { in: demandIds } }, + }), + prisma.productionStopConfirmationWarning.findMany({ + where: { demandId: { in: demandIds } }, + }), + prisma.productionStopDemandConfirmationAssignment.findMany({ + where: { demandId: { in: demandIds } }, + }), + ]) + const backupPath = resolve( + argumentValue('backup') + ?? `.master-data-audits/production-stop-stage0-confirmation-replay-backup-${Date.now()}.json`, + ) + await mkdir(dirname(backupPath), { recursive: true }) + await writeFile(backupPath, JSON.stringify({ + generatedAt: new Date().toISOString(), + demandIds, + demands, + votes, + warnings, + assignments, + }, null, 2), 'utf8') + return backupPath +} + +async function applyPlans( + plans: readonly DemandPlan[], +): Promise { + const applicablePlans = plans.filter((plan) => !plan.blockingReason) + const allNames = [...new Set(applicablePlans.flatMap((plan) => [ + ...plan.recipients, + ...plan.routingFallbacks.flatMap((fallback) => [ + fallback.originalUserName, + fallback.fallbackUserName, + ]), + ]))] + const ensuredApprovers = allNames.length + ? await productionStopDemandRepository.ensureConfirmationApproversByUserNames(allNames) + : [] + const approverByName = new Map( + ensuredApprovers.map((approver) => [normalizeName(approver.userName), approver]), + ) + const now = new Date() + const result: ApplyResult = { + processed: 0, + pendingPushes: 0, + sent: 0, + failed: 0, + confirmedWaitFlow: 0, + failures: [], + } + const chunkSize = Math.max(1, Math.min(100, Number(argumentValue('batch-size') ?? 25))) + + for (let index = 0; index < applicablePlans.length; index += chunkSize) { + const chunk = applicablePlans.slice(index, index + chunkSize) + await prisma.$transaction(async (tx) => { + for (const plan of chunk) { + const updated = await tx.productionStopDemand.updateMany({ + where: { + id: plan.demandId, + confirmationStatus: 'PENDING', + confirmationStage: 0, + }, + data: { + confirmationStage: plan.targetStage, + confirmationStatus: plan.targetStatus, + confirmationAt: plan.targetStatus === 'AGREED' ? now : null, + confirmationReasons: '', + confirmationStageEnteredAt: now, + confirmationDeadline: plan.targetDeadline ? new Date(plan.targetDeadline) : null, + confirmationDeadlineNote: plan.targetDeadlineNote, + confirmationOverdueAt: null, + confirmationPushedAt: null, + confirmationPushMessage: '', + demandStatus: plan.targetDemandStatus, + demandStatusAt: now, + demandStatusNote: plan.targetStatus === 'AGREED' + ? '历史0级确认单按新规则完成确认,进入已确认待走流程' + : `历史0级确认单按新规则重路由至${plan.targetNode}`, + ...(plan.targetStatus === 'AGREED' ? { rejectionAt: null } : {}), + }, + }) + if (updated.count !== 1) { + throw new Error(`需求 ${plan.demandNo} 已不在待确认 stage=0,停止本批次`) + } + await tx.productionStopDemandConfirmationVote.deleteMany({ + where: { demandId: plan.demandId, confirmationStage: 0 }, + }) + await tx.productionStopConfirmationWarning.updateMany({ + where: { + demandId: plan.demandId, + status: { in: ['PENDING', 'PROCESSING', 'FAILED'] }, + }, + data: { + status: 'CANCELLED', + lastError: '原0级确认逻辑已清除,改按当前确认规则重跑', + }, + }) + await tx.productionStopDemandConfirmationAssignment.deleteMany({ + where: { demandId: plan.demandId }, + }) + for (const fallback of plan.routingFallbacks) { + const approver = approverByName.get(normalizeName(fallback.originalUserName)) + const fallbackApprover = approverByName.get(normalizeName(fallback.fallbackUserName)) + if (!approver || !fallbackApprover) { + throw new Error( + `需求 ${plan.demandNo} 缺少确认人映射:${fallback.originalUserName} → ${fallback.fallbackUserName}`, + ) + } + await tx.productionStopDemandConfirmationAssignment.create({ + data: { + demandId: plan.demandId, + approverId: approver.id, + approverUserId: approver.userId, + approverName: approver.userName, + proxyUserId: fallback.fallbackUserId, + proxyUserName: fallback.fallbackUserName, + source: 'ROUTING_FALLBACK', + }, + }) + } + } + }, { + maxWait: 15_000, + timeout: 120_000, + }) + + const pendingChunk = chunk.filter((plan) => plan.targetStatus === 'PENDING') + result.processed += chunk.length + result.confirmedWaitFlow += chunk.filter((plan) => plan.targetStatus === 'AGREED').length + result.pendingPushes += pendingChunk.length + if (pendingChunk.length) { + const notificationResult = await productionStopNotificationsService + .refreshDemandConfirmations(pendingChunk.map((plan) => plan.demandId)) + result.sent += notificationResult.sent + result.failed += notificationResult.failed + const message = notificationResult.failed + ? `新规则推送完成 ${notificationResult.sent} 人,失败 ${notificationResult.failed} 人` + : `已按新规则推送 ${notificationResult.sent} 人` + await prisma.productionStopDemand.updateMany({ + where: { id: { in: pendingChunk.map((plan) => plan.demandId) } }, + data: { + confirmationPushedAt: notificationResult.sent ? now : null, + confirmationPushMessage: message, + }, + }) + } + } + + await operationLogService.record({ + action: OperationLogAction.PRODUCTION_STOP_DEMAND_UPDATE, + status: OperationLogStatus.SUCCESS, + source: 'SYSTEM', + actorId: null, + actorName: '系统管理员', + workspaceCategory: '停产需求管理', + message: `历史0级待确认单按新规则重路由 ${result.processed} 条`, + details: { + mode: 'APPLY', + processed: result.processed, + pendingPushes: result.pendingPushes, + sent: result.sent, + failed: result.failed, + confirmedWaitFlow: result.confirmedWaitFlow, + }, + }) + return result +} + +async function main() { + const apply = process.argv.includes('--apply') + if (apply && argumentValue('confirm') !== APPLY_CONFIRMATION) { + throw new Error(`正式执行必须追加 --confirm=${APPLY_CONFIRMATION};未写入任何数据`) + } + const { plans, usersByName, fallbackUser } = await planReplay() + const blocking = plans.filter((plan) => plan.blockingReason) + const summary = { + mode: apply ? 'APPLY' : 'DRY_RUN', + scanned: plans.length, + byRouteBranch: Object.fromEntries( + ['ZERO_VOTE', 'NON_DIRECTOR_VOTE', 'DIRECTOR_VOTE'].map((branch) => [ + branch, + plans.filter((plan) => plan.routeBranch === branch).length, + ]), + ), + byTargetNode: Object.fromEntries( + [...new Set(plans.map((plan) => plan.targetNode || 'NO_RECIPIENT'))].map((node) => [ + node, + plans.filter((plan) => (plan.targetNode || 'NO_RECIPIENT') === node).length, + ]), + ), + pendingPushes: plans.filter((plan) => plan.targetStatus === 'PENDING').length, + confirmedWaitFlow: plans.filter((plan) => plan.targetStatus === 'AGREED').length, + routingFallbackAssignments: + plans.reduce((sum, plan) => sum + plan.routingFallbacks.length, 0), + totalTargetRecipients: plans.reduce((sum, plan) => sum + plan.recipients.length, 0), + maxRecipientsPerDemand: Math.max(0, ...plans.map((plan) => plan.recipients.length)), + missingSelectedDingtalk: + plans.flatMap((plan) => plan.recipients) + .map((name) => usersByName.get(normalizeName(name))) + .filter((user): user is ActiveUser => Boolean(user)) + .filter((user) => !isDingtalkBound(user)).length, + fallbackRecipientAvailable: Boolean(fallbackUser && isDingtalkBound(fallbackUser)), + blocked: blocking.length, + } + const outputPath = resolve( + argumentValue('output') + ?? (apply + ? '.master-data-audits/production-stop-stage0-confirmation-replay-apply.json' + : '.master-data-audits/production-stop-stage0-confirmation-replay-dry-run.json'), + ) + await mkdir(dirname(outputPath), { recursive: true }) + if (apply) { + if (blocking.length) { + throw new Error(`有 ${blocking.length} 条需求存在阻断原因,未写入任何数据`) + } + if (!productionStopNotificationsService.isEnabled()) { + throw new Error('通知中心未启用,未写入任何数据') + } + const backupPath = await writeBackup(plans) + const applyResult = await applyPlans(plans) + await writeFile(outputPath, JSON.stringify({ + summary: { ...summary, applyResult, backupPath }, + plans, + }, null, 2), 'utf8') + console.log(JSON.stringify({ + ...summary, + applyResult, + backupPath, + outputPath, + }, null, 2)) + return + } + await writeFile(outputPath, JSON.stringify({ summary, plans }, null, 2), 'utf8') + console.log(JSON.stringify({ ...summary, blockedSamples: blocking.slice(0, 20), outputPath }, null, 2)) +} + +main() + .catch((error) => { + console.error('[production-stop-stage0-replay] FAILED:', error) + process.exitCode = 1 + }) + .finally(async () => { + await prisma.$disconnect().catch(() => null) + await productionStopFlowRepository.close().catch(() => null) + await closeSupplyChainArchiveReadPool().catch(() => null) + }) diff --git a/furniture-3d-system/src/server/repositories/product-stop-detail.repository.ts b/furniture-3d-system/src/server/repositories/product-stop-detail.repository.ts index 1f9acf70..63a5bd0a 100644 --- a/furniture-3d-system/src/server/repositories/product-stop-detail.repository.ts +++ b/furniture-3d-system/src/server/repositories/product-stop-detail.repository.ts @@ -889,12 +889,7 @@ class ProductStopDetailRepository { SELECT * FROM shop_rows WHERE "sales30d" <> 0 - OR "sales30dWithBig" <> 0 OR "dailyRealPerformance" <> 0 - OR "grossMargin" <> 0 - OR "feeRatio" <> 0 - OR "afterSaleRatio" <> 0 - OR "dailyOperatingProfit" <> 0 ORDER BY "barcode", "platform", "shopName" `) } diff --git a/furniture-3d-system/src/server/repositories/production-stop-demands.repository.ts b/furniture-3d-system/src/server/repositories/production-stop-demands.repository.ts index 2ea0a3ba..32a60df9 100644 --- a/furniture-3d-system/src/server/repositories/production-stop-demands.repository.ts +++ b/furniture-3d-system/src/server/repositories/production-stop-demands.repository.ts @@ -306,7 +306,7 @@ export type ProductionStopConfirmationAssignmentRecord = { approverName: string proxyUserId: string proxyUserName: string - source: 'LEAVE' | 'WORK_CALENDAR' + source: 'LEAVE' | 'WORK_CALENDAR' | 'ROUTING_FALLBACK' } export type ProductionStopNewDemandNoticeRow = { @@ -2372,6 +2372,7 @@ class ProductionStopDemandRepositoryClass implements ProductionStopDemandReposit const rows = await prisma.productionStopDemand.findMany({ where: { confirmationStatus: 'PENDING', + confirmationStage: { gt: 0 }, ...(targets === undefined ? {} : { id: { in: targets } }), }, select: { @@ -2414,6 +2415,7 @@ class ProductionStopDemandRepositoryClass implements ProductionStopDemandReposit return prisma.productionStopDemand.findMany({ where: { confirmationStatus: 'PENDING', + confirmationStage: { gt: 0 }, confirmationOverdueAt: { not: null }, }, select: { id: true, demandNo: true }, @@ -3758,7 +3760,7 @@ class ProductionStopDemandRepositoryClass implements ProductionStopDemandReposit }) return rows.map((row) => ({ ...row, - source: row.source as 'LEAVE' | 'WORK_CALENDAR', + source: row.source as 'LEAVE' | 'WORK_CALENDAR' | 'ROUTING_FALLBACK', })) } diff --git a/furniture-3d-system/src/server/services/production-stop-notifications.service.test.ts b/furniture-3d-system/src/server/services/production-stop-notifications.service.test.ts index ed4c4665..87c979de 100644 --- a/furniture-3d-system/src/server/services/production-stop-notifications.service.test.ts +++ b/furniture-3d-system/src/server/services/production-stop-notifications.service.test.ts @@ -69,7 +69,7 @@ function createHarness(initialPending: DemandRef[] = []) { .filter((row) => !demandIds || demandIds.includes(row.id)) .map((row) => ({ barcodes: [], - confirmationStage: 0, + confirmationStage: 1, confirmationStageEnteredAt: null, confirmationDeadline: null, opsDeptHead: [], @@ -210,7 +210,7 @@ function createHarness(initialPending: DemandRef[] = []) { id: row.id, demandNo: row.demandNo, confirmationStatus: 'PENDING', - confirmationStage: row.confirmationStage ?? 0, + confirmationStage: row.confirmationStage ?? 1, confirmationDeadline: row.confirmationDeadline ?? null, } : null @@ -316,9 +316,9 @@ describe('停产需求通知中心编排', () => { { id: 'd1', demandNo: 'TC20261020-001', barcodes: ['A1'] }, { id: 'd2', demandNo: 'TC20261020-002', barcodes: ['A2'] }, ]) - harness.resolveDirectorNames.mockResolvedValue(new Map([ - ['A1', ['张三']], - ['A2', ['张三']], + harness.resolveRoutingOwners.mockResolvedValue(new Map([ + ['A1', { opsDeptHead: ['张三'], opsDirector: [] }], + ['A2', { opsDeptHead: ['张三'], opsDirector: [] }], ])) const first = await harness.service.refreshAll() @@ -350,9 +350,9 @@ describe('停产需求通知中心编排', () => { { id: 'a2', userId: 'u2', userName: '李四' }, { id: 'a3', userId: 'u3', userName: '王五' }, ]) - harness.resolveDirectorNames.mockResolvedValue(new Map([ - ['A1', ['张三']], - ['A2', ['李四']], + harness.resolveRoutingOwners.mockResolvedValue(new Map([ + ['A1', { opsDeptHead: ['张三'], opsDirector: [] }], + ['A2', { opsDeptHead: ['李四'], opsDirector: [] }], ])) const result = await harness.service.refreshAll() @@ -402,14 +402,15 @@ describe('停产需求通知中心编排', () => { id: 'd1', demandNo: 'TC20261020-001', barcodes: ['A1'], - confirmationStage: 0, confirmationStageEnteredAt: stageEnteredAt, confirmationDeadline: deadline, }]) harness.repository.listActiveApprovers.mockResolvedValue([ { id: 'a1', userId: 'u1', userName: '张三' }, ]) - harness.resolveDirectorNames.mockResolvedValue(new Map([['A1', ['张三']]])) + harness.resolveRoutingOwners.mockResolvedValue(new Map([ + ['A1', { opsDeptHead: ['张三'], opsDirector: [] }], + ])) await harness.service.refreshAll() @@ -439,9 +440,9 @@ describe('停产需求通知中心编排', () => { { id: 'a2', userId: 'u2', userName: '李四' }, { id: 'a3', userId: 'u3', userName: '王五' }, ]) - harness.resolveDirectorNames.mockResolvedValue(new Map([ - ['A1', ['张三']], - ['A2', []], + harness.resolveRoutingOwners.mockResolvedValue(new Map([ + ['A1', { opsDeptHead: ['张三'], opsDirector: [] }], + ['A2', { opsDeptHead: [], opsDirector: [] }], ])) await harness.service.refreshAll() @@ -456,9 +457,9 @@ describe('停产需求通知中心编排', () => { { id: 'd1', demandNo: 'TC20261020-001', barcodes: ['A1'] }, { id: 'd2', demandNo: 'TC20261020-002', barcodes: ['A2'] }, ]) - harness.resolveDirectorNames.mockResolvedValue(new Map([ - ['A1', ['张三']], - ['A2', ['张三']], + harness.resolveRoutingOwners.mockResolvedValue(new Map([ + ['A1', { opsDeptHead: ['张三'], opsDirector: [] }], + ['A2', { opsDeptHead: ['张三'], opsDirector: [] }], ])) const result = await harness.service.refreshDemandConfirmations(['d1']) @@ -475,11 +476,12 @@ describe('停产需求通知中心编排', () => { .toBe(true) }) - it('旧流程没有店铺负责人时按产品档案运营总负责人精确推送', async () => { + it('三级没有有销量店铺负责人时不回退运营总负责人', async () => { const harness = createHarness([{ id: 'd1', demandNo: 'TC20261020-001', barcodes: ['A1'], + confirmationStage: 3, }]) harness.repository.listActiveApprovers.mockResolvedValue([ { id: 'a1', userId: 'u1', userName: '张三' }, @@ -494,7 +496,7 @@ describe('停产需求通知中心编排', () => { await harness.service.refreshAll() - expect(harness.sends.map((send) => send.recipientAlias)).toEqual(['张三']) + expect(harness.sends).toEqual([]) }) it('一级和二级节点只推送当前节点实际负责人', async () => { @@ -539,7 +541,9 @@ describe('停产需求通知中心编排', () => { demandNo: 'TC20261020-001', barcodes: ['A1'], }]) - harness.resolveDirectorNames.mockResolvedValue(new Map([['A1', ['张三']]])) + harness.resolveRoutingOwners.mockResolvedValue(new Map([ + ['A1', { opsDeptHead: ['张三'], opsDirector: [] }], + ])) await harness.service.refreshAll() harness.setPending([]) @@ -620,7 +624,9 @@ describe('停产需求通知中心编排', () => { createdAt: new Date(), updatedAt: new Date(), }]) - harness.resolveDirectorNames.mockResolvedValue(new Map([['A1', ['张三']]])) + harness.resolveRoutingOwners.mockResolvedValue(new Map([ + ['A1', { opsDeptHead: ['张三'], opsDirector: [] }], + ])) await harness.service.refreshAll() @@ -771,7 +777,9 @@ describe('停产需求通知中心编排', () => { { id: 'a1', userId: 'u1', userName: '张三' }, ]) harness.repository.findUserDingtalkIds.mockResolvedValue(new Map([['u1', 'ding-user-1']])) - harness.resolveDirectorNames.mockResolvedValue(new Map([['A1', ['张三']]])) + harness.resolveRoutingOwners.mockResolvedValue(new Map([ + ['A1', { opsDeptHead: ['张三'], opsDirector: [] }], + ])) await harness.service.refreshAll() @@ -785,7 +793,9 @@ describe('停产需求通知中心编排', () => { demandNo: 'TC20261020-001', barcodes: ['A1'], }]) - harness.resolveDirectorNames.mockResolvedValue(new Map([['A1', ['张三']]])) + harness.resolveRoutingOwners.mockResolvedValue(new Map([ + ['A1', { opsDeptHead: ['张三'], opsDirector: [] }], + ])) harness.client.send.mockRejectedValueOnce(new Error('network down')) const failed = await harness.service.refreshAll() @@ -810,7 +820,7 @@ describe('停产需求通知中心编排', () => { id: 'warning-1', demandId: 'd1', demandNo: 'TC20261020-001', - confirmationStage: 0, + confirmationStage: 1, stageEnteredAt: new Date(), approverId: 'a1', approverUserId: 'u1', @@ -828,7 +838,7 @@ describe('停产需求通知中心编排', () => { id: 'd1', demandNo: 'TC20261020-001', confirmationStatus: 'PENDING', - confirmationStage: 0, + confirmationStage: 1, confirmationDeadline: null, }) @@ -847,7 +857,7 @@ describe('停产需求通知中心编排', () => { id: 'warning-2', demandId: 'd1', demandNo: 'TC20261020-001', - confirmationStage: 0, + confirmationStage: 1, stageEnteredAt: new Date(), approverId: 'a1', approverUserId: 'u1', @@ -867,7 +877,7 @@ describe('停产需求通知中心编排', () => { approverUserId: 'u1', approverName: '张三', decision: 'AGREED', - confirmationStage: 0, + confirmationStage: 1, rejectionCategory: '', reason: '', source: 'USER', @@ -881,7 +891,7 @@ describe('停产需求通知中心编排', () => { id: 'warning-3', demandId: 'd1', demandNo: 'TC20261020-001', - confirmationStage: 0, + confirmationStage: 1, stageEnteredAt: new Date(), approverId: 'a1', approverUserId: 'u1', @@ -899,7 +909,7 @@ describe('停产需求通知中心编排', () => { id: 'd1', demandNo: 'TC20261020-001', confirmationStatus: 'PENDING', - confirmationStage: 0, + confirmationStage: 1, confirmationDeadline: new Date(), confirmationOverdueAt: new Date(), }) diff --git a/furniture-3d-system/src/server/services/production-stop-notifications.service.ts b/furniture-3d-system/src/server/services/production-stop-notifications.service.ts index 3993f153..e41ab403 100644 --- a/furniture-3d-system/src/server/services/production-stop-notifications.service.ts +++ b/furniture-3d-system/src/server/services/production-stop-notifications.service.ts @@ -16,7 +16,6 @@ import { type ProductionStopNewDemandRecipientType, type ProductionStopPendingNotificationKind, } from '@/lib/production-stop-notifications' -import { resolveProductionStopConfirmationApprovers } from '@/lib/production-stop-confirmation-routing' import { excludeConfirmedApproversFromFinalStage, resolveProductionStopConfirmationNodeApprovers, @@ -234,7 +233,7 @@ export class ProductionStopNotificationsService { const currentProxyByOriginalUser = new Map() if (kind === 'CONFIRM_PENDING') { const calendarAssignments = @@ -342,7 +341,7 @@ export class ProductionStopNotificationsService { approverName: string proxyUserId: string proxyUserName: string - source: 'LEAVE' | 'WORK_CALENDAR' + source: 'LEAVE' | 'WORK_CALENDAR' | 'ROUTING_FALLBACK' }> = [] const warningUpserts: Promise[] = [] for (const demand of pendingDemands) { @@ -353,15 +352,12 @@ export class ProductionStopNotificationsService { const directorNames = (demand.barcodes ?? []).flatMap((barcode) => ( directorsByBarcode.get(barcode.trim().toUpperCase()) ?? [] )) - const legacyDirectorNames = [ - ...directorNames, - ...liveOwners.flatMap((owner) => owner.opsDirector), - ] const everyBarcodeMatched = (demand.barcodes?.length ?? 0) > 0 && liveOwners.length === demand.barcodes.length const node = demand.confirmationStage > 0 ? workflowNodeByStage.get(demand.confirmationStage) : null + if (!node) continue const stageOwners = { opsDeptHead: [...new Set([ ...liveOwners.flatMap((owner) => owner.opsDeptHead), @@ -373,20 +369,17 @@ export class ProductionStopNotificationsService { ])], shopBusinessUnitHead: directorNames, } - const stageNames = node - ? resolveProductionStopConfirmationRoutingNames( - node.confirmerRole, - stageOwners, - fixedApproverName, - ) - : [] + const stageNames = resolveProductionStopConfirmationRoutingNames( + node.confirmerRole, + stageOwners, + fixedApproverName, + ) const ensuredStageApprovers = stageNames.length ? await this.repository.ensureConfirmationApproversByUserNames(stageNames) : [] for (const approver of ensuredStageApprovers) { if (!recipientMap.has(approver.id)) recipientMap.set(approver.id, approver) } - const baseRecipients = originalRecipients const stageRecipients = [...new Map( [...ensuredStageApprovers, ...originalRecipients].map((recipient) => [ recipient.id, @@ -403,26 +396,19 @@ export class ProductionStopNotificationsService { routedStageOwners = { ...stageOwners, opsDeptHead: stageNames } } } - const routedRecipients = node - ? resolveProductionStopConfirmationNodeApprovers( - stageRecipients, - node.confirmerRole, - routedStageOwners, - ) - : resolveProductionStopConfirmationApprovers( - baseRecipients, - legacyDirectorNames, - ) - const finalStageRecipients = node - ? excludeConfirmedApproversFromFinalStage({ - approvers: routedRecipients, - stage: node.sortOrder, - finalStage: finalConfirmationStage ?? node.sortOrder, - confirmerRole: node.confirmerRole, - votes: [...(agreedApproverIdsByDemand.get(demand.id) ?? [])] - .map((approverId) => ({ approverId, decision: 'AGREED' as const })), - }) - : routedRecipients + const routedRecipients = resolveProductionStopConfirmationNodeApprovers( + stageRecipients, + node.confirmerRole, + routedStageOwners, + ) + const finalStageRecipients = excludeConfirmedApproversFromFinalStage({ + approvers: routedRecipients, + stage: node.sortOrder, + finalStage: finalConfirmationStage ?? node.sortOrder, + confirmerRole: node.confirmerRole, + votes: [...(agreedApproverIdsByDemand.get(demand.id) ?? [])] + .map((approverId) => ({ approverId, decision: 'AGREED' as const })), + }) for (const originalRecipient of finalStageRecipients) { if (voteStageApproverKeys.has( `${demand.id}:${demand.confirmationStage}:${originalRecipient.id}`, @@ -451,7 +437,7 @@ export class ProductionStopNotificationsService { userName: proxyUserName, } : originalRecipient - const stageName = node?.name ?? `第${demand.confirmationStage}级需求确认` + const stageName = node.name const deadlineText = demand.confirmationDeadline ? REMINDER_DEADLINE_FORMATTER.format(demand.confirmationDeadline) : '' @@ -668,6 +654,11 @@ export class ProductionStopNotificationsService { ) { const client = this.createClient() if (!client) return { sent: 0, failed: 0, cancelled: 0 } + const activeStages = new Set( + (await this.repository.listConfirmationWorkflowNodes()) + .filter((node) => node.isActive) + .map((node) => node.sortOrder), + ) const warnings = await this.repository.claimDueConfirmationWarnings( now, limit, @@ -681,6 +672,11 @@ export class ProductionStopNotificationsService { let failed = 0 let cancelled = 0 for (const warning of warnings) { + if (warning.confirmationStage <= 0 || !activeStages.has(warning.confirmationStage)) { + await this.repository.cancelConfirmationWarning(warning.id) + cancelled += 1 + continue + } if (warning.warningType !== 'TIMEOUT') { const demand = await this.repository.findDemandById(warning.demandId) const votes = await this.repository.listConfirmationVotes(warning.demandId)