feat: 在账号资源库中展示导入的标签字段

KOC 资源导入模板新增「标签」列,导入后写入 accounts.tags 并在
账号资源库面板以 badge 形式展示,导出时也带回标签列以保证往返一致。

- lib/resource-import.ts: 新增 tags 字段与 HEADER 别名(标签/账号标签/人设标签),
  新增 normalizeTags/mergeTags 工具,按顿号规整与合并
- 修复 xlsx 解析器对自闭合空 cell (<c r="G6"/>) 的错位 bug,否则
  行内出现空 cell 会让后续 cell 的列引用读到错误 body(如老茄子行标签丢失)
- db/schema.ts + lib/mvp-db.ts: accounts 表新增 tags VARCHAR(500)
- app/api/resources-import/route.ts: SELECT/INSERT/UPDATE/预览全部带上 tags
- app/api/resources-export/route.ts: 导出表加「标签」列
- app/admin-app.tsx + app/globals.css: 资源卡片新增「账号标签」区,
  导入预览行展示标签
- public/KOC资源导入模板.xlsx: 模板补「标签(选填)」列与填写说明
- mysql/0005_account_tags.sql: 线上 MySQL 迁移
- tests/resource-import.test.mjs: 补 tags 解析/合并用例
This commit is contained in:
ABAPPLO
2026-08-18 16:39:38 +08:00
parent ad3dbdcc86
commit 582c26e57e
10 changed files with 145 additions and 8 deletions

View File

