feat: ship self-hosted KOC LOOP workflows
This commit is contained in:
@@ -1,5 +1,8 @@
|
||||
import { env } from "cloudflare:workers";
|
||||
import { getRequestExecutionContext } from "vinext/shims/request-context";
|
||||
import { getRuntimeEnv } from "../../../lib/runtime-env";
|
||||
import { runInBackground } from "../../../lib/background";
|
||||
import type { DatabaseStatement } from "../../../lib/database";
|
||||
|
||||
const env = getRuntimeEnv();
|
||||
import { enrichDistributionAccount } from "../../../lib/account-enrichment-service";
|
||||
import { createCollectionRunTasks } from "../../../lib/collection-service";
|
||||
import {
|
||||
@@ -22,8 +25,6 @@ import {
|
||||
withPartnerCors,
|
||||
} from "../../../lib/partner-cors";
|
||||
|
||||
export const runtime = "edge";
|
||||
|
||||
type PartnerBody = {
|
||||
action?: string;
|
||||
taskToken?: string;
|
||||
@@ -39,6 +40,7 @@ type PartnerBody = {
|
||||
publishUrl?: string;
|
||||
exposure?: number | string;
|
||||
views?: number | string;
|
||||
resultScreenshotKey?: string;
|
||||
};
|
||||
|
||||
type ImageAsset = {
|
||||
@@ -102,7 +104,7 @@ function publicImageAssets(value: unknown): ImageAsset[] {
|
||||
async function findTask(taskToken: string) {
|
||||
return getRawDb()
|
||||
.prepare(
|
||||
`SELECT id, name, brand, quantity, claimed_quantity, due_at, status
|
||||
`SELECT id, name, brand, quantity, claimed_quantity, due_at, status, task_type
|
||||
FROM tasks WHERE share_token = ?`,
|
||||
)
|
||||
.bind(taskToken)
|
||||
@@ -114,6 +116,7 @@ async function findTask(taskToken: string) {
|
||||
claimed_quantity: number;
|
||||
due_at: string;
|
||||
status: string;
|
||||
task_type: string;
|
||||
}>();
|
||||
}
|
||||
|
||||
@@ -128,6 +131,7 @@ async function findDelegationAccess(delegationToken: string) {
|
||||
t.claimed_quantity,
|
||||
t.due_at,
|
||||
t.status,
|
||||
t.task_type,
|
||||
b.id AS bundle_id,
|
||||
b.label AS bundle_label,
|
||||
b.quantity AS bundle_quantity,
|
||||
@@ -145,6 +149,7 @@ async function findDelegationAccess(delegationToken: string) {
|
||||
claimed_quantity: number;
|
||||
due_at: string;
|
||||
status: string;
|
||||
task_type: string;
|
||||
bundle_id: string;
|
||||
bundle_label: string;
|
||||
bundle_quantity: number;
|
||||
@@ -165,7 +170,9 @@ async function findAccessibleAssignment(
|
||||
d.account_id,
|
||||
d.publish_url,
|
||||
d.publish_screenshot_key,
|
||||
d.screenshot_key`;
|
||||
d.screenshot_key,
|
||||
d.result_screenshot_key,
|
||||
d.result_submitted_at`;
|
||||
if (delegationToken) {
|
||||
return db
|
||||
.prepare(
|
||||
@@ -185,6 +192,8 @@ async function findAccessibleAssignment(
|
||||
publish_url: string | null;
|
||||
publish_screenshot_key: string | null;
|
||||
screenshot_key: string | null;
|
||||
result_screenshot_key: string | null;
|
||||
result_submitted_at: string | null;
|
||||
}>();
|
||||
}
|
||||
if (!claimToken) return null;
|
||||
@@ -203,6 +212,8 @@ async function findAccessibleAssignment(
|
||||
publish_url: string | null;
|
||||
publish_screenshot_key: string | null;
|
||||
screenshot_key: string | null;
|
||||
result_screenshot_key: string | null;
|
||||
result_submitted_at: string | null;
|
||||
}>();
|
||||
}
|
||||
|
||||
@@ -263,6 +274,8 @@ async function handleGet(request: Request) {
|
||||
d.publish_url,
|
||||
d.publish_time,
|
||||
d.publish_screenshot_key,
|
||||
d.result_screenshot_key,
|
||||
d.result_submitted_at,
|
||||
d.screenshot_key AS creator_screenshot_key,
|
||||
d.ocr_status,
|
||||
d.exposure,
|
||||
@@ -295,6 +308,7 @@ async function handleGet(request: Request) {
|
||||
b.created_at,
|
||||
b.revoked_at,
|
||||
SUM(CASE WHEN d.publish_url IS NOT NULL AND d.publish_url != '' THEN 1 ELSE 0 END) AS completed_count,
|
||||
SUM(CASE WHEN d.result_submitted_at IS NOT NULL THEN 1 ELSE 0 END) AS result_completed_count,
|
||||
SUM(CASE WHEN d.screenshot_key IS NOT NULL AND d.exposure IS NOT NULL AND d.views IS NOT NULL THEN 1 ELSE 0 END) AS creator_completed_count
|
||||
FROM delegation_bundles b
|
||||
LEFT JOIN distributions d ON d.delegation_bundle_id = b.id
|
||||
@@ -325,6 +339,8 @@ async function handleGet(request: Request) {
|
||||
d.publish_url,
|
||||
d.publish_time,
|
||||
d.publish_screenshot_key,
|
||||
d.result_screenshot_key,
|
||||
d.result_submitted_at,
|
||||
d.screenshot_key AS creator_screenshot_key,
|
||||
d.ocr_status,
|
||||
d.exposure,
|
||||
@@ -344,7 +360,7 @@ async function handleGet(request: Request) {
|
||||
.all();
|
||||
delegation = {
|
||||
id: delegationAccess.bundle_id,
|
||||
label: "转派发布包",
|
||||
label: task.task_type === "screenshot_collect" ? "转派截图任务包" : "转派发布包",
|
||||
quantity: delegationAccess.bundle_quantity,
|
||||
createdAt: delegationAccess.bundle_created_at,
|
||||
assignments: assignments.results.map((assignment) => ({
|
||||
@@ -362,6 +378,7 @@ async function handleGet(request: Request) {
|
||||
brand: task.brand,
|
||||
dueAt: task.due_at,
|
||||
status: task.status,
|
||||
type: task.task_type,
|
||||
}
|
||||
: {
|
||||
name: task.name,
|
||||
@@ -370,6 +387,7 @@ async function handleGet(request: Request) {
|
||||
claimedQuantity: task.claimed_quantity,
|
||||
dueAt: task.due_at,
|
||||
status: task.status,
|
||||
type: task.task_type,
|
||||
availableQuantity: available?.count ?? 0,
|
||||
},
|
||||
claim,
|
||||
@@ -402,10 +420,11 @@ async function handlePost(request: Request) {
|
||||
if (
|
||||
delegationToken &&
|
||||
body.action !== "submit" &&
|
||||
body.action !== "submit_creator_metrics"
|
||||
body.action !== "submit_creator_metrics" &&
|
||||
body.action !== "submit_screenshot_result"
|
||||
) {
|
||||
return Response.json(
|
||||
{ error: "分享链接只能用于查看和回填包内笔记" },
|
||||
{ error: "分享链接只能用于查看和回填包内任务" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
@@ -438,7 +457,10 @@ async function handlePost(request: Request) {
|
||||
c.quantity,
|
||||
c.created_at,
|
||||
COUNT(d.id) AS note_count,
|
||||
SUM(CASE WHEN d.publish_url IS NOT NULL AND d.publish_url != '' THEN 1 ELSE 0 END) AS completed_count,
|
||||
SUM(CASE
|
||||
WHEN ? = 'screenshot_collect' AND d.result_submitted_at IS NOT NULL THEN 1
|
||||
WHEN ? != 'screenshot_collect' AND d.publish_url IS NOT NULL AND d.publish_url != '' THEN 1
|
||||
ELSE 0 END) AS completed_count,
|
||||
MIN(co.title) AS first_title
|
||||
FROM claims c
|
||||
LEFT JOIN distributions d ON d.claim_id = c.id
|
||||
@@ -448,7 +470,7 @@ async function handlePost(request: Request) {
|
||||
ORDER BY c.created_at DESC, c.id DESC
|
||||
LIMIT 20`,
|
||||
)
|
||||
.bind(task.id, partnerId, legacyPartnerId)
|
||||
.bind(task.task_type, task.task_type, task.id, partnerId, legacyPartnerId)
|
||||
.all<{
|
||||
claim_token: string;
|
||||
quantity: number;
|
||||
@@ -469,7 +491,7 @@ async function handlePost(request: Request) {
|
||||
quantity: claim.note_count || claim.quantity,
|
||||
completedCount: claim.completed_count || 0,
|
||||
createdAt: claim.created_at,
|
||||
firstTitle: claim.first_title || "领取的笔记",
|
||||
firstTitle: claim.first_title || (task.task_type === "screenshot_collect" ? "领取的截图任务" : "领取的笔记"),
|
||||
})),
|
||||
});
|
||||
}
|
||||
@@ -495,9 +517,9 @@ async function handlePost(request: Request) {
|
||||
`SELECT id FROM contents
|
||||
WHERE task_id = ? AND status = 'available'
|
||||
ORDER BY COALESCE(source_row, 999999), created_at, id
|
||||
LIMIT ?`,
|
||||
LIMIT ${quantity}`,
|
||||
)
|
||||
.bind(task.id, quantity)
|
||||
.bind(task.id)
|
||||
.all<{ id: string }>();
|
||||
if (available.results.length === 0) {
|
||||
return Response.json({ error: "当前任务已领完" }, { status: 409 });
|
||||
@@ -508,7 +530,7 @@ async function handlePost(request: Request) {
|
||||
const claimantName = claimantIdentifier.display;
|
||||
const claimId = uid("claim");
|
||||
const claimToken = crypto.randomUUID().replaceAll("-", "");
|
||||
const statements: D1PreparedStatement[] = [
|
||||
const statements: DatabaseStatement[] = [
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO partners
|
||||
@@ -584,7 +606,7 @@ async function handlePost(request: Request) {
|
||||
}
|
||||
if (distributionIds.length === 0) {
|
||||
return Response.json(
|
||||
{ error: "请至少选择一篇待发布笔记" },
|
||||
{ error: task.task_type === "screenshot_collect" ? "请至少选择一份待提交任务" : "请至少选择一篇待发布笔记" },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
@@ -602,7 +624,7 @@ async function handlePost(request: Request) {
|
||||
const placeholders = distributionIds.map(() => "?").join(", ");
|
||||
const selected = await db
|
||||
.prepare(
|
||||
`SELECT id, publish_url, delegation_bundle_id
|
||||
`SELECT id, publish_url, result_submitted_at, delegation_bundle_id
|
||||
FROM distributions
|
||||
WHERE claim_id = ? AND id IN (${placeholders})`,
|
||||
)
|
||||
@@ -610,6 +632,7 @@ async function handlePost(request: Request) {
|
||||
.all<{
|
||||
id: string;
|
||||
publish_url: string | null;
|
||||
result_submitted_at: string | null;
|
||||
delegation_bundle_id: string | null;
|
||||
}>();
|
||||
if (selected.results.length !== distributionIds.length) {
|
||||
@@ -618,9 +641,13 @@ async function handlePost(request: Request) {
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
if (selected.results.some((item) => item.publish_url)) {
|
||||
if (selected.results.some((item) =>
|
||||
task.task_type === "screenshot_collect"
|
||||
? item.result_submitted_at
|
||||
: item.publish_url,
|
||||
)) {
|
||||
return Response.json(
|
||||
{ error: "已发布的笔记不能再次转派" },
|
||||
{ error: task.task_type === "screenshot_collect" ? "已提交的截图任务不能再次转派" : "已发布的笔记不能再次转派" },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
@@ -632,7 +659,7 @@ async function handlePost(request: Request) {
|
||||
}
|
||||
const bundleId = uid("delegate");
|
||||
const shareToken = crypto.randomUUID().replaceAll("-", "");
|
||||
const statements: D1PreparedStatement[] = [
|
||||
const statements: DatabaseStatement[] = [
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO delegation_bundles
|
||||
@@ -658,6 +685,7 @@ async function handlePost(request: Request) {
|
||||
WHERE id = ?
|
||||
AND claim_id = ?
|
||||
AND publish_url IS NULL
|
||||
AND result_submitted_at IS NULL
|
||||
AND delegation_bundle_id IS NULL`,
|
||||
)
|
||||
.bind(bundleId, distributionId, claimRow.id),
|
||||
@@ -721,19 +749,18 @@ async function handlePost(request: Request) {
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
const published = await db
|
||||
const completed = await db
|
||||
.prepare(
|
||||
`SELECT COUNT(*) AS count
|
||||
FROM distributions
|
||||
WHERE delegation_bundle_id = ?
|
||||
AND publish_url IS NOT NULL
|
||||
AND publish_url != ''`,
|
||||
AND (publish_url IS NOT NULL AND publish_url != '' OR result_submitted_at IS NOT NULL)`,
|
||||
)
|
||||
.bind(bundle.id)
|
||||
.first<{ count: number }>();
|
||||
if ((published?.count ?? 0) > 0) {
|
||||
if ((completed?.count ?? 0) > 0) {
|
||||
return Response.json(
|
||||
{ error: "该分享包已有笔记发布,需保留链接继续完成第7天数据回收" },
|
||||
{ error: task.task_type === "screenshot_collect" ? "该分享包已有截图提交,不能撤销" : "该分享包已有笔记发布,需保留链接继续完成第7天数据回收" },
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
@@ -759,6 +786,9 @@ async function handlePost(request: Request) {
|
||||
}
|
||||
|
||||
if (body.action === "submit") {
|
||||
if (task.task_type === "screenshot_collect") {
|
||||
return Response.json({ error: "截图回收任务无需填写发布链接" }, { status: 400 });
|
||||
}
|
||||
const claimToken = textValue(body.claimToken, 80);
|
||||
const distributionId = textValue(body.distributionId, 80);
|
||||
const publishInput = textValue(body.publishUrl, 5000);
|
||||
@@ -796,7 +826,7 @@ async function handlePost(request: Request) {
|
||||
const accountId =
|
||||
reuseExistingAccount ||
|
||||
`account-${hashText(`${account.platform}:${account.platformUid}`)}`;
|
||||
const statements: D1PreparedStatement[] = [];
|
||||
const statements: DatabaseStatement[] = [];
|
||||
if (!reuseExistingAccount) {
|
||||
statements.push(
|
||||
db
|
||||
@@ -884,17 +914,15 @@ async function handlePost(request: Request) {
|
||||
env as unknown as CollectionMcpBindings,
|
||||
),
|
||||
).catch(() => undefined);
|
||||
const executionContext = getRequestExecutionContext();
|
||||
if (executionContext) {
|
||||
executionContext.waitUntil(enrichment);
|
||||
} else {
|
||||
await enrichment;
|
||||
}
|
||||
runInBackground(enrichment, "distribution account enrichment");
|
||||
}
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
|
||||
if (body.action === "submit_creator_metrics") {
|
||||
if (task.task_type === "screenshot_collect") {
|
||||
return Response.json({ error: "截图回收任务不需要创作者数据" }, { status: 400 });
|
||||
}
|
||||
const claimToken = textValue(body.claimToken, 80);
|
||||
const distributionId = textValue(body.distributionId, 80);
|
||||
const exposure = creatorMetricValue(body.exposure);
|
||||
@@ -941,6 +969,49 @@ async function handlePost(request: Request) {
|
||||
return Response.json({ submitted: true });
|
||||
}
|
||||
|
||||
if (body.action === "submit_screenshot_result") {
|
||||
if (task.task_type !== "screenshot_collect") {
|
||||
return Response.json({ error: "当前任务不支持这种回填方式" }, { status: 400 });
|
||||
}
|
||||
const claimToken = textValue(body.claimToken, 80);
|
||||
const distributionId = textValue(body.distributionId, 80);
|
||||
const assignment = await findAccessibleAssignment(
|
||||
task.id,
|
||||
distributionId,
|
||||
claimToken,
|
||||
delegationToken,
|
||||
);
|
||||
if (!assignment) {
|
||||
return Response.json({ error: "任务与领取凭证不匹配" }, { status: 403 });
|
||||
}
|
||||
if (!assignment.result_screenshot_key) {
|
||||
return Response.json({ error: "请先上传任务截图" }, { status: 400 });
|
||||
}
|
||||
const statements: DatabaseStatement[] = [
|
||||
db
|
||||
.prepare(
|
||||
`UPDATE distributions SET
|
||||
result_submitted_at = CURRENT_TIMESTAMP,
|
||||
status = 'complete',
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = ?`,
|
||||
)
|
||||
.bind(assignment.id),
|
||||
];
|
||||
if (!assignment.result_submitted_at) {
|
||||
statements.push(
|
||||
db
|
||||
.prepare(
|
||||
`UPDATE partners SET completed_total = completed_total + 1
|
||||
WHERE id = ?`,
|
||||
)
|
||||
.bind(assignment.partner_id),
|
||||
);
|
||||
}
|
||||
await db.batch(statements);
|
||||
return Response.json({ submitted: true });
|
||||
}
|
||||
|
||||
return Response.json({ error: "不支持的操作" }, { status: 400 });
|
||||
} catch (error) {
|
||||
return Response.json(
|
||||
|
||||
Reference in New Issue
Block a user