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:
@@ -4,7 +4,6 @@ import { refreshTaskStatus } from "./task-service";
|
||||
type ReleasableDistribution = {
|
||||
id: string;
|
||||
task_id: string;
|
||||
task_type: string;
|
||||
content_id: string;
|
||||
content_title: string;
|
||||
partner_id: string;
|
||||
@@ -28,7 +27,6 @@ export class DistributionReleaseError extends Error {
|
||||
export function distributionReleaseBlockReason(input: {
|
||||
publishUrl?: string | null;
|
||||
resultSubmittedAt?: string | null;
|
||||
taskType?: string | null;
|
||||
}) {
|
||||
if (input.publishUrl) return "已回填发布链接的笔记不能释放";
|
||||
if (input.resultSubmittedAt) return "已提交结果截图的任务不能释放";
|
||||
@@ -49,7 +47,6 @@ export async function releaseUnfinishedDistribution(
|
||||
`SELECT
|
||||
d.id,
|
||||
d.task_id,
|
||||
t.task_type,
|
||||
d.content_id,
|
||||
c.title AS content_title,
|
||||
d.partner_id,
|
||||
@@ -74,7 +71,6 @@ export async function releaseUnfinishedDistribution(
|
||||
const blocked = distributionReleaseBlockReason({
|
||||
publishUrl: distribution.publish_url,
|
||||
resultSubmittedAt: distribution.result_submitted_at,
|
||||
taskType: distribution.task_type,
|
||||
});
|
||||
if (blocked) throw new DistributionReleaseError(blocked, 409);
|
||||
|
||||
|
||||
@@ -871,21 +871,12 @@ export async function getDashboardData(ownerUserid?: string) {
|
||||
(SELECT c.body FROM contents c WHERE c.task_id = t.id ORDER BY c.source_row LIMIT 1) AS instructions,
|
||||
(SELECT COUNT(*) FROM distributions d WHERE d.task_id = t.id) AS dist_total,
|
||||
(SELECT COUNT(*) FROM distributions d WHERE d.task_id = t.id AND d.status = 'complete') AS dist_complete,
|
||||
(SELECT COUNT(*) FROM distributions d WHERE d.task_id = t.id AND d.result_submitted_at IS NOT NULL) AS dist_submitted,
|
||||
(SELECT rt.name FROM tasks rt WHERE rt.id = t.related_task_id) AS related_task_name,
|
||||
(SELECT COUNT(*) FROM distributions d WHERE d.task_id = t.related_task_id) AS related_dist_total,
|
||||
(SELECT COUNT(*) FROM distributions d WHERE d.task_id = t.related_task_id AND d.status = 'complete') AS related_dist_complete,
|
||||
(SELECT rt2.id FROM tasks rt2 WHERE rt2.related_task_id = t.id LIMIT 1) AS reverse_related_task_id,
|
||||
(SELECT rt2.name FROM tasks rt2 WHERE rt2.related_task_id = t.id LIMIT 1) AS reverse_related_task_name,
|
||||
(SELECT COUNT(*) FROM distributions d WHERE d.task_id = (SELECT rt2.id FROM tasks rt2 WHERE rt2.related_task_id = t.id LIMIT 1)) AS reverse_dist_total,
|
||||
(SELECT COUNT(*) FROM distributions d WHERE d.task_id = (SELECT rt2.id FROM tasks rt2 WHERE rt2.related_task_id = t.id LIMIT 1) AND d.result_submitted_at IS NOT NULL) AS reverse_dist_submitted
|
||||
(SELECT COUNT(*) FROM distributions d WHERE d.task_id = t.id AND d.result_submitted_at IS NOT NULL) AS dist_submitted
|
||||
FROM tasks t
|
||||
LEFT JOIN projects pj ON pj.id = t.project_id`;
|
||||
const distributionsBase = `SELECT
|
||||
d.*,
|
||||
c.title AS content_title,
|
||||
c.related_content_id AS related_content_id,
|
||||
rc.title AS related_content_title,
|
||||
p.name AS partner_name,
|
||||
cl.claimant_name AS claimant_name,
|
||||
a.nickname AS account_nickname,
|
||||
@@ -898,7 +889,6 @@ export async function getDashboardData(ownerUserid?: string) {
|
||||
t.due_at AS due_at
|
||||
FROM distributions d
|
||||
JOIN contents c ON c.id = d.content_id
|
||||
LEFT JOIN contents rc ON rc.id = c.related_content_id
|
||||
JOIN partners p ON p.id = d.partner_id
|
||||
LEFT JOIN claims cl ON cl.id = d.claim_id
|
||||
JOIN tasks t ON t.id = d.task_id
|
||||
|
||||
@@ -58,12 +58,7 @@ export function buildProjectAppMessage(
|
||||
const portal = text(portalUrl).replace(/\/$/, "");
|
||||
const claimUrl =
|
||||
portal && task.share_token ? `${portal}/?task=${task.share_token}` : "";
|
||||
const formatLabel =
|
||||
task.task_type === "screenshot_collect"
|
||||
? "截图回收"
|
||||
: task.content_format === "video"
|
||||
? "视频"
|
||||
: "图文";
|
||||
const formatLabel = task.content_format === "video" ? "视频" : "图文";
|
||||
return [
|
||||
`【项目任务】${task.name}`,
|
||||
`品牌:${task.brand}|数量:${task.quantity} 份|截止:${task.due_at}`,
|
||||
|
||||
@@ -17,7 +17,6 @@ export type ProjectRow = {
|
||||
main_group_member_ids: string;
|
||||
owner_userid: string;
|
||||
main_chat_id: string;
|
||||
parent_id: string;
|
||||
status: string;
|
||||
note: string;
|
||||
created_at: string;
|
||||
@@ -33,7 +32,6 @@ export type ProjectSummary = {
|
||||
mainGroupMemberIds: string[];
|
||||
ownerUserid: string;
|
||||
mainChatId: string;
|
||||
parentProjectId: string;
|
||||
taskCount: number;
|
||||
};
|
||||
|
||||
@@ -51,16 +49,9 @@ export type ProjectTaskRow = {
|
||||
share_token: string | null;
|
||||
owner_userid: string;
|
||||
task_chat_id: string;
|
||||
project_name?: string;
|
||||
};
|
||||
|
||||
export type ProjectSubproject = {
|
||||
id: string;
|
||||
name: string;
|
||||
brand: string;
|
||||
ownerUserid: string;
|
||||
mainChatId: string;
|
||||
taskCount: number;
|
||||
recovery_enabled: number;
|
||||
recovery_due_at: string;
|
||||
recovery_submitted: number;
|
||||
};
|
||||
|
||||
export type ProjectMainChat = {
|
||||
@@ -72,8 +63,6 @@ export type ProjectDetail = {
|
||||
project: ProjectSummary;
|
||||
tasks: ProjectTaskRow[];
|
||||
mainChat: ProjectMainChat;
|
||||
subprojects: ProjectSubproject[];
|
||||
pushTasks: ProjectTaskRow[];
|
||||
};
|
||||
|
||||
export type MainChatEnsureReason =
|
||||
@@ -238,59 +227,6 @@ export async function ensureProjectMainChat(
|
||||
}
|
||||
}
|
||||
|
||||
async function loadProjectParents(
|
||||
db: DatabaseClient,
|
||||
): Promise<Map<string, string>> {
|
||||
const result = await db
|
||||
.prepare("SELECT id, parent_id FROM projects")
|
||||
.all<{ id: string; parent_id: string }>();
|
||||
return new Map(result.results.map((row) => [row.id, text(row.parent_id)]));
|
||||
}
|
||||
|
||||
// candidate 是否位于 ancestor 的子孙链上(沿 candidate 的祖先链向上找 ancestor)
|
||||
function isDescendantProject(
|
||||
parents: Map<string, string>,
|
||||
ancestorId: string,
|
||||
candidateId: string,
|
||||
): boolean {
|
||||
let current = candidateId;
|
||||
const seen = new Set<string>();
|
||||
while (current) {
|
||||
if (current === ancestorId) return true;
|
||||
if (seen.has(current)) return false;
|
||||
seen.add(current);
|
||||
current = parents.get(current) ?? "";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function collectDescendantIds(
|
||||
db: DatabaseClient,
|
||||
projectId: string,
|
||||
): Promise<string[]> {
|
||||
const parents = await loadProjectParents(db);
|
||||
const childrenOf = new Map<string, string[]>();
|
||||
for (const [id, parent] of parents) {
|
||||
if (!parent) continue;
|
||||
const list = childrenOf.get(parent) ?? [];
|
||||
list.push(id);
|
||||
childrenOf.set(parent, list);
|
||||
}
|
||||
const descendants: string[] = [];
|
||||
const queue = [text(projectId)];
|
||||
const visited = new Set(queue);
|
||||
while (queue.length > 0) {
|
||||
const current = queue.shift() as string;
|
||||
for (const child of childrenOf.get(current) ?? []) {
|
||||
if (visited.has(child)) continue;
|
||||
visited.add(child);
|
||||
descendants.push(child);
|
||||
queue.push(child);
|
||||
}
|
||||
}
|
||||
return descendants;
|
||||
}
|
||||
|
||||
export async function listProjects(
|
||||
db: DatabaseClient,
|
||||
ownerUserid?: string,
|
||||
@@ -303,7 +239,7 @@ export async function listProjects(
|
||||
const result = await (ownerFilter
|
||||
? db
|
||||
.prepare(
|
||||
`SELECT p.id, p.name, p.brand, p.main_group_member_ids, p.owner_userid, p.main_chat_id, p.parent_id, p.status, p.note, p.created_at,
|
||||
`SELECT p.id, p.name, p.brand, p.main_group_member_ids, p.owner_userid, p.main_chat_id, p.status, p.note, p.created_at,
|
||||
(SELECT COUNT(*) FROM tasks t WHERE t.project_id = p.id) AS task_count
|
||||
FROM projects p
|
||||
WHERE p.owner_userid = ?
|
||||
@@ -312,7 +248,7 @@ export async function listProjects(
|
||||
.bind(ownerFilter)
|
||||
: db
|
||||
.prepare(
|
||||
`SELECT p.id, p.name, p.brand, p.main_group_member_ids, p.owner_userid, p.main_chat_id, p.parent_id, p.status, p.note, p.created_at,
|
||||
`SELECT p.id, p.name, p.brand, p.main_group_member_ids, p.owner_userid, p.main_chat_id, p.status, p.note, p.created_at,
|
||||
(SELECT COUNT(*) FROM tasks t WHERE t.project_id = p.id) AS task_count
|
||||
FROM projects p
|
||||
ORDER BY p.created_at DESC`,
|
||||
@@ -328,7 +264,6 @@ export async function listProjects(
|
||||
mainGroupMemberIds: parseJsonArray(row.main_group_member_ids),
|
||||
ownerUserid: row.owner_userid ?? "",
|
||||
mainChatId: row.main_chat_id ?? "",
|
||||
parentProjectId: row.parent_id ?? "",
|
||||
taskCount: Number(row.task_count),
|
||||
}));
|
||||
}
|
||||
@@ -340,7 +275,7 @@ export async function getProjectDetail(
|
||||
const id = text(projectId);
|
||||
const project = await db
|
||||
.prepare(
|
||||
`SELECT id, name, brand, main_group_member_ids, owner_userid, main_chat_id, parent_id, status, note, created_at
|
||||
`SELECT id, name, brand, main_group_member_ids, owner_userid, main_chat_id, status, note, created_at
|
||||
FROM projects WHERE id = ?`,
|
||||
)
|
||||
.bind(id)
|
||||
@@ -350,38 +285,13 @@ export async function getProjectDetail(
|
||||
const tasks = await db
|
||||
.prepare(
|
||||
`SELECT id, name, brand, quantity, claimed_quantity, due_at, status,
|
||||
task_type, platform, content_format, share_token, owner_userid, task_chat_id
|
||||
FROM tasks WHERE project_id = ?
|
||||
ORDER BY created_at DESC`,
|
||||
)
|
||||
.bind(id)
|
||||
.all<ProjectTaskRow>();
|
||||
|
||||
const subprojects = await db
|
||||
.prepare(
|
||||
`SELECT p.id, p.name, p.brand, p.owner_userid, p.main_chat_id,
|
||||
(SELECT COUNT(*) FROM tasks t WHERE t.project_id = p.id) AS task_count
|
||||
FROM projects p
|
||||
WHERE p.parent_id = ?
|
||||
ORDER BY p.created_at DESC`,
|
||||
)
|
||||
.bind(id)
|
||||
.all<ProjectRow & { task_count: number }>();
|
||||
|
||||
const descendantIds = await collectDescendantIds(db, id);
|
||||
const pushIds = [id, ...descendantIds];
|
||||
const placeholders = pushIds.map(() => "?").join(", ");
|
||||
const pushTasks = await db
|
||||
.prepare(
|
||||
`SELECT t.id, t.name, t.brand, t.quantity, t.claimed_quantity, t.due_at, t.status,
|
||||
t.task_type, t.platform, t.content_format, t.share_token, t.owner_userid, t.task_chat_id,
|
||||
pj.name AS project_name
|
||||
FROM tasks t
|
||||
LEFT JOIN projects pj ON pj.id = t.project_id
|
||||
WHERE t.project_id IN (${placeholders})
|
||||
task_type, platform, content_format, share_token, owner_userid, task_chat_id,
|
||||
recovery_enabled, recovery_due_at,
|
||||
(SELECT COUNT(*) FROM distributions d WHERE d.task_id = t.id AND d.result_submitted_at IS NOT NULL) AS recovery_submitted
|
||||
FROM tasks t WHERE t.project_id = ?
|
||||
ORDER BY t.created_at DESC`,
|
||||
)
|
||||
.bind(...pushIds)
|
||||
.bind(id)
|
||||
.all<ProjectTaskRow>();
|
||||
|
||||
return {
|
||||
@@ -395,7 +305,6 @@ export async function getProjectDetail(
|
||||
mainGroupMemberIds: parseJsonArray(project.main_group_member_ids),
|
||||
ownerUserid: project.owner_userid ?? "",
|
||||
mainChatId: project.main_chat_id ?? "",
|
||||
parentProjectId: project.parent_id ?? "",
|
||||
taskCount: tasks.results.length,
|
||||
},
|
||||
tasks: tasks.results,
|
||||
@@ -406,15 +315,6 @@ export async function getProjectDetail(
|
||||
project.owner_userid,
|
||||
),
|
||||
},
|
||||
subprojects: subprojects.results.map((row) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
brand: row.brand,
|
||||
ownerUserid: row.owner_userid ?? "",
|
||||
mainChatId: row.main_chat_id ?? "",
|
||||
taskCount: Number(row.task_count),
|
||||
})),
|
||||
pushTasks: pushTasks.results,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -425,7 +325,6 @@ export type SaveProjectInput = {
|
||||
mainGroupMemberIds?: unknown;
|
||||
ownerUserid?: unknown;
|
||||
note?: unknown;
|
||||
parentProjectId?: unknown;
|
||||
};
|
||||
|
||||
export async function saveProject(
|
||||
@@ -439,33 +338,19 @@ export async function saveProject(
|
||||
const brand = text(input.brand);
|
||||
const note = text(input.note ?? "");
|
||||
const ownerUserid = text(input.ownerUserid).slice(0, 64);
|
||||
const parentProjectId = text(input.parentProjectId);
|
||||
const memberIds = effectiveProjectMembers(input.mainGroupMemberIds, ownerUserid);
|
||||
if (!name) throw new ProjectError("请填写项目名称");
|
||||
|
||||
if (parentProjectId) {
|
||||
if (parentProjectId === id) {
|
||||
throw new ProjectError("上级项目不能是项目自身");
|
||||
}
|
||||
const parents = await loadProjectParents(db);
|
||||
if (!parents.has(parentProjectId)) {
|
||||
throw new ProjectError("上级项目不存在", 404);
|
||||
}
|
||||
if (id && isDescendantProject(parents, id, parentProjectId)) {
|
||||
throw new ProjectError("上级项目不能是当前项目的子项目");
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
let projectId = id;
|
||||
if (id) {
|
||||
const result = await db
|
||||
.prepare(
|
||||
`UPDATE projects
|
||||
SET name = ?, brand = ?, main_group_member_ids = ?, owner_userid = ?, note = ?, parent_id = ?
|
||||
SET name = ?, brand = ?, main_group_member_ids = ?, owner_userid = ?, note = ?
|
||||
WHERE id = ?`,
|
||||
)
|
||||
.bind(name, brand, JSON.stringify(memberIds), ownerUserid, note, parentProjectId, id)
|
||||
.bind(name, brand, JSON.stringify(memberIds), ownerUserid, note, id)
|
||||
.run();
|
||||
if (result.meta.changes === 0) throw new ProjectError("项目不存在", 404);
|
||||
} else {
|
||||
@@ -473,8 +358,8 @@ export async function saveProject(
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO projects
|
||||
(id, name, brand, main_group_member_ids, owner_userid, parent_id, status, note, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?)`,
|
||||
(id, name, brand, main_group_member_ids, owner_userid, status, note, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, 'active', ?, ?)`,
|
||||
)
|
||||
.bind(
|
||||
projectId,
|
||||
@@ -482,7 +367,6 @@ export async function saveProject(
|
||||
brand,
|
||||
JSON.stringify(memberIds),
|
||||
ownerUserid,
|
||||
parentProjectId,
|
||||
note,
|
||||
now,
|
||||
)
|
||||
@@ -505,13 +389,6 @@ export async function deleteProject(
|
||||
): Promise<void> {
|
||||
const id = text(projectId);
|
||||
if (!id) throw new ProjectError("缺少项目 ID");
|
||||
const childCount = await db
|
||||
.prepare("SELECT COUNT(*) AS count FROM projects WHERE parent_id = ?")
|
||||
.bind(id)
|
||||
.first<{ count: number }>();
|
||||
if (Number(childCount?.count ?? 0) > 0) {
|
||||
throw new ProjectError("该项目下还有子项目,请先删除子项目或把它们移到其他项目下");
|
||||
}
|
||||
const result = await db
|
||||
.prepare("DELETE FROM projects WHERE id = ?")
|
||||
.bind(id)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -80,12 +80,7 @@ export function buildTaskGroupPushMessage(
|
||||
const portal = portalUrl.trim().replace(/\/$/, "");
|
||||
const shareToken = bindingValue(task.share_token);
|
||||
const claimUrl = portal && shareToken ? `${portal}/?task=${shareToken}` : "";
|
||||
const formatLabel =
|
||||
task.task_type === "screenshot_collect"
|
||||
? "截图回收"
|
||||
: task.content_format === "video"
|
||||
? "视频"
|
||||
: "图文";
|
||||
const formatLabel = task.content_format === "video" ? "视频" : "图文";
|
||||
const lines = [
|
||||
`【新任务】${task.name}`,
|
||||
`品牌:${task.brand}|数量:${task.quantity} 份|截止:${task.due_at}`,
|
||||
|
||||
@@ -27,17 +27,17 @@ type DueSoonRow = {
|
||||
wecom_external_user_id: string | null;
|
||||
task_id: string;
|
||||
task_name: string;
|
||||
task_type: string;
|
||||
due_at: string;
|
||||
pending_phase: "publish" | "recovery";
|
||||
pending_due_at: string;
|
||||
content_title: string;
|
||||
};
|
||||
|
||||
function pendingActionLabel(taskType: string) {
|
||||
return taskType === "screenshot_collect" ? "截图待提交" : "待发布";
|
||||
function pendingActionLabel(pendingPhase: string) {
|
||||
return pendingPhase === "recovery" ? "截图待提交" : "待发布";
|
||||
}
|
||||
|
||||
function pendingSummary(rows: DueSoonRow[]) {
|
||||
const shot = rows.filter((row) => row.task_type === "screenshot_collect").length;
|
||||
const shot = rows.filter((row) => row.pending_phase === "recovery").length;
|
||||
const publish = rows.length - shot;
|
||||
if (shot === 0) return `${rows.length} 条笔记待发布`;
|
||||
if (publish === 0) return `${rows.length} 份截图待提交`;
|
||||
@@ -66,6 +66,7 @@ export async function runDueSoonWecomNotifications(
|
||||
const portalUrl = bindingValue(getRuntimeEnv().KOC_PORTAL_URL);
|
||||
const taskFilter = String(taskId ?? "").trim();
|
||||
|
||||
// 双阶段催办:发布阶段(未回填链接)看 due_at;回收阶段(已发布未收截图)看 recovery_due_at
|
||||
const dueSoonBase = `SELECT
|
||||
d.id AS distribution_id,
|
||||
d.partner_id,
|
||||
@@ -73,27 +74,29 @@ export async function runDueSoonWecomNotifications(
|
||||
p.wecom_external_user_id,
|
||||
t.id AS task_id,
|
||||
t.name AS task_name,
|
||||
t.task_type,
|
||||
t.due_at,
|
||||
CASE WHEN d.publish_url IS NULL OR d.publish_url = '' THEN 'publish' ELSE 'recovery' END AS pending_phase,
|
||||
CASE WHEN d.publish_url IS NULL OR d.publish_url = '' THEN t.due_at ELSE t.recovery_due_at END AS pending_due_at,
|
||||
c.title AS content_title
|
||||
FROM distributions d
|
||||
JOIN tasks t ON t.id = d.task_id
|
||||
JOIN partners p ON p.id = d.partner_id
|
||||
JOIN contents c ON c.id = d.content_id
|
||||
WHERE (
|
||||
(t.task_type = 'screenshot_collect' AND d.result_submitted_at IS NULL)
|
||||
OR (t.task_type != 'screenshot_collect'
|
||||
AND (d.publish_url IS NULL OR d.publish_url = ''))
|
||||
)
|
||||
AND t.due_at IS NOT NULL AND t.due_at != ''
|
||||
AND t.due_at <= ?`;
|
||||
((d.publish_url IS NULL OR d.publish_url = '')
|
||||
AND t.due_at IS NOT NULL AND t.due_at != '' AND t.due_at <= ?)
|
||||
OR (t.recovery_enabled = 1
|
||||
AND d.publish_url IS NOT NULL AND d.publish_url != ''
|
||||
AND d.result_submitted_at IS NULL
|
||||
AND t.recovery_due_at IS NOT NULL AND t.recovery_due_at != ''
|
||||
AND t.recovery_due_at <= ?)
|
||||
)`;
|
||||
const statement = db
|
||||
.prepare(
|
||||
taskFilter
|
||||
? `${dueSoonBase} AND t.id = ? ORDER BY t.due_at ASC, p.name ASC`
|
||||
: `${dueSoonBase} ORDER BY t.due_at ASC, p.name ASC`,
|
||||
? `${dueSoonBase} AND t.id = ? ORDER BY pending_due_at ASC, p.name ASC`
|
||||
: `${dueSoonBase} ORDER BY pending_due_at ASC, p.name ASC`,
|
||||
)
|
||||
.bind(...(taskFilter ? [cutoff, taskFilter] : [cutoff]));
|
||||
.bind(...(taskFilter ? [cutoff, cutoff, taskFilter] : [cutoff, cutoff]));
|
||||
const result = await statement.all<DueSoonRow>();
|
||||
|
||||
const grouped = new Map<
|
||||
@@ -129,7 +132,7 @@ export async function runDueSoonWecomNotifications(
|
||||
? [entry.externalUserId]
|
||||
: [];
|
||||
const lines = entry.rows.slice(0, 5).map((row) => {
|
||||
return `· 《${truncate(row.task_name, 24)}》— ${truncate(row.content_title, 24)}(${pendingActionLabel(row.task_type)},截止 ${row.due_at})`;
|
||||
return `· 《${truncate(row.task_name, 24)}》— ${truncate(row.content_title, 24)}(${pendingActionLabel(row.pending_phase)},截止 ${row.pending_due_at})`;
|
||||
});
|
||||
const overflow =
|
||||
entry.rows.length > 5 ? `\n…还有 ${entry.rows.length - 5} 条` : "";
|
||||
@@ -155,7 +158,7 @@ export async function runDueSoonWecomNotifications(
|
||||
} else {
|
||||
dueSoonSent += 1;
|
||||
}
|
||||
const earliestDue = entry.rows[0]?.due_at ?? "";
|
||||
const earliestDue = entry.rows[0]?.pending_due_at ?? "";
|
||||
digestTasks.push(
|
||||
`· ${entry.partnerName}(${entry.rows.length} 条,最近截止 ${earliestDue})`,
|
||||
);
|
||||
@@ -168,7 +171,7 @@ export async function runDueSoonWecomNotifications(
|
||||
for (const row of result.results) {
|
||||
const entry = byTask.get(row.task_id) ?? {
|
||||
taskName: row.task_name,
|
||||
dueAt: row.due_at,
|
||||
dueAt: row.pending_due_at,
|
||||
rows: [],
|
||||
};
|
||||
entry.rows.push(row);
|
||||
@@ -224,7 +227,8 @@ type OverdueRow = {
|
||||
id: string;
|
||||
task_id: string;
|
||||
task_name: string;
|
||||
due_at: string;
|
||||
pending_phase: "publish" | "recovery";
|
||||
pending_due_at: string;
|
||||
project_id: string;
|
||||
partner_id: string;
|
||||
partner_name: string;
|
||||
@@ -241,24 +245,33 @@ export type OverdueEscalationSummary = {
|
||||
async function queryOverdueUnpublished(
|
||||
db: DatabaseClient,
|
||||
cutoff: string,
|
||||
options: { phases: "publish" | "all" } = { phases: "all" },
|
||||
): Promise<OverdueRow[]> {
|
||||
const publishBranch = `(d.publish_url IS NULL OR d.publish_url = '')
|
||||
AND t.due_at IS NOT NULL AND t.due_at != ''
|
||||
AND t.due_at < ?`;
|
||||
const recoveryBranch = `t.recovery_enabled = 1
|
||||
AND d.publish_url IS NOT NULL AND d.publish_url != ''
|
||||
AND d.result_submitted_at IS NULL
|
||||
AND t.recovery_due_at IS NOT NULL AND t.recovery_due_at != ''
|
||||
AND t.recovery_due_at < ?`;
|
||||
const where =
|
||||
options.phases === "publish"
|
||||
? publishBranch
|
||||
: `(${publishBranch}) OR (${recoveryBranch})`;
|
||||
const result = await db
|
||||
.prepare(
|
||||
`SELECT d.id, t.id AS task_id, t.name AS task_name, t.due_at,
|
||||
`SELECT d.id, t.id AS task_id, t.name AS task_name,
|
||||
CASE WHEN d.publish_url IS NULL OR d.publish_url = '' THEN 'publish' ELSE 'recovery' END AS pending_phase,
|
||||
CASE WHEN d.publish_url IS NULL OR d.publish_url = '' THEN t.due_at ELSE t.recovery_due_at END AS pending_due_at,
|
||||
t.project_id, p.id AS partner_id, p.name AS partner_name
|
||||
FROM distributions d
|
||||
JOIN tasks t ON t.id = d.task_id
|
||||
JOIN partners p ON p.id = d.partner_id
|
||||
WHERE (
|
||||
(t.task_type = 'screenshot_collect' AND d.result_submitted_at IS NULL)
|
||||
OR (t.task_type != 'screenshot_collect'
|
||||
AND (d.publish_url IS NULL OR d.publish_url = ''))
|
||||
)
|
||||
AND t.due_at IS NOT NULL AND t.due_at != ''
|
||||
AND t.due_at < ?
|
||||
ORDER BY t.due_at ASC, t.name ASC`,
|
||||
WHERE ${where}
|
||||
ORDER BY pending_due_at ASC, t.name ASC`,
|
||||
)
|
||||
.bind(cutoff)
|
||||
.bind(...(options.phases === "publish" ? [cutoff] : [cutoff, cutoff]))
|
||||
.all<OverdueRow>();
|
||||
return result.results;
|
||||
}
|
||||
@@ -274,19 +287,28 @@ export async function runOverdueEscalation(
|
||||
|
||||
const byTask = new Map<
|
||||
string,
|
||||
{ taskName: string; dueAt: string; projectId: string; count: number; partners: Set<string> }
|
||||
{
|
||||
taskName: string;
|
||||
dueAt: string;
|
||||
phase: "publish" | "recovery";
|
||||
projectId: string;
|
||||
count: number;
|
||||
partners: Set<string>;
|
||||
}
|
||||
>();
|
||||
for (const row of rows) {
|
||||
const entry = byTask.get(row.task_id) ?? {
|
||||
const key = `${row.task_id}:${row.pending_phase}`;
|
||||
const entry = byTask.get(key) ?? {
|
||||
taskName: row.task_name,
|
||||
dueAt: row.due_at,
|
||||
dueAt: row.pending_due_at,
|
||||
phase: row.pending_phase,
|
||||
projectId: bindingValue(row.project_id),
|
||||
count: 0,
|
||||
partners: new Set<string>(),
|
||||
};
|
||||
entry.count += 1;
|
||||
entry.partners.add(row.partner_name || row.partner_id);
|
||||
byTask.set(row.task_id, entry);
|
||||
byTask.set(key, entry);
|
||||
}
|
||||
|
||||
const summary: OverdueEscalationSummary = {
|
||||
@@ -303,7 +325,8 @@ export async function runOverdueEscalation(
|
||||
const lines = [...byTask.values()].map((entry) => {
|
||||
const partners = [...entry.partners].slice(0, 5).join("、");
|
||||
const overflow = entry.partners.size > 5 ? ` 等 ${entry.partners.size} 位` : "";
|
||||
return `· ${truncate(entry.taskName, 24)}(截止 ${entry.dueAt}):${entry.count} 条超期未发布 — ${partners}${overflow}`;
|
||||
const label = entry.phase === "recovery" ? "截图超期未提交" : "超期未发布";
|
||||
return `· ${truncate(entry.taskName, 24)}(截止 ${entry.dueAt}):${entry.count} 条${label} — ${partners}${overflow}`;
|
||||
});
|
||||
try {
|
||||
await sendWecomRobotMessage(
|
||||
@@ -321,11 +344,16 @@ export async function runOverdueEscalation(
|
||||
|
||||
const env = getRuntimeEnv();
|
||||
const cardUrl = bindingValue(env.APP_ORIGIN) || bindingValue(env.KOC_PORTAL_URL);
|
||||
for (const [taskId, entry] of byTask) {
|
||||
for (const [key, entry] of byTask) {
|
||||
const taskId = key.split(":")[0];
|
||||
const overdueText =
|
||||
entry.phase === "recovery"
|
||||
? `${entry.count} 份截图超期未提交`
|
||||
: `${entry.count} 条内容超期未发布`;
|
||||
await sendTaskChatMessage(
|
||||
db,
|
||||
taskId,
|
||||
`【超期催办】《${truncate(entry.taskName, 24)}》(截止 ${entry.dueAt})有 ${entry.count} 条内容超期未发布,请跟进催办或释放。`,
|
||||
`【超期催办】《${truncate(entry.taskName, 24)}》(截止 ${entry.dueAt})有 ${overdueText},请跟进催办或释放。`,
|
||||
config,
|
||||
fetchImpl,
|
||||
);
|
||||
@@ -343,7 +371,7 @@ export async function runOverdueEscalation(
|
||||
touser: members,
|
||||
taskId: `task:${taskId}:due`,
|
||||
title: `超期催办:${truncate(entry.taskName, 20)}`,
|
||||
description: `${entry.count} 条内容超期未发布(截止 ${entry.dueAt}),请跟进催办或释放`,
|
||||
description: `${entry.phase === "recovery" ? `${entry.count} 份截图超期未提交` : `${entry.count} 条内容超期未发布`}(截止 ${entry.dueAt}),请跟进催办或释放`,
|
||||
url: cardUrl,
|
||||
buttons: [
|
||||
{ key: "view_task", name: "查看任务", url: cardUrl },
|
||||
@@ -398,7 +426,10 @@ export async function runOverdueAutoRelease(
|
||||
|
||||
const today = shanghaiDateFromTimestamp(now);
|
||||
summary.cutoff = computeDueCutoff(today, -days);
|
||||
const rows = await queryOverdueUnpublished(db, summary.cutoff);
|
||||
// 自动释放只处理发布阶段超期:回收超期的笔记已发布,释放重派无意义
|
||||
const rows = await queryOverdueUnpublished(db, summary.cutoff, {
|
||||
phases: "publish",
|
||||
});
|
||||
|
||||
for (const row of rows) {
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user