feat: add audited async task reconciliation and frozen bindings
This commit is contained in:
1 parent
5be06a97c1
commit
c716ec7478
28 files changed
+1312
-76
No files matched your search
@@ -2,6 +2,7 @@
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { catalogClient, type CatalogModel } from '../services/catalog'
|
||||
import { enterprise } from '../services/enterprise'
|
||||
import TaskReconciliation from './TaskReconciliation.vue'
|
||||
type Json = Record<string, unknown>
|
||||
const models = ref<CatalogModel[]>([]), selected = ref(''), loaded = ref(false), busy = ref(false), notice = ref(''), history = ref<Json[]>([]), records = ref<Json[]>([]), summary = ref<Json>({}), page = ref(1)
|
||||
const retail = ref<Json>({}), procurement = ref<Json | null>(null), retailFields = reactive<Record<string, string>>({}), costFields = reactive<Record<string, string>>({}), costKnown = ref(false), retailTiers = ref('[]'), costTiers = ref('[]'), protocols = ref<string[]>([])
|
||||
@@ -49,5 +50,6 @@ async function reconcile() { busy.value = true; try { await enterprise(`/api/adm
|
||||
<form v-if="reconcileId" @submit.prevent="reconcile"><h4>核对 {{ reconcileId }}</h4><label class="form-label">实际采购成本(元)<input v-model="reconcileCost" class="text-input" inputmode="decimal" required /></label><label class="form-label">渠道账单依据<textarea v-model="reconcileNote" class="text-input" minlength="3" maxlength="2000" required /></label><button class="button primary" :disabled="busy">确认成本</button><button type="button" class="button secondary" @click="reconcileId = ''">取消</button></form>
|
||||
<div class="responsive-table"><table><thead><tr><th>时间/模型</th><th>调用</th><th>用户消费</th><th>采购成本</th><th>核对状态</th><th></th></tr></thead><tbody><tr v-for="r in records" :key="String(r.id)"><td>{{ r.created_at }}<br />{{ r.public_name }}</td><td>{{ r.status }}</td><td>{{ money(r.cost_amount) }}</td><td>{{ money(r.procurement_cost) }}</td><td>{{ state(r.cost_status) }}</td><td><button class="button secondary small" @click="reconcileId = String(r.id); reconcileCost = ''; reconcileNote = ''">核对</button></td></tr></tbody></table></div><div class="protocols"><button class="button secondary" :disabled="page <= 1" @click="page--; refresh().catch(e => notice = String(e))">上一页</button><span>第 {{ page }} 页</span><button class="button secondary" :disabled="records.length < 50" @click="page++; refresh().catch(e => notice = String(e))">下一页</button></div>
|
||||
</section>
|
||||
<TaskReconciliation />
|
||||
</template>
|
||||
<style scoped>.finance-card{padding:24px;margin-bottom:22px}.finance-card .form-label{flex-direction:column;gap:8px}.finance-card p{font-size:13px;color:#64736d;line-height:1.7}.finance-grid{display:grid;grid-template-columns:1fr 1fr;gap:24px}.finance-card button,.finance-card details{margin-top:16px}.finance-card summary{cursor:pointer}.history{max-height:340px;overflow:auto}.history pre{white-space:pre-wrap;background:#f3f6f4;padding:12px}.protocols{display:flex;align-items:center;gap:18px;flex-wrap:wrap}@media(max-width:700px){.finance-grid{grid-template-columns:1fr}}</style>
|
||||
@@ -0,0 +1,108 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import UiModal from './UiModal.vue'
|
||||
import { reconciliationPayload, taskReconciliation, type ReconciliationAction, type ReconciliationCommand, type ReconciliationReceipt, type ReconciliationTask } from '../services/task-reconciliation'
|
||||
|
||||
const rows = ref<ReconciliationTask[]>([]), total = ref(0), page = ref(1), loaded = ref(false), busy = ref(false), loading = ref(false), notice = ref('')
|
||||
const selected = ref<ReconciliationTask | null>(null), history = ref<ReconciliationReceipt[]>([])
|
||||
const action = ref<ReconciliationAction>('confirm_failed'), evidence = ref(''), note = ref(''), providerTaskId = ref(''), fingerprint = ref(''), resultText = ref('{}'), confirmed = ref(false)
|
||||
const quote = ref<{ expectedCost: string; expectedUpdatedAt: string } | null>(null)
|
||||
const pending = ref<{ signature: string; command: ReconciliationCommand } | null>(null)
|
||||
const actionName = (value: string) => ({ resume_polling: '恢复只读轮询', confirm_failed: '确认失败并释放冻结', confirm_succeeded: '确认成功并结算' })[value] || value
|
||||
const stateName = (value: string) => ({ reconciling: '待核账', running: '执行中', failed: '失败', succeeded: '成功', cancelled: '已取消' })[value] || value
|
||||
const actionable = computed(() => selected.value?.status === 'reconciling' && !selected.value.completionStatus && selected.value.costAmount == null)
|
||||
const bindingKnown = computed(() => !!selected.value?.providerId && !!selected.value?.upstreamModel)
|
||||
const confirmation = computed(() => action.value === 'confirm_failed'
|
||||
? `我已核实上游失败或未受理,确认释放该任务冻结 ¥${selected.value?.reservedAmount ?? '—'},不代表给钱包额外加款`
|
||||
: action.value === 'confirm_succeeded' ? `我已核实任务成功和计费用量,确认实际扣费 ¥${quote.value?.expectedCost ?? '尚未核算'}`
|
||||
: '我已核实原任务编号和原账号指纹,仅恢复查询,不重新生成、不释放冻结额度')
|
||||
watch([action, resultText], () => { quote.value = null; confirmed.value = false })
|
||||
|
||||
function result() {
|
||||
if (new TextEncoder().encode(resultText.value).length > 32_768) throw new Error('结果与用量 JSON 最多 32 KiB')
|
||||
const parsed: unknown = JSON.parse(resultText.value)
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('结果必须是 JSON 对象')
|
||||
return parsed as Record<string, unknown>
|
||||
}
|
||||
async function refresh() {
|
||||
loading.value = true
|
||||
try { const data = await taskReconciliation.list(page.value); rows.value = data.records; total.value = data.total; loaded.value = true }
|
||||
catch (error) { notice.value = error instanceof Error ? error.message : '读取待核账任务失败' }
|
||||
finally { loading.value = false }
|
||||
}
|
||||
onMounted(refresh)
|
||||
async function open(task: ReconciliationTask) {
|
||||
if (busy.value) return
|
||||
busy.value = true; notice.value = ''
|
||||
try {
|
||||
const data = await taskReconciliation.detail(task.id)
|
||||
selected.value = data.task; history.value = data.history
|
||||
action.value = 'confirm_failed'; evidence.value = ''; note.value = ''; resultText.value = '{}'
|
||||
providerTaskId.value = data.task.providerTaskId || ''; fingerprint.value = data.task.credentialFingerprint || ''
|
||||
confirmed.value = false; quote.value = null; pending.value = null
|
||||
} catch (error) { notice.value = error instanceof Error ? error.message : '读取任务详情失败' }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
async function calculate() {
|
||||
if (!selected.value) return
|
||||
busy.value = true; notice.value = ''; confirmed.value = false
|
||||
try { quote.value = await taskReconciliation.quote(selected.value.id, result()) }
|
||||
catch (error) { quote.value = null; notice.value = error instanceof Error ? error.message : '核算失败,冻结额度保持不变' }
|
||||
finally { busy.value = false }
|
||||
}
|
||||
async function submit() {
|
||||
if (!selected.value || !confirmed.value || !actionable.value) return
|
||||
busy.value = true; notice.value = ''
|
||||
try {
|
||||
const body = reconciliationPayload(selected.value, action.value, evidence.value, note.value, providerTaskId.value, fingerprint.value, quote.value,
|
||||
action.value === 'confirm_succeeded' ? result() : {})
|
||||
const signature = JSON.stringify(body)
|
||||
if (!pending.value || pending.value.signature !== signature) pending.value = { signature, command: { requestId: crypto.randomUUID(), ...body } }
|
||||
const saved = await taskReconciliation.submit(selected.value.id, pending.value.command)
|
||||
selected.value = saved.task
|
||||
confirmed.value = false
|
||||
notice.value = `核账操作已记录${saved.replayed ? '(原操作回执,未重复执行)' : ''},操作编号 ${saved.requestId}`
|
||||
try { const data = await taskReconciliation.detail(saved.task.id); selected.value = data.task; history.value = data.history; await refresh() }
|
||||
catch { notice.value += ';操作已成功,但详情刷新失败,请稍后刷新查看' }
|
||||
} catch (error) {
|
||||
notice.value = `${error instanceof Error ? error.message : '无法确认操作结果'}${pending.value ? `;原样重试将保留操作编号 ${pending.value.command.requestId},不会重新生成任务` : ''}`
|
||||
} finally { busy.value = false }
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="panel reconciliation-card">
|
||||
<header class="panel-header"><div><span>ASYNC TASK RECONCILIATION</span><h3>异步任务人工核账</h3></div><button class="button secondary small" :disabled="loading || busy" @click="refresh">刷新</button></header>
|
||||
<p>仅处理上游受理或执行结果未知的任务。冻结金额仍占用钱包和预算;先核对渠道任务记录与账单,再决定终态。不会自动重发生成请求。</p>
|
||||
<p v-if="notice && !selected" role="status" class="reconciliation-notice">{{ notice }}</p>
|
||||
<div class="responsive-table"><table><thead><tr><th>任务 / 用户</th><th>模型 / 原渠道</th><th>冻结金额</th><th>上游编号</th><th>异常</th><th></th></tr></thead>
|
||||
<tbody><tr v-for="task in rows" :key="task.id"><td><code>{{ task.id }}</code><small>{{ task.userId }}</small></td><td>{{ task.modelId }}<small>{{ task.providerId || '历史执行绑定待核实' }}</small></td><td>¥ {{ task.reservedAmount }}</td><td>{{ task.providerTaskId || '回执未知' }}</td><td>{{ task.error?.message || '待核实上游记录' }}</td><td><button class="button secondary small" :disabled="busy" @click="open(task)">核账</button></td></tr>
|
||||
<tr v-if="!rows.length"><td colspan="6">{{ loading ? '正在读取…' : !loaded ? '待核账数据尚未读取' : '暂无待核账任务' }}</td></tr></tbody>
|
||||
</table></div>
|
||||
<div class="reconciliation-actions"><button class="button secondary small" :disabled="page <= 1 || loading || busy" @click="page--; refresh()">上一页</button><span>第 {{ page }} 页 · {{ loaded ? total : '—' }} 笔待核账</span><button class="button secondary small" :disabled="page * 50 >= total || loading || busy" @click="page++; refresh()">下一页</button></div>
|
||||
</section>
|
||||
|
||||
<UiModal v-if="selected" title="核实异步任务" eyebrow="EVIDENCE-BACKED DECISION" wide @close="!busy && (selected = null)">
|
||||
<p v-if="notice" role="status" class="reconciliation-notice">{{ notice }}</p>
|
||||
<dl class="detail-list"><div><dt>本地任务</dt><dd><code>{{ selected.id }}</code></dd></div><div><dt>状态 / 原预留金额</dt><dd>{{ stateName(selected.status) }} · ¥ {{ selected.reservedAmount }}</dd></div><div><dt>原执行渠道 / 模型</dt><dd>{{ selected.providerId || '不可证明' }} / {{ selected.upstreamModel || '不可证明' }}</dd></div><div><dt>实际扣费</dt><dd>{{ selected.costAmount == null ? '尚未结算' : `¥ ${selected.costAmount}` }}</dd></div></dl>
|
||||
<details><summary>任务原价格快照(不是当前目录价格)</summary><pre>{{ selected.pricing ? JSON.stringify(selected.pricing, null, 2) : '历史固定价任务:沿用原预留金额;不按当前目录价格补算' }}</pre></details>
|
||||
<p v-if="!bindingKnown" class="reconciliation-notice">历史任务原执行路由不可证明,不能猜测后恢复查询。核实上游终态后再选择成功或失败确认。</p>
|
||||
<form v-if="actionable" id="task-reconciliation-form" @submit.prevent="submit">
|
||||
<fieldset :disabled="busy">
|
||||
<label class="form-label">核账决定<select v-model="action" class="text-input"><option value="confirm_failed">确认失败并释放冻结</option><option value="confirm_succeeded">确认成功并按原快照结算</option><option value="resume_polling" :disabled="!bindingKnown">关联原任务,恢复只读轮询</option></select></label>
|
||||
<template v-if="action === 'resume_polling'"><label class="form-label">已核实的上游任务编号<input v-model="providerTaskId" class="text-input" required maxlength="160" :readonly="!!selected.providerTaskId" /></label><label class="form-label">原上游账号 SHA-256 指纹(不是 API Key)<input v-model="fingerprint" class="text-input" required pattern="[0-9a-f]{64}" maxlength="64" :readonly="!!selected.credentialFingerprint" /></label><p>只允许已有服务器凭据池中的账号,不接受粘贴密钥;已知任务编号和账号不可改绑。</p></template>
|
||||
<template v-if="action === 'confirm_succeeded'"><label class="form-label">核实结果及用量 JSON<textarea v-model="resultText" class="text-input" rows="7" spellcheck="false" required /></label><p>仅接受规范化结果地址、usage 或 usageMetadata。不得粘贴原始响应、密钥或大段生成内容;Token 用量不完整时不能确认成功扣费。</p><button type="button" class="button secondary small" @click="calculate">按原快照核算金额</button><p class="reconciliation-charge">本次实际扣费:{{ quote ? `¥ ${quote.expectedCost}` : '尚未核算' }}。金额可能超过预留,须核对上游用量。</p></template>
|
||||
<label class="form-label">上游证据引用<input v-model="evidence" class="text-input" minlength="3" maxlength="500" placeholder="渠道账单编号、工单号或任务记录引用;不要包含密钥" required /></label>
|
||||
<label class="form-label">核账说明<textarea v-model="note" class="text-input" minlength="10" maxlength="2000" rows="3" required placeholder="说明核对了哪些记录及结论,至少 10 字;不要记录凭据" /></label>
|
||||
<label class="reconciliation-confirm"><input v-model="confirmed" type="checkbox" required :disabled="action === 'confirm_succeeded' && !quote" />{{ confirmation }}</label>
|
||||
</fieldset>
|
||||
</form>
|
||||
<p v-else>此任务已被处理或存在可信终态,不允许再次人工改写。请查看操作历史。</p>
|
||||
<section v-if="history.length" class="reconciliation-history"><h4>最近核账历史</h4><article v-for="receipt in history" :key="receipt.request_id"><strong>{{ actionName(receipt.action) }} · {{ stateName(receipt.after_state.status) }}</strong><small>{{ receipt.created_at }} · {{ receipt.actor_user_id }}</small><p>{{ receipt.evidence_reference }} · {{ receipt.note }}</p><code>{{ receipt.request_id }}</code></article></section>
|
||||
<template #footer><button type="button" class="button secondary" :disabled="busy" @click="selected = null">关闭</button><button v-if="actionable" class="button primary" form="task-reconciliation-form" :disabled="busy || !confirmed || (action === 'confirm_succeeded' && !quote)">{{ busy ? '正在提交…' : '确认并记录审计' }}</button></template>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.reconciliation-card{padding:24px;margin-top:22px}.reconciliation-card p,.reconciliation-actions,.reconciliation-history p{font-size:13px;color:#64736d;line-height:1.7}.reconciliation-card td small,.reconciliation-history small{display:block;margin-top:5px;color:#64736d}.reconciliation-card code{word-break:break-all}.reconciliation-actions{display:flex;gap:16px;align-items:center;margin-top:16px}.reconciliation-notice{padding:12px;border:1px solid #f0dcc6;background:#fffaf4;color:#8b5218;word-break:break-word}.form-label{display:flex;flex-direction:column;gap:8px;margin-top:18px}fieldset{border:0;margin:0;padding:0;min-width:0}.reconciliation-confirm{display:flex;gap:10px;align-items:flex-start;margin-top:20px;font-size:13px;line-height:1.7}.reconciliation-charge{font-weight:600}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#f3f6f4;padding:12px;font-size:12px;max-height:220px;overflow:auto}.reconciliation-history{margin-top:24px}.reconciliation-history article{padding:14px 0;border-top:1px solid #e5e9e7}.reconciliation-history code{font-size:11px;overflow-wrap:anywhere}
|
||||
</style>
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { ReconciliationTask, ReconciliationAction, ReconciliationCommand } from './task-reconciliation'
|
||||
|
||||
/** Build one explicit decision. Its request ID is retained by the UI until the payload changes. */
|
||||
export function reconciliationPayload(task: ReconciliationTask, action: ReconciliationAction, evidenceReference: string,
|
||||
note: string, providerTaskId: string, credentialFingerprint: string, quote: { expectedCost: string; expectedUpdatedAt: string } | null,
|
||||
result: Record<string, unknown>): Omit<ReconciliationCommand, 'requestId'> {
|
||||
const payload: Omit<ReconciliationCommand, 'requestId'> = { action, expectedUpdatedAt: task.updatedAt, evidenceReference: evidenceReference.trim(), note: note.trim() }
|
||||
if (action === 'resume_polling') {
|
||||
payload.providerTaskId = providerTaskId.trim()
|
||||
payload.credentialFingerprint = credentialFingerprint.trim()
|
||||
} else if (action === 'confirm_succeeded') {
|
||||
if (!quote || quote.expectedUpdatedAt !== task.updatedAt) throw new Error('请先按任务原价格快照核算并确认金额;任务版本变化后需重新打开核对')
|
||||
payload.expectedCost = quote.expectedCost
|
||||
payload.result = result
|
||||
}
|
||||
return payload
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { enterprise } from './enterprise'
|
||||
|
||||
export type ReconciliationAction = 'resume_polling' | 'confirm_failed' | 'confirm_succeeded'
|
||||
export interface ReconciliationTask {
|
||||
id: string
|
||||
userId: string
|
||||
modelId: string
|
||||
taskType: string
|
||||
status: string
|
||||
updatedAt: string
|
||||
reservedAmount: string
|
||||
costAmount: string | null
|
||||
providerId: string | null
|
||||
upstreamModel: string | null
|
||||
providerTaskId: string | null
|
||||
credentialFingerprint: string | null
|
||||
completionStatus: string | null
|
||||
requiresReconciliation: boolean
|
||||
pricing: Record<string, unknown> | null
|
||||
error: { code?: string; message?: string } | null
|
||||
}
|
||||
export interface ReconciliationReceipt {
|
||||
request_id: string
|
||||
actor_user_id: string
|
||||
action: ReconciliationAction
|
||||
evidence_reference: string
|
||||
note: string
|
||||
created_at: string
|
||||
before_state: ReconciliationTask
|
||||
after_state: ReconciliationTask
|
||||
}
|
||||
export interface ReconciliationCommand {
|
||||
requestId: string
|
||||
action: ReconciliationAction
|
||||
expectedUpdatedAt: string
|
||||
evidenceReference: string
|
||||
note: string
|
||||
providerTaskId?: string
|
||||
credentialFingerprint?: string
|
||||
expectedCost?: string
|
||||
result?: Record<string, unknown>
|
||||
}
|
||||
|
||||
const root = '/api/admin/task-reconciliation'
|
||||
export const taskReconciliation = {
|
||||
list(page: number) { return enterprise<{ records: ReconciliationTask[]; total: number; page: number }>(`${root}?page=${page}`) },
|
||||
detail(id: string) { return enterprise<{ task: ReconciliationTask; history: ReconciliationReceipt[] }>(`${root}/${encodeURIComponent(id)}`) },
|
||||
quote(id: string, result: Record<string, unknown>) { return enterprise<{ expectedCost: string; expectedUpdatedAt: string }>(`${root}/${encodeURIComponent(id)}/quote`, result, 'POST') },
|
||||
submit(id: string, command: ReconciliationCommand) { return enterprise<{ task: ReconciliationTask; requestId: string; replayed: boolean }>(`${root}/${encodeURIComponent(id)}`, command, 'POST') },
|
||||
}
|
||||
|
||||
export { reconciliationPayload } from './task-reconciliation-state'
|
||||
Reference in new issue
Block a user