feat: 任务模型物理合并,发布+回收并为单任务双阶段

- tasks 新增 recovery_enabled/recovery_due_at/recovery_instructions/recovery_example_images,回收挂自己名下(先发布后交截图),不再置 complete
- 存量 screenshot_collect 迁移并入父任务后删除(mysql/0020 含 DELETE,生产执行前务必备份)
- 新 action task_enable_recovery:ghost 面板一键开通回收,截止默认=发布截止
- 企微催办双阶段(待发布/截图待提交);超期自动释放仅发布阶段
- admin 删 groupTaskMasters 聚合改单卡双面板;portal 详情页回收截图区块+批次回收进度
- 测试 309 全绿 + Playwright E2E 20/20
This commit is contained in:
ABAPPLO
2026-09-24 15:52:45 +08:00
parent ab78b187c0
commit e2a93e22cf
29 changed files with 2219 additions and 2195 deletions

View File

@@ -15,17 +15,13 @@ export type CreateDistributionTaskInput = {
contentFormat?: "image_text" | "video";
projectId?: string;
ownerUserid?: string;
recoveryEnabled?: boolean;
recoveryDueAt?: string;
recoveryInstructions?: string;
recoveryExampleImageKey?: string;
};
export type CreateScreenshotTaskInput = {
name: string;
relatedTaskId: string;
dueAt: string;
instructions: string;
exampleImageKey?: string;
projectId?: string;
ownerUserid?: string;
};
;
export type DistributionTaskCreation = {
created: boolean;
@@ -42,16 +38,7 @@ export type DistributionTaskCreation = {
contentFormat: "image_text" | "video";
};
export type ScreenshotTaskCreation = {
created: true;
taskId: string;
shareToken: string;
name: string;
brand: string;
dueAt: string;
quantity: number;
relatedTaskId: string;
};
type TaskRow = {
id: string;
@@ -133,9 +120,25 @@ async function findExistingTask(
.first<TaskRow>();
}
type RecoveryConfig = {
enabled: boolean;
dueAt: string;
instructions: string;
exampleImages: string;
};
function recoveryExampleImagesJson(exampleImageKey: string) {
return exampleImageKey.startsWith("task-assets/")
? JSON.stringify([
{ index: 1, key: exampleImageKey, width: null, height: null },
])
: "[]";
}
async function insertTaskFromSource(
source: FeishuSource,
input: CreateDistributionTaskInput,
recovery: RecoveryConfig,
) {
const db = getRawDb();
const taskId = uid("task");
@@ -146,8 +149,10 @@ async function insertTaskFromSource(
(id, name, brand, quantity, claimed_quantity, due_at, status,
platform, content_format, project_id, owner_userid,
source_url, source_sheet_id, source_sheet_name, source_synced_at,
share_token, join_qr_code)
VALUES (?, ?, ?, ?, 0, ?, 'importing', ?, ?, ?, ?, ?, ?, ?, ?, ?, '')`,
share_token, join_qr_code,
recovery_enabled, recovery_due_at, recovery_instructions, recovery_example_images)
VALUES (?, ?, ?, ?, 0, ?, 'importing', ?, ?, ?, ?, ?, ?, ?, ?, ?, '',
?, ?, ?, ?)`,
)
.bind(
taskId,
@@ -164,6 +169,10 @@ async function insertTaskFromSource(
source.sheetName,
source.syncedAt,
shareToken,
recovery.enabled ? 1 : 0,
recovery.dueAt,
recovery.instructions,
recovery.exampleImages,
)
.run();
@@ -228,6 +237,10 @@ export async function createDistributionTask(
contentFormat: rawInput.contentFormat === "video" ? "video" : "image_text",
projectId: normalizedValue(rawInput.projectId ?? ""),
ownerUserid: normalizedValue(rawInput.ownerUserid ?? "").slice(0, 64),
recoveryEnabled: rawInput.recoveryEnabled !== false,
recoveryDueAt: normalizedValue(rawInput.recoveryDueAt ?? ""),
recoveryInstructions: normalizedValue(rawInput.recoveryInstructions ?? ""),
recoveryExampleImageKey: normalizedValue(rawInput.recoveryExampleImageKey ?? ""),
};
if (!input.feishuUrl || !input.name || !input.brand) {
throw new Error("请补全飞书链接、任务名称和品牌/项目");
@@ -260,7 +273,17 @@ export async function createDistributionTask(
) {
throw new Error("视频任务中存在未识别到视频的内容行,请检查飞书“视频”列");
}
const inserted = await insertTaskFromSource(source, input);
const recoveryDueAt = normalizedValue(rawInput.recoveryDueAt ?? "");
const inserted = await insertTaskFromSource(source, input, {
enabled: rawInput.recoveryEnabled !== false,
dueAt: recoveryDueAt ? normalizedDueDate(recoveryDueAt) : input.dueAt,
instructions:
normalizedValue(rawInput.recoveryInstructions ?? "") ||
"请提交发布后的笔记截图",
exampleImages: recoveryExampleImagesJson(
normalizedValue(rawInput.recoveryExampleImageKey ?? ""),
),
});
return {
created: true,
taskId: inserted.taskId,
@@ -277,141 +300,6 @@ export async function createDistributionTask(
};
}
type ScreenshotSourceTaskRow = {
id: string;
name: string;
brand: string;
quantity: number;
project_id: string;
owner_userid: string;
task_type: "content_publish" | "screenshot_collect";
};
type ScreenshotSourceContentRow = {
id: string;
title: string;
source_row: number | null;
};
export async function createScreenshotTask(
rawInput: CreateScreenshotTaskInput,
): Promise<ScreenshotTaskCreation> {
await ensureSchema();
const input = {
name: normalizedValue(rawInput.name),
relatedTaskId: normalizedValue(rawInput.relatedTaskId),
dueAt: normalizedDueDate(rawInput.dueAt),
instructions: normalizedValue(rawInput.instructions),
exampleImageKey: normalizedValue(rawInput.exampleImageKey ?? ""),
projectId: normalizedValue(rawInput.projectId ?? ""),
ownerUserid: normalizedValue(rawInput.ownerUserid ?? "").slice(0, 64),
};
if (!input.name || !input.relatedTaskId || !input.instructions) {
throw new Error("请补全任务名称、关联分发任务和任务说明");
}
if (input.exampleImageKey && !input.exampleImageKey.startsWith("task-assets/")) {
throw new Error("示例截图无效,请重新上传");
}
const db = getRawDb();
const source = await db
.prepare(
`SELECT id, name, brand, quantity, project_id, owner_userid, task_type
FROM tasks WHERE id = ?`,
)
.bind(input.relatedTaskId)
.first<ScreenshotSourceTaskRow>();
if (!source) throw new Error("关联的分发任务不存在");
if (source.task_type !== "content_publish") {
throw new Error("请选择内容发布类型的分发任务");
}
const existing = await db
.prepare("SELECT id FROM tasks WHERE related_task_id = ?")
.bind(input.relatedTaskId)
.first<{ id: string }>();
if (existing) throw new Error("该分发任务已有关联回收任务");
const sourceContents = await db
.prepare(
"SELECT id, title, source_row FROM contents WHERE task_id = ? ORDER BY source_row, id",
)
.bind(input.relatedTaskId)
.all<ScreenshotSourceContentRow>();
if (sourceContents.results.length === 0) {
throw new Error("分发任务还没有可回收的笔记");
}
const taskId = uid("task");
const shareToken = crypto.randomUUID().replaceAll("-", "");
const imageAssets = input.exampleImageKey
? JSON.stringify([
{ index: 1, key: input.exampleImageKey, width: null, height: null },
])
: "[]";
const projectId = input.projectId || source.project_id;
const ownerUserid = input.ownerUserid || source.owner_userid;
await db
.prepare(
`INSERT INTO tasks
(id, name, brand, quantity, claimed_quantity, due_at, status,
task_type, project_id, owner_userid, source_url, source_sheet_id, source_sheet_name,
share_token, collection_days, join_qr_code, related_task_id)
VALUES (?, ?, ?, ?, 0, ?, 'active', 'screenshot_collect', ?, ?, '', '', '', ?, '[]', '', ?)`,
)
.bind(
taskId,
input.name,
source.brand,
sourceContents.results.length,
input.dueAt,
projectId,
ownerUserid,
shareToken,
input.relatedTaskId,
)
.run();
try {
const statements = sourceContents.results.map((row) =>
db
.prepare(
`INSERT INTO contents
(id, task_id, title, body, image_assets, video_assets, status, source, source_row, related_content_id)
VALUES (?, ?, ?, ?, ?, '[]', 'available', '截图回收任务', ?, ?)`,
)
.bind(
uid("content"),
taskId,
row.title,
input.instructions,
imageAssets,
row.source_row,
row.id,
),
);
for (let index = 0; index < statements.length; index += 100) {
await db.batch(statements.slice(index, index + 100));
}
} catch (error) {
await db.batch([
db.prepare("DELETE FROM contents WHERE task_id = ?").bind(taskId),
db.prepare("DELETE FROM tasks WHERE id = ?").bind(taskId),
]);
throw error;
}
return {
created: true,
taskId,
shareToken,
name: input.name,
brand: source.brand,
dueAt: input.dueAt,
quantity: sourceContents.results.length,
relatedTaskId: input.relatedTaskId,
};
}
export type UpdateTaskInput = {
taskId: string;
name: string;
@@ -420,10 +308,10 @@ export type UpdateTaskInput = {
projectId?: string;
platform?: "小红书" | "抖音";
contentFormat?: "image_text" | "video";
quantity?: number;
keyword?: string;
instructions?: string;
exampleImageKey?: string;
recoveryEnabled?: boolean;
recoveryDueAt?: string;
recoveryInstructions?: string;
recoveryExampleImageKey?: string;
};
export type TaskUpdateResult = {
@@ -434,79 +322,16 @@ export type TaskUpdateResult = {
type UpdatableTaskRow = {
id: string;
task_type: "content_publish" | "screenshot_collect";
quantity: number;
claimed_quantity: number;
platform: "小红书" | "抖音";
content_format: "image_text" | "video";
related_task_id: string;
recovery_enabled: number;
recovery_due_at: string;
recovery_instructions: string | null;
recovery_example_images: string;
};
// 截图任务的 keyword/instructions 存在 contents 每行(title/body),数量与行数一一对应
async function syncScreenshotContents(
db: DatabaseClient,
taskId: string,
params: {
oldQuantity: number;
quantity: number;
keyword: string;
instructions: string;
exampleImageKey: string;
},
) {
const delta = params.quantity - params.oldQuantity;
if (delta > 0) {
const sample = await db
.prepare(
"SELECT image_assets FROM contents WHERE task_id = ? ORDER BY source_row LIMIT 1",
)
.bind(taskId)
.first<{ image_assets: string }>();
const imageAssets = sample?.image_assets ?? "[]";
const statements = Array.from({ length: delta }, (_, index) =>
db
.prepare(
`INSERT INTO contents
(id, task_id, title, body, image_assets, video_assets, status, source, source_row)
VALUES (?, ?, ?, ?, ?, '[]', 'available', '截图回收任务', ?)`,
)
.bind(
uid("content"),
taskId,
params.keyword,
params.instructions,
imageAssets,
params.oldQuantity + index + 1,
),
);
for (let index = 0; index < statements.length; index += 100) {
await db.batch(statements.slice(index, index + 100));
}
} else if (delta < 0) {
// 只删未领取的尾部行,已领取(claimed)的保留
await db
.prepare(
`DELETE FROM contents WHERE task_id = ? AND status = 'available'
ORDER BY source_row DESC LIMIT ?`,
)
.bind(taskId, -delta)
.run();
}
await db
.prepare("UPDATE contents SET title = ?, body = ? WHERE task_id = ?")
.bind(params.keyword, params.instructions, taskId)
.run();
if (params.exampleImageKey.startsWith("task-assets/")) {
const imageAssets = JSON.stringify([
{ index: 1, key: params.exampleImageKey, width: null, height: null },
]);
await db
.prepare("UPDATE contents SET image_assets = ? WHERE task_id = ?")
.bind(imageAssets, taskId)
.run();
}
}
export async function updateTask(
rawInput: UpdateTaskInput,
db: DatabaseClient = getRawDb(),
@@ -524,10 +349,7 @@ export async function updateTask(
contentFormat: rawInput.contentFormat === "video" || rawInput.contentFormat === "image_text"
? rawInput.contentFormat
: undefined,
quantity: Math.floor(Number(rawInput.quantity ?? 0)),
keyword: normalizedValue(rawInput.keyword ?? ""),
instructions: normalizedValue(rawInput.instructions ?? ""),
exampleImageKey: normalizedValue(rawInput.exampleImageKey ?? ""),
recoveryExampleImageKey: normalizedValue(rawInput.recoveryExampleImageKey ?? ""),
};
if (!input.name || !input.brand) {
throw new Error("请补全任务名称和品牌");
@@ -535,81 +357,41 @@ export async function updateTask(
const row = await db
.prepare(
"SELECT id, task_type, quantity, claimed_quantity, platform, content_format, related_task_id FROM tasks WHERE id = ?",
`SELECT id, quantity, claimed_quantity, platform, content_format,
recovery_enabled, recovery_due_at, recovery_instructions, recovery_example_images
FROM tasks WHERE id = ?`,
)
.bind(taskId)
.first<UpdatableTaskRow>();
if (!row) throw new Error("任务不存在");
const quantity = Number(row.quantity);
const claimed = Number(row.claimed_quantity);
let quantity = Number(row.quantity);
if (row.task_type === "screenshot_collect") {
const related = Boolean(row.related_task_id);
if (!input.instructions) {
throw new Error(related ? "请补全任务说明" : "请补全搜索关键词和任务说明");
}
if (related) {
if (
rawInput.quantity !== undefined &&
rawInput.quantity !== null &&
input.quantity !== quantity
) {
throw new Error("关联任务的份数由分发任务决定,不可修改");
}
if (input.keyword) {
const firstTitle = await db
.prepare(
"SELECT title FROM contents WHERE task_id = ? ORDER BY source_row, id LIMIT 1",
)
.bind(taskId)
.first<{ title: string }>();
if (firstTitle && input.keyword !== firstTitle.title) {
throw new Error("关联任务的搜索关键词由分发任务笔记决定,不可修改");
}
}
await db
.prepare("UPDATE contents SET body = ? WHERE task_id = ?")
.bind(input.instructions, taskId)
.run();
if (input.exampleImageKey.startsWith("task-assets/")) {
const imageAssets = JSON.stringify([
{ index: 1, key: input.exampleImageKey, width: null, height: null },
]);
await db
.prepare("UPDATE contents SET image_assets = ? WHERE task_id = ?")
.bind(imageAssets, taskId)
.run();
}
} else {
if (!input.keyword) {
throw new Error("请补全搜索关键词和任务说明");
}
if (
!Number.isInteger(input.quantity) ||
input.quantity < 1 ||
input.quantity > 500
) {
throw new Error("任务数量需为 1—500 份");
}
if (input.quantity < claimed) {
throw new Error(`任务数量不能低于已领取的 ${claimed} 份`);
}
quantity = input.quantity;
await syncScreenshotContents(db, taskId, {
oldQuantity: Number(row.quantity),
quantity,
keyword: input.keyword,
instructions: input.instructions,
exampleImageKey: input.exampleImageKey,
});
}
}
const recoveryEnabled =
rawInput.recoveryEnabled === undefined
? row.recovery_enabled
: rawInput.recoveryEnabled
? 1
: 0;
const recoveryDueAtInput = normalizedValue(rawInput.recoveryDueAt ?? "");
const recoveryDueAt = recoveryDueAtInput
? normalizedDueDate(recoveryDueAtInput)
: row.recovery_due_at || input.dueAt;
const recoveryInstructions =
normalizedValue(rawInput.recoveryInstructions ?? "") ||
row.recovery_instructions ||
"";
const recoveryExampleImages = input.recoveryExampleImageKey
? recoveryExampleImagesJson(input.recoveryExampleImageKey)
: row.recovery_example_images;
await db
.prepare(
`UPDATE tasks
SET name = ?, brand = ?, due_at = ?, project_id = ?,
platform = ?, content_format = ?, quantity = ?
platform = ?, content_format = ?, quantity = ?,
recovery_enabled = ?, recovery_due_at = ?, recovery_instructions = ?,
recovery_example_images = ?
WHERE id = ?`,
)
.bind(
@@ -620,6 +402,10 @@ export async function updateTask(
input.platform ?? row.platform,
input.contentFormat ?? row.content_format,
quantity,
recoveryEnabled,
recoveryDueAt,
recoveryInstructions,
recoveryExampleImages,
taskId,
)
.run();
@@ -628,6 +414,52 @@ export async function updateTask(
return { taskId, quantity, claimedQuantity: claimed };
}
export type EnableRecoveryInput = {
taskId: string;
recoveryDueAt?: string;
recoveryInstructions?: string;
recoveryExampleImageKey?: string;
};
export async function enableTaskRecovery(
rawInput: EnableRecoveryInput,
db: DatabaseClient = getRawDb(),
): Promise<{ taskId: string; recoveryDueAt: string }> {
const taskId = normalizedValue(rawInput.taskId);
if (!taskId) throw new Error("缺少 taskId");
const row = await db
.prepare(
"SELECT id, due_at, recovery_example_images FROM tasks WHERE id = ?",
)
.bind(taskId)
.first<{
id: string;
due_at: string;
recovery_example_images: string;
}>();
if (!row) throw new Error("任务不存在");
const dueAtInput = normalizedValue(rawInput.recoveryDueAt ?? "");
const dueAt = dueAtInput ? normalizedDueDate(dueAtInput) : row.due_at;
const exampleImageKey = normalizedValue(rawInput.recoveryExampleImageKey ?? "");
await db
.prepare(
`UPDATE tasks SET recovery_enabled = 1, recovery_due_at = ?,
recovery_instructions = ?, recovery_example_images = ?
WHERE id = ?`,
)
.bind(
dueAt,
normalizedValue(rawInput.recoveryInstructions ?? "") ||
"请提交发布后的笔记截图",
exampleImageKey
? recoveryExampleImagesJson(exampleImageKey)
: row.recovery_example_images,
taskId,
)
.run();
return { taskId, recoveryDueAt: dueAt };
}
export function buildClaimUrl(portalOrigin: string, shareToken: string) {
const origin = normalizedValue(portalOrigin).replace(/\/$/, "");
if (!origin) throw new Error("KOC 领取站点地址尚未配置");
@@ -638,32 +470,29 @@ export function buildClaimUrl(portalOrigin: string, shareToken: string) {
type TaskStatusRow = {
id: string;
task_type: "content_publish" | "screenshot_collect";
status: string;
};
type DistributionProgressRow = {
total: number;
complete_count: number;
submitted_count: number;
};
// 纯重算任务状态:条件满足置 completed,不满足回 active(释放重开等场景);
// importing 是导入中间态,不参与推导
// importing 是导入中间态,不参与推导。完成判定取发布阶段口径(complete_count)
export async function refreshTaskStatus(
taskId: string,
db: DatabaseClient = getRawDb(),
): Promise<string> {
const row = await db
.prepare("SELECT id, task_type, status FROM tasks WHERE id = ?")
.prepare("SELECT id, status FROM tasks WHERE id = ?")
.bind(taskId)
.first<TaskStatusRow>();
if (!row || row.status === "importing") return row?.status ?? "";
const progress = await db
.prepare(
`SELECT COUNT(*) AS total,
COALESCE(SUM(CASE WHEN status = 'complete' THEN 1 ELSE 0 END), 0) AS complete_count,
COALESCE(SUM(CASE WHEN result_submitted_at IS NOT NULL THEN 1 ELSE 0 END), 0) AS submitted_count
COALESCE(SUM(CASE WHEN status = 'complete' THEN 1 ELSE 0 END), 0) AS complete_count
FROM distributions WHERE task_id = ?`,
)
.bind(taskId)
@@ -676,13 +505,10 @@ export async function refreshTaskStatus(
.first<{ available_count: number }>();
const total = Number(progress?.total ?? 0);
const availableCount = Number(available?.available_count ?? 0);
let completed = false;
if (total > 0 && availableCount === 0) {
completed =
row.task_type === "screenshot_collect"
? Number(progress?.submitted_count ?? 0) === total
: Number(progress?.complete_count ?? 0) === total;
}
const completed =
total > 0 &&
availableCount === 0 &&
Number(progress?.complete_count ?? 0) === total;
const next = completed ? "completed" : "active";
if (next !== row.status) {
await db