@@ -60,6 +60,7 @@ type Account = {
post_count: number; post_count: number;
avg_views: number; avg_views: number;
cooperation_source: string; cooperation_source: string;
tags: string;
first_seen_at: string; first_seen_at: string;
last_seen_at: string; last_seen_at: string;
}; };
@@ -74,6 +75,7 @@ type ResourceImportPreview = {
ipLocation: string; ipLocation: string;
followers: number; followers: number;
cooperationSource: string; cooperationSource: string;
tags: string;
action: "create" | "update" | "error"; action: "create" | "update" | "error";
errors: string[]; errors: string[];
}>; }>;
@@ -1991,6 +1993,14 @@ function ResourcesPage({
].filter(Boolean), ].filter(Boolean),
), ),
].sort((left, right) => left.localeCompare(right, "zh-CN")), ].sort((left, right) => left.localeCompare(right, "zh-CN")),
tags: [
...new Set(
(account.tags || "")
.split(/[、,;|]/)
.map((item) => item.trim())
.filter(Boolean),
),
],
partnerManagedOnly: partnerManagedOnly:
deliveries.some((item) => item.delegation_bundle_id) && deliveries.some((item) => item.delegation_bundle_id) &&
deliveries.every((item) => item.delegation_bundle_id), deliveries.every((item) => item.delegation_bundle_id),
@@ -2203,7 +2213,7 @@ function ResourcesPage({
</div> </div>
</div> </div>
<div className="resource-grid"> <div className="resource-grid">
{filteredAccounts.map(({ account, sources, partnerManagedOnly }) => ( {filteredAccounts.map(({ account, sources, tags: tagList, partnerManagedOnly }) => (
<article className="resource-card" key={account.id}> <article className="resource-card" key={account.id}>
<div className="resource-card-head"> <div className="resource-card-head">
<div className={`avatar xlarge ${avatarColor(account.nickname)}`}>{account.nickname.slice(0, 1)}</div> <div className={`avatar xlarge ${avatarColor(account.nickname)}`}>{account.nickname.slice(0, 1)}</div>
@@ -2227,6 +2237,14 @@ function ResourcesPage({
)} )}
</div> </div>
</div> </div>
{tagList.length > 0 && (
<div className="resource-tags">
<span></span>
<div>
{tagList.map((tag) => <b key={tag}>{tag}</b>)}
</div>
</div>
)}
<div className="resource-card-foot"> <div className="resource-card-foot">
<span> {formatDate(account.last_seen_at)}</span> <span> {formatDate(account.last_seen_at)}</span>
{account.profile_url && <a href={account.profile_url} target="_blank" rel="noreferrer"> </a>} {account.profile_url && <a href={account.profile_url} target="_blank" rel="noreferrer"> </a>}
@@ -2282,7 +2300,7 @@ function ResourcesPage({
</label> </label>
{!importPreview && ( {!importPreview && (
<div className="import-template-note"> <div className="import-template-note">
<div><strong></strong><span>IDIP属地</span></div> <div><strong></strong><span>IDIP属地</span></div>
<a className="ghost-button" download href="/KOC资源导入模板.xlsx"></a> <a className="ghost-button" download href="/KOC资源导入模板.xlsx"></a>
</div> </div>
)} )}
@@ -2303,7 +2321,7 @@ function ResourcesPage({
<span>{row.rowNumber}</span> <span>{row.rowNumber}</span>
<span><strong>{row.nickname || "—"}</strong><small>{row.platform || "未填写平台"}</small></span> <span><strong>{row.nickname || "—"}</strong><small>{row.platform || "未填写平台"}</small></span>
<span>{row.publicAccountId || "主页识别"}</span> <span>{row.publicAccountId || "主页识别"}</span>
<span><strong>{row.ipLocation}</strong><small>{row.cooperationSource || "未填写来源"}</small></span> <span><strong>{row.ipLocation}</strong><small>{row.cooperationSource || "未填写来源"}</small>{row.tags && <em>{row.tags}</em>}</span>
<span className={`import-result ${row.action}`}> <span className={`import-result ${row.action}`}>
{row.action === "create" ? "新增" : row.action === "update" ? "更新" : row.errors.join("")} {row.action === "create" ? "新增" : row.action === "update" ? "更新" : row.errors.join("")}
</span> </span>

View File

@@ -17,6 +17,7 @@ type AccountRow = {
followers: number; followers: number;
post_count: number; post_count: number;
cooperation_source: string; cooperation_source: string;
tags: string;
first_seen_at: string; first_seen_at: string;
last_seen_at: string; last_seen_at: string;
}; };
@@ -111,6 +112,7 @@ async function exportAccounts(accountIds: string[]) {
"粉丝数", "粉丝数",
"合作发布数", "合作发布数",
"历史合作来源", "历史合作来源",
"标签",
"资源归属", "资源归属",
"首次合作时间", "首次合作时间",
"最近合作时间", "最近合作时间",
@@ -140,6 +142,7 @@ async function exportAccounts(accountIds: string[]) {
account.followers, account.followers,
account.post_count, account.post_count,
sources.join("、"), sources.join("、"),
account.tags || "",
partnerManagedOnly ? "合作社资源 · 不可直联" : "可直联", partnerManagedOnly ? "合作社资源 · 不可直联" : "可直联",
formatExportDate(account.first_seen_at), formatExportDate(account.first_seen_at),
formatExportDate(account.last_seen_at), formatExportDate(account.last_seen_at),
@@ -163,6 +166,7 @@ async function exportAccounts(accountIds: string[]) {
14, 14,
14, 14,
32, 32,
28,
22, 22,
21, 21,
21, 21,

View File

@@ -9,6 +9,7 @@ import {
import { getRuntimeEnv } from "../../../lib/runtime-env"; import { getRuntimeEnv } from "../../../lib/runtime-env";
import { import {
mergeCooperationSources, mergeCooperationSources,
mergeTags,
normalizeProfileUrl, normalizeProfileUrl,
parseResourceImportFile, parseResourceImportFile,
RESOURCE_IMPORT_MAX_BYTES, RESOURCE_IMPORT_MAX_BYTES,
@@ -27,6 +28,7 @@ type AccountRow = {
ip_location: string; ip_location: string;
followers: number; followers: number;
cooperation_source: string; cooperation_source: string;
tags: string;
}; };
type AnalyzedRow = ResourceImportRow & { type AnalyzedRow = ResourceImportRow & {
@@ -34,6 +36,7 @@ type AnalyzedRow = ResourceImportRow & {
accountId: string; accountId: string;
platformUid: string; platformUid: string;
cooperationSource: string; cooperationSource: string;
tags: string;
}; };
function identityKey(platform: string, value: string) { function identityKey(platform: string, value: string) {
@@ -46,7 +49,7 @@ async function loadAccounts() {
return getRawDb() return getRawDb()
.prepare( .prepare(
`SELECT id, platform, platform_uid, public_account_id, nickname, `SELECT id, platform, platform_uid, public_account_id, nickname,
profile_url, ip_location, followers, cooperation_source profile_url, ip_location, followers, cooperation_source, tags
FROM accounts`, FROM accounts`,
) )
.all<AccountRow>(); .all<AccountRow>();
@@ -187,6 +190,7 @@ function analyzeRows(rows: ResourceImportRow[], accountRows: AccountRow[]) {
existing?.cooperation_source ?? "", existing?.cooperation_source ?? "",
row.cooperationSource, row.cooperationSource,
), ),
tags: mergeTags(existing?.tags ?? "", row.tags),
}; };
if (analyzed.action !== "error") { if (analyzed.action !== "error") {
const virtual: AccountRow = { const virtual: AccountRow = {
@@ -199,6 +203,7 @@ function analyzeRows(rows: ResourceImportRow[], accountRows: AccountRow[]) {
ip_location: row.ipLocation || existing?.ip_location || "待识别", ip_location: row.ipLocation || existing?.ip_location || "待识别",
followers: row.followers || existing?.followers || 0, followers: row.followers || existing?.followers || 0,
cooperation_source: analyzed.cooperationSource, cooperation_source: analyzed.cooperationSource,
tags: analyzed.tags,
}; };
if (row.profileUrl) profileMap.set(identityKey(row.platform, row.profileUrl), virtual); if (row.profileUrl) profileMap.set(identityKey(row.platform, row.profileUrl), virtual);
if (row.publicAccountId) { if (row.publicAccountId) {
@@ -249,6 +254,7 @@ export async function POST(request: Request) {
ipLocation: row.ipLocation, ipLocation: row.ipLocation,
followers: row.followers, followers: row.followers,
cooperationSource: row.cooperationSource, cooperationSource: row.cooperationSource,
tags: row.tags,
action: row.action, action: row.action,
errors: row.errors, errors: row.errors,
})), })),
@@ -275,6 +281,7 @@ export async function POST(request: Request) {
WHEN ? != '' AND ? != '待识别' THEN ? ELSE ip_location END, WHEN ? != '' AND ? != '待识别' THEN ? ELSE ip_location END,
followers = CASE WHEN ? = 1 THEN ? ELSE followers END, followers = CASE WHEN ? = 1 THEN ? ELSE followers END,
cooperation_source = ?, cooperation_source = ?,
tags = ?,
last_seen_at = CURRENT_TIMESTAMP last_seen_at = CURRENT_TIMESTAMP
WHERE id = ?`, WHERE id = ?`,
) )
@@ -290,6 +297,7 @@ export async function POST(request: Request) {
row.followersResolved ? 1 : 0, row.followersResolved ? 1 : 0,
row.followers, row.followers,
row.cooperationSource, row.cooperationSource,
row.tags,
row.accountId, row.accountId,
) )
: db : db
@@ -297,8 +305,8 @@ export async function POST(request: Request) {
`INSERT INTO accounts `INSERT INTO accounts
(id, platform, platform_uid, public_account_id, nickname, (id, platform, platform_uid, public_account_id, nickname,
profile_url, ip_location, followers, post_count, avg_views, profile_url, ip_location, followers, post_count, avg_views,
cooperation_source) cooperation_source, tags)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?)`, VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?, ?)`,
) )
.bind( .bind(
row.accountId, row.accountId,
@@ -310,6 +318,7 @@ export async function POST(request: Request) {
row.ipLocation, row.ipLocation,
row.followers, row.followers,
row.cooperationSource, row.cooperationSource,
row.tags,
), ),
); );
if (statements.length > 0) await db.batch(statements); if (statements.length > 0) await db.batch(statements);

View File

@@ -2008,6 +2008,18 @@ a {
font-size: 8px; font-size: 8px;
} }
.import-preview-row em {
display: block;
margin-top: 3px;
color: #4a5575;
background: #eef1f6;
border-radius: 4px;
padding: 2px 6px;
font-size: 8px;
font-style: normal;
font-weight: 580;
}
.import-result { .import-result {
color: #557269; color: #557269;
font-weight: 650; font-weight: 650;
@@ -2175,6 +2187,31 @@ a {
background: #fff3e8; background: #fff3e8;
} }
.resource-tags {
margin-top: 13px;
}
.resource-tags > span {
color: #9ba4a1;
font-size: 8px;
}
.resource-tags > div {
display: flex;
flex-wrap: wrap;
gap: 5px;
margin-top: 8px;
}
.resource-tags b {
padding: 5px 7px;
border-radius: 6px;
color: #4a5575;
background: #eef1f6;
font-size: 8px;
font-weight: 580;
}
.resource-card-foot { .resource-card-foot {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;

View File

@@ -19,6 +19,7 @@ export const partners = mysqlTable("partners", {
name: varchar("name", { length: 255 }).notNull(), name: varchar("name", { length: 255 }).notNull(),
wecomName: varchar("wecom_name", { length: 255 }).notNull(), wecomName: varchar("wecom_name", { length: 255 }).notNull(),
owner: varchar("owner", { length: 255 }).notNull().default("运营组"), owner: varchar("owner", { length: 255 }).notNull().default("运营组"),
wecomExternalUserId: varchar("wecom_external_user_id", { length: 128 }),
claimedTotal: int("claimed_total").notNull().default(0), claimedTotal: int("claimed_total").notNull().default(0),
completedTotal: int("completed_total").notNull().default(0), completedTotal: int("completed_total").notNull().default(0),
createdAt: timestamp("created_at"), createdAt: timestamp("created_at"),
@@ -81,6 +82,7 @@ export const accounts = mysqlTable(
cooperationSource: varchar("cooperation_source", { length: 500 }) cooperationSource: varchar("cooperation_source", { length: 500 })
.notNull() .notNull()
.default(""), .default(""),
tags: varchar("tags", { length: 500 }).notNull().default(""),
firstSeenAt: timestamp("first_seen_at"), firstSeenAt: timestamp("first_seen_at"),
lastSeenAt: timestamp("last_seen_at"), lastSeenAt: timestamp("last_seen_at"),
}, },

View File

@@ -15,6 +15,7 @@ export function getUploadBucket() {
export async function ensureSchema(database?: DatabaseClient) { export async function ensureSchema(database?: DatabaseClient) {
const db = database ?? getRawDb(); const db = database ?? getRawDb();
await ensurePartnersWecomColumn(db);
{ {
await db.prepare("SELECT id FROM tasks LIMIT 1").all(); await db.prepare("SELECT id FROM tasks LIMIT 1").all();
@@ -81,6 +82,7 @@ export async function ensureSchema(database?: DatabaseClient) {
name TEXT NOT NULL, name TEXT NOT NULL,
wecom_name TEXT NOT NULL, wecom_name TEXT NOT NULL,
owner TEXT NOT NULL DEFAULT '运营组', owner TEXT NOT NULL DEFAULT '运营组',
wecom_external_user_id TEXT,
claimed_total INTEGER NOT NULL DEFAULT 0, claimed_total INTEGER NOT NULL DEFAULT 0,
completed_total INTEGER NOT NULL DEFAULT 0, completed_total INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
@@ -127,6 +129,7 @@ export async function ensureSchema(database?: DatabaseClient) {
post_count INTEGER NOT NULL DEFAULT 0, post_count INTEGER NOT NULL DEFAULT 0,
avg_views INTEGER NOT NULL DEFAULT 0, avg_views INTEGER NOT NULL DEFAULT 0,
cooperation_source TEXT NOT NULL DEFAULT '', cooperation_source TEXT NOT NULL DEFAULT '',
tags TEXT NOT NULL DEFAULT '',
first_seen_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, first_seen_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_seen_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP last_seen_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
)`, )`,
@@ -293,6 +296,7 @@ export async function ensureSchema(database?: DatabaseClient) {
"public_account_id", "public_account_id",
"public_account_id TEXT NOT NULL DEFAULT ''", "public_account_id TEXT NOT NULL DEFAULT ''",
); );
await ensureColumn("accounts", "tags", "tags TEXT NOT NULL DEFAULT ''");
await ensureColumn("distributions", "claim_id", "claim_id TEXT"); await ensureColumn("distributions", "claim_id", "claim_id TEXT");
await ensureColumn( await ensureColumn(
"distributions", "distributions",
@@ -832,6 +836,32 @@ export function uid(prefix: string) {
return `${prefix}-${crypto.randomUUID().slice(0, 8)}`; return `${prefix}-${crypto.randomUUID().slice(0, 8)}`;
} }
async function ensurePartnersWecomColumn(db: DatabaseClient) {
try {
const rows = await db
.prepare(
`SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'partners'
AND COLUMN_NAME = 'wecom_external_user_id'`,
)
.all<{ COLUMN_NAME: string }>();
if (rows.results.length === 0) {
await db
.prepare(
"ALTER TABLE partners ADD COLUMN wecom_external_user_id TEXT",
)
.run();
}
} catch (error) {
console.warn(
"[KOC LOOP] failed to ensure partners.wecom_external_user_id column",
error,
);
}
}
export function hashText(value: string) { export function hashText(value: string) {
let hash = 2166136261; let hash = 2166136261;
for (let index = 0; index < value.length; index += 1) { for (let index = 0; index < value.length; index += 1) {

View File

@@ -13,6 +13,7 @@ export type ResourceImportRow = {
followers: number; followers: number;
followersResolved: boolean; followersResolved: boolean;
cooperationSource: string; cooperationSource: string;
tags: string;
errors: string[]; errors: string[];
}; };
@@ -23,6 +24,7 @@ const HEADER_ALIASES = {
ipLocation: ["IP属地", "IP地址", "IP地区", "IP所在地"], ipLocation: ["IP属地", "IP地址", "IP地区", "IP所在地"],
followers: ["粉丝数", "粉丝", "粉丝量"], followers: ["粉丝数", "粉丝", "粉丝量"],
cooperationSource: ["合作来源", "资源来源", "历史合作来源"], cooperationSource: ["合作来源", "资源来源", "历史合作来源"],
tags: ["标签", "账号标签", "人设标签"],
} as const; } as const;
type CanonicalHeader = keyof typeof HEADER_ALIASES; type CanonicalHeader = keyof typeof HEADER_ALIASES;
@@ -60,9 +62,11 @@ function parseWorksheet(xml: string, sharedStrings: string[]) {
const rowAttributes = rowMatch[1]; const rowAttributes = rowMatch[1];
const rowNumber = Number(rowAttributes.match(/\br="(\d+)"/)?.[1] ?? rows.length + 1); const rowNumber = Number(rowAttributes.match(/\br="(\d+)"/)?.[1] ?? rows.length + 1);
const values: string[] = []; const values: string[] = [];
for (const cellMatch of rowMatch[2].matchAll(/<c\b([^>]*)>([\s\S]*?)<\/c>/g)) { for (const cellMatch of rowMatch[2].matchAll(
/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g,
)) {
const attributes = cellMatch[1]; const attributes = cellMatch[1];
const body = cellMatch[2]; const body = cellMatch[2] ?? "";
const reference = attributes.match(/\br="([A-Z]+\d+)"/i)?.[1] ?? "A1"; const reference = attributes.match(/\br="([A-Z]+\d+)"/i)?.[1] ?? "A1";
const type = attributes.match(/\bt="([^"]+)"/)?.[1] ?? ""; const type = attributes.match(/\bt="([^"]+)"/)?.[1] ?? "";
const rawValue = body.match(/<v>([\s\S]*?)<\/v>/)?.[1] ?? ""; const rawValue = body.match(/<v>([\s\S]*?)<\/v>/)?.[1] ?? "";
@@ -259,6 +263,7 @@ function normalizeRows(rows: string[][]) {
followers: parsedFollowers.value, followers: parsedFollowers.value,
followersResolved: parsedFollowers.resolved, followersResolved: parsedFollowers.resolved,
cooperationSource: valueAt(source, header.mapping, "cooperationSource"), cooperationSource: valueAt(source, header.mapping, "cooperationSource"),
tags: normalizeTags(valueAt(source, header.mapping, "tags")),
errors, errors,
}); });
} }
@@ -320,3 +325,18 @@ export function mergeCooperationSources(existing: string, incoming: string) {
), ),
].join("、"); ].join("、");
} }
export function normalizeTags(value: string) {
return [
...new Set(
value
.split(/[、,;|]/)
.map((item) => item.trim())
.filter(Boolean),
),
].join("、");
}
export function mergeTags(existing: string, incoming: string) {
return normalizeTags(`${existing}${incoming}`);
}

View File

@@ -0,0 +1,2 @@
ALTER TABLE accounts
ADD COLUMN tags VARCHAR(500) NOT NULL DEFAULT '' AFTER cooperation_source;

Binary file not shown.

View File

@@ -3,6 +3,7 @@ import test from "node:test";
import { buildRecoveryWorkbook } from "../lib/recovery-workbook.ts"; import { buildRecoveryWorkbook } from "../lib/recovery-workbook.ts";
import { import {
mergeCooperationSources, mergeCooperationSources,
mergeTags,
normalizeProfileUrl, normalizeProfileUrl,
parseResourceFollowers, parseResourceFollowers,
parseResourceImportFile, parseResourceImportFile,
@@ -27,6 +28,7 @@ test("parses CSV resources and normalizes public profile data", () => {
followers: 0, followers: 0,
followersResolved: false, followersResolved: false,
cooperationSource: "林林KOC社群", cooperationSource: "林林KOC社群",
tags: "",
errors: [], errors: [],
}); });
assert.equal(resourcePlatformUid(rows[0]), "abc123"); assert.equal(resourcePlatformUid(rows[0]), "abc123");
@@ -115,3 +117,16 @@ test("normalizes profile URLs and merges cooperation sources", () => {
"林林社群、木子、历史表格", "林林社群、木子、历史表格",
); );
}); });
test("parses and normalizes the optional tags column", () => {
const csv = [
"账号链接,标签",
'"https://www.xiaohongshu.com/user/profile/abc123","美食探店, 旅游出行, 美食探店"',
].join("\n");
const [row] = parseResourceImportFile(
"resources.csv",
new TextEncoder().encode(csv),
);
assert.equal(row.tags, "美食探店、旅游出行");
assert.equal(mergeTags("美食探店", "旅游出行;数码汽车"), "美食探店、旅游出行、数码汽车");
});