609 lines
17 KiB
TypeScript
609 lines
17 KiB
TypeScript
import { createTaskEvent } from '../../repositories/task-event-repo.js'
|
|
import { getTaskById, updateTask } from '../../repositories/task-repo.js'
|
|
import { createHttpError } from '../../utils/http.js'
|
|
import { parseTaskContext as parseTaskContextValue } from '../../utils/task-json.js'
|
|
import { nowIso } from '../../utils/time.js'
|
|
import type { JsonObject } from '../../types/json.js'
|
|
import { TASK_STATUS } from '../../domain/task-status.js'
|
|
import {
|
|
normalizeAffiliateDashFlow,
|
|
syncAffiliateDashTaskStatus,
|
|
} from '../fulfillment/affiliate-dash/index.js'
|
|
import {
|
|
bindAffiliateDashDelivery,
|
|
getAffiliateDashBindResult,
|
|
submitAffiliateDashDelivery,
|
|
} from '../platforms/affiliate-dash/order-service.js'
|
|
import {
|
|
assertValidClaimUid,
|
|
canUpdateClaimUid,
|
|
getClaimIdentityFromTask,
|
|
} from './claim-identity.js'
|
|
import { buildClaimDetailPayload, getClaimContext } from './kuaishou-cloud-claim-context.js'
|
|
import type { TaskRow } from '../../types/repository/rows.js'
|
|
|
|
type ClaimDetailPayload = ReturnType<typeof buildClaimDetailPayload>
|
|
|
|
const RETIRED_EXECUTOR_KEYS = new Set(['kuaishou_feifei', 'kuaishou_ct_assisted'])
|
|
|
|
function isRetiredExecutor(executorKey: unknown) {
|
|
return RETIRED_EXECUTOR_KEYS.has(String(executorKey || '').trim())
|
|
}
|
|
|
|
export async function getKuaishouCloudClaimDetail(token: unknown): Promise<ClaimDetailPayload> {
|
|
const context = await getClaimContext(token)
|
|
let task = context.task
|
|
const executorKey = String(task.executor_key || '').trim()
|
|
|
|
// 已下线渠道:只读详情,不主动同步上游
|
|
if (isRetiredExecutor(executorKey)) {
|
|
return buildClaimDetailPayload({
|
|
claimToken: context.claimToken,
|
|
task,
|
|
order: context.order,
|
|
orderItem: context.orderItem,
|
|
})
|
|
}
|
|
|
|
if (executorKey === 'affiliate_dash') {
|
|
task = (await syncAffiliateDashTaskStatus(task)) || task
|
|
if (shouldRefreshAffiliateDashBindState(task)) {
|
|
task = (await refreshAffiliateDashBindState(task)) || task
|
|
}
|
|
}
|
|
|
|
return buildClaimDetailPayload({
|
|
claimToken: context.claimToken,
|
|
task,
|
|
order: context.order,
|
|
orderItem: context.orderItem,
|
|
})
|
|
}
|
|
|
|
/**
|
|
* 统一领取 Step1:提交游戏 UID。
|
|
* 已下线渠道仅允许查看,禁止再改 UID。
|
|
*/
|
|
export async function submitClaimUid(
|
|
token: unknown,
|
|
payload: { uid?: unknown } = {},
|
|
): Promise<ClaimDetailPayload> {
|
|
const context = await getClaimContext(token)
|
|
const executorKey = String(context.task.executor_key || '').trim()
|
|
|
|
if (isRetiredExecutor(executorKey)) {
|
|
throw createHttpError('该履约渠道已下线,无法继续提交 UID', {
|
|
statusCode: 409,
|
|
errorCode: 'claim_channel_offline',
|
|
})
|
|
}
|
|
|
|
const expectedUid = assertValidClaimUid(payload.uid)
|
|
const now = nowIso()
|
|
|
|
if (!canUpdateClaimUid(context.task)) {
|
|
throw createHttpError('当前任务状态不可修改 UID', {
|
|
statusCode: 409,
|
|
errorCode: 'claim_uid_locked',
|
|
})
|
|
}
|
|
|
|
const taskContext = parseTaskContext(context.task)
|
|
const previous = getClaimIdentityFromTask(context.task)
|
|
if (executorKey === 'affiliate_dash') {
|
|
return submitAffiliateDashClaimUid(context, expectedUid, previous, taskContext, now, token)
|
|
}
|
|
|
|
const nextContext = {
|
|
...taskContext,
|
|
claimIdentity: buildClaimIdentityContext(previous, expectedUid, now),
|
|
}
|
|
|
|
await updateTask(context.task.id, {
|
|
context_json: JSON.stringify(nextContext),
|
|
claimed_at: context.task.claimed_at || now,
|
|
last_error: '',
|
|
updated_at: now,
|
|
})
|
|
|
|
await createClaimUidSubmittedEventIfChanged(
|
|
context.task.id,
|
|
previous.expectedUid,
|
|
expectedUid,
|
|
now,
|
|
)
|
|
|
|
return getKuaishouCloudClaimDetail(token)
|
|
}
|
|
|
|
function buildClaimIdentityContext(
|
|
previous: ReturnType<typeof getClaimIdentityFromTask>,
|
|
expectedUid: string,
|
|
now: string,
|
|
) {
|
|
return {
|
|
expectedUid,
|
|
submittedAt:
|
|
previous.expectedUid === expectedUid && previous.submittedAt ? previous.submittedAt : now,
|
|
source: 'claim_page',
|
|
}
|
|
}
|
|
|
|
async function createClaimUidSubmittedEventIfChanged(
|
|
taskId: number,
|
|
previousUid: string,
|
|
expectedUid: string,
|
|
now: string,
|
|
) {
|
|
if (previousUid === expectedUid) {
|
|
return
|
|
}
|
|
|
|
await createTaskEvent(
|
|
taskId,
|
|
'claim_uid_submitted',
|
|
{
|
|
expectedUid,
|
|
previousUid: previousUid || '',
|
|
source: 'claim_page',
|
|
},
|
|
now,
|
|
)
|
|
}
|
|
|
|
async function submitAffiliateDashClaimUid(
|
|
context: Awaited<ReturnType<typeof getClaimContext>>,
|
|
expectedUid: string,
|
|
previous: ReturnType<typeof getClaimIdentityFromTask>,
|
|
taskContext: JsonObject,
|
|
now: string,
|
|
token: unknown,
|
|
): Promise<ClaimDetailPayload> {
|
|
const flow = normalizeAffiliateDashFlow(taskContext.affiliateDash)
|
|
const claimIdentity = buildClaimIdentityContext(previous, expectedUid, now)
|
|
const baseTaskPatch = {
|
|
claimed_at: context.task.claimed_at || now,
|
|
last_error: '',
|
|
updated_at: now,
|
|
}
|
|
|
|
if (!flow.orderNo) {
|
|
await updateTask(context.task.id, {
|
|
...baseTaskPatch,
|
|
context_json: JSON.stringify({
|
|
...taskContext,
|
|
claimIdentity,
|
|
affiliateDash: clearAffiliateDashBindSnapshot(flow, expectedUid),
|
|
}),
|
|
})
|
|
await createClaimUidSubmittedEventIfChanged(
|
|
context.task.id,
|
|
previous.expectedUid,
|
|
expectedUid,
|
|
now,
|
|
)
|
|
return getKuaishouCloudClaimDetail(token)
|
|
}
|
|
|
|
if (canReuseAffiliateDashBindSnapshot(flow, expectedUid)) {
|
|
const nextFlow = {
|
|
...flow,
|
|
gameAccount: expectedUid,
|
|
expectedGameAccount: expectedUid,
|
|
bindMismatch: false,
|
|
}
|
|
await updateTask(context.task.id, {
|
|
...baseTaskPatch,
|
|
task_status: TASK_STATUS.WAITING_BINDING,
|
|
context_json: JSON.stringify({
|
|
...taskContext,
|
|
claimIdentity,
|
|
affiliateDash: nextFlow,
|
|
}),
|
|
})
|
|
await createClaimUidSubmittedEventIfChanged(
|
|
context.task.id,
|
|
previous.expectedUid,
|
|
expectedUid,
|
|
now,
|
|
)
|
|
await createTaskEvent(
|
|
context.task.id,
|
|
'affiliate_dash_bind_reused',
|
|
{
|
|
orderNo: flow.orderNo,
|
|
bindUuid: flow.bindUuid,
|
|
gameAccount: expectedUid,
|
|
},
|
|
now,
|
|
)
|
|
return getKuaishouCloudClaimDetail(token)
|
|
}
|
|
|
|
const bindResult = await bindAffiliateDashDelivery({
|
|
orderNo: flow.orderNo,
|
|
gameAccount: expectedUid,
|
|
})
|
|
const alreadyBound = Boolean(bindResult.bound)
|
|
const nextFlow = {
|
|
...flow,
|
|
bindUuid: bindResult.bindUuid,
|
|
bindUrl: bindResult.bindUrl,
|
|
qrUrl: bindResult.qrUrl,
|
|
gameAccount: expectedUid,
|
|
expectedGameAccount: expectedUid,
|
|
// 乐玩「已授权免扫码」会直接 bound=true;否则清空等待扫码。
|
|
bound: alreadyBound,
|
|
boundAccount: alreadyBound ? String(bindResult.gameAccount || expectedUid || '').trim() : '',
|
|
roleName: alreadyBound ? String(bindResult.roleName || '').trim() : '',
|
|
gameChannel: alreadyBound ? String(bindResult.gameChannel || '').trim() : '',
|
|
bindMismatch: false,
|
|
}
|
|
|
|
await updateTask(context.task.id, {
|
|
...baseTaskPatch,
|
|
task_status: TASK_STATUS.WAITING_BINDING,
|
|
context_json: JSON.stringify({
|
|
...taskContext,
|
|
claimIdentity,
|
|
affiliateDash: nextFlow,
|
|
}),
|
|
})
|
|
await createClaimUidSubmittedEventIfChanged(
|
|
context.task.id,
|
|
previous.expectedUid,
|
|
expectedUid,
|
|
now,
|
|
)
|
|
await createTaskEvent(
|
|
context.task.id,
|
|
'affiliate_dash_bind_created',
|
|
{
|
|
orderNo: flow.orderNo,
|
|
bindUuid: bindResult.bindUuid,
|
|
gameAccount: expectedUid,
|
|
},
|
|
now,
|
|
)
|
|
|
|
return getKuaishouCloudClaimDetail(token)
|
|
}
|
|
|
|
/**
|
|
* affiliate_dash 领取 Step2:提交发货(绑定完成后)。
|
|
*/
|
|
export async function submitAffiliateDashClaim(
|
|
token: unknown,
|
|
payload: { gameAccount?: unknown; bindUuid?: unknown } = {},
|
|
): Promise<ClaimDetailPayload> {
|
|
const context = await getClaimContext(token)
|
|
const task = context.task
|
|
const executorKey = String(task.executor_key || '').trim()
|
|
if (executorKey !== 'affiliate_dash') {
|
|
throw createHttpError('当前领取链接不是 affiliate-dash 领取流程', {
|
|
statusCode: 409,
|
|
errorCode: 'claim_not_affiliate_dash',
|
|
})
|
|
}
|
|
|
|
const taskContext = parseTaskContextValue(task)
|
|
const flow = normalizeAffiliateDashFlow(taskContext.affiliateDash)
|
|
if (!flow.orderNo) {
|
|
throw createHttpError('affiliate-dash 订单尚未创建', {
|
|
statusCode: 409,
|
|
errorCode: 'affiliate_dash_order_missing',
|
|
})
|
|
}
|
|
|
|
const expectedGameAccount = String(
|
|
getClaimIdentityFromTask(task).expectedUid ||
|
|
flow.expectedGameAccount ||
|
|
flow.gameAccount ||
|
|
'',
|
|
).trim()
|
|
const requestedGameAccount = String(payload.gameAccount || '').trim()
|
|
const requestedBindUuid = String(payload.bindUuid || '').trim()
|
|
const bindUuid = String(flow.bindUuid || '').trim()
|
|
if (!expectedGameAccount || !bindUuid) {
|
|
throw createHttpError('缺少绑定账号或 bindUuid', {
|
|
statusCode: 400,
|
|
errorCode: 'affiliate_dash_submit_missing',
|
|
})
|
|
}
|
|
if (
|
|
requestedGameAccount &&
|
|
normalizeUid(requestedGameAccount) !== normalizeUid(expectedGameAccount)
|
|
) {
|
|
throw createHttpError('提交 UID 与第一步填写 UID 不一致,请先更新 UID 后重新绑定', {
|
|
statusCode: 409,
|
|
errorCode: 'affiliate_dash_submit_uid_changed',
|
|
})
|
|
}
|
|
if (requestedBindUuid && requestedBindUuid !== bindUuid) {
|
|
throw createHttpError('绑定二维码已更新,请刷新页面后重试', {
|
|
statusCode: 409,
|
|
errorCode: 'affiliate_dash_bind_uuid_stale',
|
|
})
|
|
}
|
|
|
|
const now = nowIso()
|
|
const isMock = Boolean(flow.mock?.enabled)
|
|
const gameAccount = expectedGameAccount
|
|
const latestFlow = flow
|
|
|
|
if (!isMock && flow.bindUuid) {
|
|
if (isAffiliateDashBindSnapshotStale(flow, expectedGameAccount)) {
|
|
throw createHttpError('绑定二维码与当前 UID 不一致,请更新 UID 后重新绑定', {
|
|
statusCode: 409,
|
|
errorCode: 'affiliate_dash_bind_uid_stale',
|
|
})
|
|
}
|
|
|
|
const latestBoundAccount = latestFlow.boundAccount
|
|
const latestMismatch =
|
|
Boolean(latestFlow.bindMismatch) ||
|
|
Boolean(
|
|
latestFlow.bound &&
|
|
latestBoundAccount &&
|
|
normalizeUid(latestBoundAccount) !== normalizeUid(expectedGameAccount),
|
|
)
|
|
if (!latestFlow.bound) {
|
|
throw createHttpError('绑定尚未完成,请先扫码绑定账号', {
|
|
statusCode: 409,
|
|
errorCode: 'affiliate_dash_bind_pending',
|
|
})
|
|
}
|
|
if (!latestBoundAccount) {
|
|
throw createHttpError('暂时无法确认绑定 UID,请稍后自动刷新后再提交', {
|
|
statusCode: 409,
|
|
errorCode: 'affiliate_dash_bound_account_missing',
|
|
})
|
|
}
|
|
if (latestMismatch) {
|
|
throw createHttpError('绑定账号与填写 UID 不一致,请确认后重新绑定', {
|
|
statusCode: 409,
|
|
errorCode: 'affiliate_dash_bind_mismatch',
|
|
})
|
|
}
|
|
}
|
|
|
|
const result = isMock
|
|
? {
|
|
status: 'delivered',
|
|
message: '开发 mock 已模拟提交发货',
|
|
providerOrderNo: `MOCKAD-${flow.orderNo}`,
|
|
}
|
|
: await submitAffiliateDashDelivery({
|
|
orderNo: flow.orderNo,
|
|
gameAccount,
|
|
bindUuid,
|
|
})
|
|
|
|
const nextFlow = {
|
|
...latestFlow,
|
|
gameAccount,
|
|
bindUuid,
|
|
submitStatus: result.status,
|
|
orderStatus: result.status || flow.orderStatus,
|
|
}
|
|
|
|
await updateTask(task.id, {
|
|
task_status: TASK_STATUS.REDEEMING,
|
|
context_json: JSON.stringify({
|
|
...taskContext,
|
|
affiliateDash: nextFlow,
|
|
}),
|
|
result_code: 'affiliate_dash_submitted',
|
|
result_message: result.message || 'affiliate-dash 已提交发货',
|
|
updated_at: now,
|
|
})
|
|
await createTaskEvent(
|
|
task.id,
|
|
'affiliate_dash_submitted',
|
|
{
|
|
orderNo: flow.orderNo,
|
|
submitStatus: result.status,
|
|
providerOrderNo: result.providerOrderNo,
|
|
},
|
|
now,
|
|
)
|
|
|
|
if (result.status === 'delivered') {
|
|
const refreshedTask = await getTaskById(task.id)
|
|
if (refreshedTask) {
|
|
await syncAffiliateDashTaskStatus(refreshedTask, { snapshotOnly: true })
|
|
}
|
|
}
|
|
|
|
return getKuaishouCloudClaimDetail(token)
|
|
}
|
|
|
|
type AffiliateDashFlowSnapshot = ReturnType<typeof normalizeAffiliateDashFlow>
|
|
|
|
function resolveAffiliateDashExpectedGameAccount(
|
|
task: Partial<TaskRow> | null | undefined,
|
|
flow: AffiliateDashFlowSnapshot,
|
|
) {
|
|
return String(
|
|
getClaimIdentityFromTask(task).expectedUid ||
|
|
flow.expectedGameAccount ||
|
|
flow.gameAccount ||
|
|
'',
|
|
).trim()
|
|
}
|
|
|
|
function resolveAffiliateDashRecordedBindUid(flow: AffiliateDashFlowSnapshot) {
|
|
return normalizeUid(flow.expectedGameAccount || flow.gameAccount)
|
|
}
|
|
|
|
export function isAffiliateDashBindSnapshotStale(flowLike: unknown, expectedUid: unknown): boolean {
|
|
const flow = normalizeAffiliateDashFlow(flowLike)
|
|
const expected = normalizeUid(expectedUid)
|
|
if (!flow.bindUuid || !expected) {
|
|
return false
|
|
}
|
|
|
|
const recordedBindUid = resolveAffiliateDashRecordedBindUid(flow)
|
|
return !recordedBindUid || recordedBindUid !== expected
|
|
}
|
|
|
|
export function canReuseAffiliateDashBindSnapshot(
|
|
flowLike: unknown,
|
|
expectedUid: unknown,
|
|
): boolean {
|
|
const flow = normalizeAffiliateDashFlow(flowLike)
|
|
const expected = normalizeUid(expectedUid)
|
|
if (
|
|
!expected ||
|
|
!flow.bindUuid ||
|
|
!(flow.bindUrl || flow.qrUrl) ||
|
|
flow.bindMismatch ||
|
|
isAffiliateDashBindSnapshotStale(flow, expected)
|
|
) {
|
|
return false
|
|
}
|
|
|
|
const boundAccount = normalizeUid(flow.boundAccount)
|
|
if (boundAccount && boundAccount !== expected) {
|
|
return false
|
|
}
|
|
|
|
return !flow.bound || Boolean(boundAccount)
|
|
}
|
|
|
|
export function shouldRefreshAffiliateDashBindStateForSnapshot(input: {
|
|
taskStatus?: unknown
|
|
orderStatus?: unknown
|
|
submitStatus?: unknown
|
|
}): boolean {
|
|
const taskStatus = String(input.taskStatus || '').trim()
|
|
if (
|
|
taskStatus === TASK_STATUS.REDEEMING ||
|
|
taskStatus === TASK_STATUS.DISPATCHED_PENDING_RETURN ||
|
|
taskStatus === TASK_STATUS.REDEEMED ||
|
|
taskStatus === TASK_STATUS.COMPLETED
|
|
) {
|
|
return false
|
|
}
|
|
|
|
const submitStatus = String(input.submitStatus || '').trim()
|
|
if (submitStatus) {
|
|
return false
|
|
}
|
|
|
|
const orderStatus = String(input.orderStatus || '').trim()
|
|
return !['delivering', 'delivered', 'ship_failed', 'cancelled'].includes(orderStatus)
|
|
}
|
|
|
|
function shouldRefreshAffiliateDashBindState(task: TaskRow): boolean {
|
|
const flow = normalizeAffiliateDashFlow(parseTaskContextValue(task).affiliateDash)
|
|
return shouldRefreshAffiliateDashBindStateForSnapshot({
|
|
taskStatus: task.task_status,
|
|
orderStatus: flow.orderStatus,
|
|
submitStatus: flow.submitStatus,
|
|
})
|
|
}
|
|
|
|
function clearAffiliateDashBindSnapshot(
|
|
flow: AffiliateDashFlowSnapshot,
|
|
expectedUid: unknown,
|
|
): AffiliateDashFlowSnapshot {
|
|
const gameAccount = String(expectedUid || '').trim()
|
|
return {
|
|
...flow,
|
|
bindUuid: '',
|
|
bindUrl: '',
|
|
qrUrl: '',
|
|
gameAccount: gameAccount || flow.gameAccount,
|
|
expectedGameAccount: gameAccount || flow.expectedGameAccount,
|
|
bound: false,
|
|
boundAccount: '',
|
|
roleName: '',
|
|
gameChannel: '',
|
|
bindMismatch: false,
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 轮询绑定状态:详情查询时若有 bind_uuid,拉取 affiliate-dash bind-result 实时刷新
|
|
* bound / 绑定账号 / mismatch 到上下文(可重入,拉取失败不阻塞详情)。
|
|
*/
|
|
async function refreshAffiliateDashBindState(task: TaskRow): Promise<TaskRow | null> {
|
|
const taskContext = parseTaskContextValue(task)
|
|
const flow = normalizeAffiliateDashFlow(taskContext.affiliateDash)
|
|
if (flow.mock?.enabled) {
|
|
return task
|
|
}
|
|
if (!flow.orderNo || !flow.bindUuid) {
|
|
return task
|
|
}
|
|
|
|
const expectedGameAccount = resolveAffiliateDashExpectedGameAccount(task, flow)
|
|
if (isAffiliateDashBindSnapshotStale(flow, expectedGameAccount)) {
|
|
const now = nowIso()
|
|
return (
|
|
(await updateTask(task.id, {
|
|
context_json: JSON.stringify({
|
|
...taskContext,
|
|
affiliateDash: clearAffiliateDashBindSnapshot(flow, expectedGameAccount),
|
|
}),
|
|
last_error: '绑定二维码与当前 UID 不一致,请点击更新 UID 重新生成绑定二维码',
|
|
updated_at: now,
|
|
})) || task
|
|
)
|
|
}
|
|
|
|
try {
|
|
const result = await getAffiliateDashBindResult({
|
|
orderNo: flow.orderNo,
|
|
bindUuid: flow.bindUuid,
|
|
})
|
|
const boundAccount = result.bound ? result.gameAccount || flow.boundAccount : ''
|
|
const localMismatch = Boolean(
|
|
boundAccount &&
|
|
expectedGameAccount &&
|
|
normalizeUid(boundAccount) !== normalizeUid(expectedGameAccount),
|
|
)
|
|
const nextFlow = {
|
|
...flow,
|
|
bindUuid: result.bindUuid || flow.bindUuid,
|
|
bindUrl: result.bindUrl || flow.bindUrl,
|
|
qrUrl: result.qrUrl || flow.qrUrl,
|
|
gameAccount: expectedGameAccount || flow.gameAccount,
|
|
expectedGameAccount: expectedGameAccount || flow.expectedGameAccount,
|
|
bound: result.bound,
|
|
boundAccount,
|
|
roleName: result.bound
|
|
? String(result.roleName || flow.roleName || '').trim()
|
|
: flow.roleName,
|
|
gameChannel: result.bound
|
|
? String(result.gameChannel || flow.gameChannel || '').trim()
|
|
: flow.gameChannel,
|
|
bindMismatch: Boolean(result.mismatch) || localMismatch,
|
|
}
|
|
const now = nowIso()
|
|
|
|
return (
|
|
(await updateTask(task.id, {
|
|
context_json: JSON.stringify({
|
|
...taskContext,
|
|
affiliateDash: nextFlow,
|
|
}),
|
|
updated_at: now,
|
|
})) || task
|
|
)
|
|
} catch {
|
|
return task
|
|
}
|
|
}
|
|
|
|
function normalizeUid(value: unknown) {
|
|
return String(value || '')
|
|
.trim()
|
|
.replace(/\s+/g, '')
|
|
}
|
|
|
|
function parseTaskContext(task: Partial<TaskRow> | null | undefined): JsonObject {
|
|
return parseTaskContextValue(task)
|
|
}
|