发送消息ok

This commit is contained in:
yml
2026-04-12 13:48:32 +08:00
parent 0029147bc4
commit 381d18f3c9
11 changed files with 608 additions and 4 deletions
@@ -115,3 +115,92 @@ export async function findLatestSuccessfulMessageDeliveryByTask(taskId, channel)
return result.rows[0] || null
}
export async function listMessageDeliveries({
page = 1,
pageSize = 20,
provider = '',
platform = '',
status = '',
shopId = '',
platformOrderId = '',
taskNo = '',
dateFrom = '',
dateTo = '',
} = {}) {
const offset = (page - 1) * pageSize
const filters = []
const params = []
if (provider) {
params.push(provider)
filters.push(`md.provider = $${params.length}`)
}
if (platform) {
params.push(platform)
filters.push(`md.platform = $${params.length}`)
}
if (status) {
params.push(status)
filters.push(`md.status = $${params.length}`)
}
if (shopId) {
params.push(shopId)
filters.push(`md.shop_id = $${params.length}`)
}
if (platformOrderId) {
params.push(`%${platformOrderId}%`)
filters.push(`md.platform_order_id ILIKE $${params.length}`)
}
if (taskNo) {
params.push(`%${taskNo}%`)
filters.push(`ft.task_no ILIKE $${params.length}`)
}
if (dateFrom) {
params.push(dateFrom)
filters.push(`md.created_at >= $${params.length}`)
}
if (dateTo) {
params.push(dateTo)
filters.push(`md.created_at <= $${params.length}`)
}
const whereClause = filters.length > 0 ? `WHERE ${filters.join(' AND ')}` : ''
const fromClause = `
FROM message_deliveries md
LEFT JOIN fulfillment_tasks ft ON ft.id = md.task_id
`
const totalResult = await query(
`SELECT COUNT(*)::int AS total ${fromClause} ${whereClause}`,
params,
)
params.push(pageSize)
params.push(offset)
const itemsResult = await query(
`
SELECT
md.*,
ft.task_no,
ft.task_status
${fromClause}
${whereClause}
ORDER BY md.id DESC
LIMIT $${params.length - 1} OFFSET $${params.length}
`,
params,
)
return {
items: itemsResult.rows,
total: Number(totalResult.rows[0]?.total || 0),
}
}
+2
View File
@@ -4,6 +4,7 @@ import authRouter from './admin/auth.js'
import auditLogsRouter from './admin/audit-logs.js'
import dashboardRouter from './admin/dashboard.js'
import inventoryRouter from './admin/inventory.js'
import messageDeliveriesRouter from './admin/message-deliveries.js'
import ordersRouter from './admin/orders.js'
import platformConfigRouter from './admin/platform-config.js'
import { requireAdminSession } from './admin/shared.js'
@@ -23,6 +24,7 @@ router.use(platformConfigRouter)
router.use(ordersRouter)
router.use(tasksRouter)
router.use(inventoryRouter)
router.use(messageDeliveriesRouter)
router.use(webhookEventsRouter)
router.use((req, res) => {
@@ -0,0 +1,17 @@
import { Router } from 'express'
import { getAdminMessageDeliveries } from '../../services/admin/admin-service.js'
import { createJsonHandler } from './shared.js'
const router = Router()
router.get('/message-deliveries', createJsonHandler(
(req) => getAdminMessageDeliveries(req.query),
{
successMessage: 'ok',
errorMessage: '读取消息发送记录失败',
scope: '[admin/message-deliveries]',
},
))
export default router
@@ -32,6 +32,7 @@ import {
} from '../../repositories/task-inventory-binding-repo.js'
import { createTaskEvent, listTaskEventsByTaskId } from '../../repositories/task-event-repo.js'
import { getWebhookEventById, listWebhookEvents, listWebhookEventsByOrderId } from '../../repositories/webhook-event-repo.js'
import { listMessageDeliveries } from '../../repositories/message-delivery-repo.js'
import { createHttpError } from '../../utils/http.js'
import { formatFenToAmount, normalizeFen, parseAmountToFen } from '../../utils/money.js'
import { nowIso } from '../../utils/time.js'
@@ -197,6 +198,28 @@ export async function getAdminTasks(query = {}) {
}
}
export async function getAdminMessageDeliveries(query = {}) {
const page = normalizePage(query.page)
const pageSize = normalizePageSize(query.pageSize)
const { items, total } = await listMessageDeliveries({
page,
pageSize,
provider: String(query.provider || '').trim(),
platform: String(query.platform || '').trim(),
status: String(query.status || '').trim(),
shopId: String(query.shopId || '').trim(),
platformOrderId: String(query.platformOrderId || '').trim(),
taskNo: String(query.taskNo || '').trim(),
dateFrom: normalizeDateQuery(query.dateFrom),
dateTo: normalizeDateQuery(query.dateTo, true),
})
return {
items: items.map(mapAdminMessageDeliveryListItem),
pagination: { page, pageSize, total },
}
}
export async function getAdminTaskDetail(taskId) {
const task = await getTaskById(Number(taskId))
@@ -1103,6 +1126,33 @@ function mapAdminFulfillmentBindingConfigItem(item) {
}
}
function mapAdminMessageDeliveryListItem(item) {
return {
deliveryId: Number(item.id),
provider: String(item.provider || '').trim(),
platform: String(item.platform || '').trim(),
shopId: String(item.shop_id || '').trim(),
shopName: String(item.shop_name || '').trim(),
channel: String(item.channel || '').trim(),
orderId: item.order_id ? Number(item.order_id) : null,
taskId: item.task_id ? Number(item.task_id) : null,
taskNo: String(item.task_no || '').trim(),
taskStatus: String(item.task_status || '').trim(),
platformOrderId: String(item.platform_order_id || '').trim(),
recipientKey: String(item.recipient_key || '').trim(),
messageContent: String(item.message_content || '').trim(),
claimUrl: String(item.claim_url || '').trim(),
status: String(item.status || '').trim(),
requestUrl: String(item.request_url || '').trim(),
responseStatus: Number(item.response_status || 0),
response: safeParseJson(item.response_json),
errorMessage: String(item.error_message || '').trim(),
sentAt: item.sent_at || null,
createdAt: item.created_at,
updatedAt: item.updated_at,
}
}
function matchesObservedProduct(binding, observed) {
const provider = String(binding?.provider || '').trim()
const platform = String(binding?.platform || '').trim()
@@ -28,7 +28,7 @@ export async function ensureAgisoXianyuClaimMessageDeliveredForTask({ order, tas
return { sent: false, skipped: true, reason: 'missing_endpoint_or_access_token_or_app_secret' }
}
const successful = findLatestSuccessfulMessageDeliveryByTask(task.id, AGISO_XIANYU_MESSAGE_CHANNEL)
const successful = await findLatestSuccessfulMessageDeliveryByTask(task.id, AGISO_XIANYU_MESSAGE_CHANNEL)
if (successful) {
return { sent: false, skipped: true, reason: 'already_sent', deliveryId: successful.id }
}
@@ -52,7 +52,7 @@ export async function ensureAgisoXianyuClaimMessageDeliveredForTask({ order, tas
apiVersion: String(config.apiVersion || '1').trim() || '1',
})
const createdAt = nowIso()
const delivery = createMessageDelivery({
const delivery = await createMessageDelivery({
provider: 'agiso',
platform: String(order.platform || '').trim() || 'unknown',
shopId: String(order.shop_id || '').trim(),
@@ -85,7 +85,7 @@ export async function ensureAgisoXianyuClaimMessageDeliveredForTask({ order, tas
const rawText = await response.text()
const parsed = safeParseJson(rawText)
const success = isAgisoSendSuccess(response.status, parsed)
const updated = updateMessageDelivery(delivery.id, {
const updated = await updateMessageDelivery(delivery.id, {
status: success ? 'success' : 'failed',
response_status: response.status,
response_json: JSON.stringify(parsed ?? { rawText }),
@@ -104,7 +104,7 @@ export async function ensureAgisoXianyuClaimMessageDeliveredForTask({ order, tas
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error || '发送消息失败')
updateMessageDelivery(delivery.id, {
await updateMessageDelivery(delivery.id, {
status: 'failed',
response_status: 0,
response_json: '{}',
+4
View File
@@ -68,6 +68,10 @@ const router = createRouter({
path: 'inventory',
component: () => import('@/views/admin/AdminInventoryView.vue'),
},
{
path: 'message-deliveries',
component: () => import('@/views/admin/AdminMessageDeliveriesView.vue'),
},
{
path: 'webhook-events',
component: () => import('@/views/admin/AdminWebhookEventsView.vue'),
+8
View File
@@ -5,6 +5,7 @@ import type {
AdminAuditLogItem,
AdminFulfillmentBindingConfigItem,
AdminInventoryItemListItem,
AdminMessageDeliveryListItem,
AdminObservedProductItem,
AdminTaskActionResponse,
AdminDashboardSummary,
@@ -154,6 +155,13 @@ export function fetchAdminInventoryItems(params?: Record<string, unknown>) {
return apiGet<{ items: AdminInventoryItemListItem[]; pagination: AdminPagination }>('/api/v1/admin/inventory', params)
}
export function fetchAdminMessageDeliveries(params?: Record<string, unknown>) {
return apiGet<{ items: AdminMessageDeliveryListItem[]; pagination: AdminPagination }>(
'/api/v1/admin/message-deliveries',
params,
)
}
export function importAdminInventoryItems(payload: Record<string, unknown>) {
return apiPost<{ total: number; created: number; duplicated: number }>('/api/v1/admin/inventory/import', payload)
}
+25
View File
@@ -371,6 +371,31 @@ export interface AdminInventoryItemListItem {
updatedAt: string
}
export interface AdminMessageDeliveryListItem {
deliveryId: number
provider: string
platform: string
shopId: string
shopName: string
channel: string
orderId: number | null
taskId: number | null
taskNo: string
taskStatus: string
platformOrderId: string
recipientKey: string
messageContent: string
claimUrl: string
status: string
requestUrl: string
responseStatus: number
response: Record<string, unknown>
errorMessage: string
sentAt: string | null
createdAt: string
updatedAt: string
}
export interface AdminWebhookEventListItem {
eventId: number
provider: string
+7
View File
@@ -40,6 +40,13 @@ export const adminInventoryCredentialTypeOptions = [
{ label: '纯文本凭据', value: 'text_credential' },
]
export const adminMessageDeliveryStatusOptions = [
{ label: '全部状态', value: '' },
{ label: '发送成功', value: 'success' },
{ label: '发送失败', value: 'failed' },
{ label: '等待发送', value: 'pending' },
]
export const adminWebhookProcessedOptions = [
{ label: '全部', value: '' },
{ label: '处理成功', value: '1' },
@@ -15,6 +15,7 @@ const navItems = computed(() => {
{ to: '/admin/orders', label: '订单' },
{ to: '/admin/tasks', label: '任务' },
{ to: '/admin/inventory', label: '库存' },
{ to: '/admin/message-deliveries', label: '消息发送' },
{ to: '/admin/webhook-events', label: 'Webhook' },
]
@@ -0,0 +1,401 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import AdminPaginationBar from '@/components/admin/AdminPaginationBar.vue'
import AdminStatusTag from '@/components/admin/AdminStatusTag.vue'
import { fetchAdminMessageDeliveries } from '@/services/admin'
import type { AdminMessageDeliveryListItem, AdminPagination } from '@/types/admin'
import { formatAdminDateTime } from '@/utils/admin-time'
import { adminMessageDeliveryStatusOptions } from '@/utils/admin-options'
const loading = ref(true)
const errorMessage = ref('')
const items = ref<AdminMessageDeliveryListItem[]>([])
const provider = ref('agiso')
const platform = ref('xianyu')
const status = ref('')
const shopId = ref('')
const platformOrderId = ref('')
const taskNo = ref('')
const dateFrom = ref('')
const dateTo = ref('')
const pagination = ref<AdminPagination>({
page: 1,
pageSize: 20,
total: 0,
})
const summary = computed(() => ({
successCount: items.value.filter((item) => item.status === 'success').length,
failedCount: items.value.filter((item) => item.status === 'failed').length,
pendingCount: items.value.filter((item) => item.status === 'pending').length,
}))
async function loadMessageDeliveries(page = pagination.value.page) {
loading.value = true
errorMessage.value = ''
try {
const response = await fetchAdminMessageDeliveries({
page,
pageSize: pagination.value.pageSize,
provider: provider.value.trim(),
platform: platform.value.trim(),
status: status.value.trim(),
shopId: shopId.value.trim(),
platformOrderId: platformOrderId.value.trim(),
taskNo: taskNo.value.trim(),
dateFrom: dateFrom.value.trim(),
dateTo: dateTo.value.trim(),
})
items.value = response.data.items
pagination.value = response.data.pagination
} catch (error) {
errorMessage.value = error instanceof Error ? error.message : '读取消息发送记录失败'
} finally {
loading.value = false
}
}
function resetFilters() {
provider.value = 'agiso'
platform.value = 'xianyu'
status.value = ''
shopId.value = ''
platformOrderId.value = ''
taskNo.value = ''
dateFrom.value = ''
dateTo.value = ''
void loadMessageDeliveries(1)
}
function formatResponse(item: AdminMessageDeliveryListItem) {
if (item.responseStatus <= 0 && !item.errorMessage) {
return '-'
}
const parts = []
if (item.responseStatus > 0) {
parts.push(`HTTP ${item.responseStatus}`)
}
const msg = String(item.response?.Error_Msg || item.response?.msg || item.response?.message || item.response?.error || '').trim()
if (msg) {
parts.push(msg)
}
return parts.join(' · ') || item.errorMessage || '-'
}
onMounted(loadMessageDeliveries)
</script>
<template>
<section class="admin-panel">
<header class="panel-header">
<div>
<h1>消息发送记录</h1>
<p>查看领取链接消息是否真正发出平台返回了什么失败原因是什么</p>
</div>
</header>
<section class="filter-bar">
<input v-model="provider" class="text-input" placeholder="服务商,如 agiso" />
<input v-model="platform" class="text-input" placeholder="业务平台,如 xianyu" />
<select v-model="status" class="text-input select-input">
<option v-for="option in adminMessageDeliveryStatusOptions" :key="option.value" :value="option.value">
{{ option.label }}
</option>
</select>
<input v-model="shopId" class="text-input" placeholder="店铺 ID" />
</section>
<section class="filter-bar">
<input v-model="platformOrderId" class="text-input" placeholder="平台订单号" />
<input v-model="taskNo" class="text-input" placeholder="任务号" />
<input v-model="dateFrom" class="text-input" type="date" placeholder="开始日期" />
<input v-model="dateTo" class="text-input" type="date" placeholder="结束日期" />
<el-button round type="primary" @click="() => loadMessageDeliveries(1)">查询</el-button>
<el-button round @click="resetFilters">清空</el-button>
</section>
<section v-if="!loading && items.length > 0" class="summary-grid">
<article class="summary-card">
<span class="summary-label">当前页成功</span>
<strong class="summary-value">{{ summary.successCount }}</strong>
</article>
<article class="summary-card">
<span class="summary-label">当前页失败</span>
<strong class="summary-value">{{ summary.failedCount }}</strong>
</article>
<article class="summary-card">
<span class="summary-label">当前页等待</span>
<strong class="summary-value">{{ summary.pendingCount }}</strong>
</article>
</section>
<p v-if="errorMessage" class="error-copy">{{ errorMessage }}</p>
<div v-if="loading" class="empty-block">消息发送记录加载中</div>
<div v-else-if="items.length === 0" class="empty-block">当前筛选下还没有消息发送记录</div>
<div v-else class="table-card">
<table class="data-table">
<thead>
<tr>
<th>ID</th>
<th>来源</th>
<th>订单 / 任务</th>
<th>发送状态</th>
<th>消息内容</th>
<th>Claim 链接</th>
<th>接口结果</th>
<th>时间</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items" :key="item.deliveryId">
<td>#{{ item.deliveryId }}</td>
<td>
<div class="cell-stack">
<div class="cell-title">{{ item.provider || '-' }} / {{ item.platform || '-' }}</div>
<div class="cell-subtle">{{ item.shopName || item.shopId || '-' }}</div>
<div class="cell-subtle">{{ item.channel || '-' }}</div>
</div>
</td>
<td>
<div class="cell-stack">
<div class="cell-title">{{ item.platformOrderId || '-' }}</div>
<div class="meta-chip-row">
<span v-if="item.orderId" class="meta-chip">
订单
<RouterLink class="inline-link" :to="`/admin/orders/${item.orderId}`">{{ item.orderId }}</RouterLink>
</span>
<span v-if="item.taskId" class="meta-chip">
任务
<RouterLink class="inline-link" :to="`/admin/tasks/${item.taskId}`">{{ item.taskNo || item.taskId }}</RouterLink>
</span>
</div>
<div v-if="item.taskStatus" class="tag-row">
<AdminStatusTag :status="item.taskStatus" />
</div>
</div>
</td>
<td>
<div class="cell-stack">
<div class="tag-row">
<AdminStatusTag :status="item.status" />
</div>
<div class="cell-subtle">HTTP {{ item.responseStatus || 0 }}</div>
<div v-if="item.errorMessage" class="error-inline">{{ item.errorMessage }}</div>
</div>
</td>
<td>
<div class="message-cell" :title="item.messageContent">
{{ item.messageContent || '-' }}
</div>
</td>
<td>
<a v-if="item.claimUrl" class="claim-link" :href="item.claimUrl" target="_blank" rel="noreferrer">
打开链接
</a>
<span v-else>-</span>
</td>
<td>
<div class="cell-stack">
<div class="cell-title">{{ formatResponse(item) }}</div>
<div v-if="item.requestUrl" class="cell-subtle">{{ item.requestUrl }}</div>
</div>
</td>
<td>
<div class="cell-stack">
<div class="cell-title">创建 {{ formatAdminDateTime(item.createdAt) }}</div>
<div class="cell-subtle">发送 {{ formatAdminDateTime(item.sentAt) }}</div>
<div class="cell-subtle">更新 {{ formatAdminDateTime(item.updatedAt) }}</div>
</div>
</td>
</tr>
</tbody>
</table>
<AdminPaginationBar
:page="pagination.page"
:page-size="pagination.pageSize"
:total="pagination.total"
:loading="loading"
@change="loadMessageDeliveries"
/>
</div>
</section>
</template>
<style scoped>
.admin-panel {
display: grid;
gap: 16px;
}
.panel-header h1 {
margin: 0;
color: #1d3555;
}
.panel-header p {
margin: 8px 0 0;
color: #64748b;
}
.filter-bar {
display: flex;
gap: 12px;
align-items: center;
}
.summary-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
}
.summary-card,
.table-card,
.empty-block,
.error-copy {
padding: 18px;
border-radius: 20px;
background: rgba(255, 255, 255, 0.94);
border: 1px solid rgba(86, 108, 138, 0.1);
}
.summary-card {
display: grid;
gap: 8px;
}
.summary-label {
color: #2559a7;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.04em;
}
.summary-value {
font-size: 30px;
line-height: 1;
color: #1d3555;
}
.error-copy {
color: #b42318;
}
.empty-block {
color: #64748b;
}
.text-input {
width: 100%;
min-height: 42px;
padding: 0 14px;
border-radius: 14px;
border: 1px solid rgba(86, 108, 138, 0.18);
background: rgba(255, 255, 255, 0.94);
}
.select-input {
appearance: none;
}
.data-table {
width: 100%;
border-collapse: collapse;
}
.data-table th,
.data-table td {
padding: 12px 10px;
text-align: left;
border-bottom: 1px solid rgba(86, 108, 138, 0.08);
color: #334155;
vertical-align: top;
}
.data-table th {
color: #64748b;
font-size: 13px;
}
.cell-stack {
display: grid;
gap: 6px;
}
.cell-title {
color: #1d3555;
font-weight: 700;
}
.cell-subtle {
color: #64748b;
}
.message-cell {
max-width: 360px;
white-space: pre-wrap;
word-break: break-word;
line-height: 1.6;
}
.claim-link,
.inline-link {
color: #175cd3;
text-decoration: none;
}
.meta-chip-row,
.tag-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.meta-chip {
display: inline-flex;
align-items: center;
gap: 4px;
min-height: 28px;
padding: 0 10px;
border-radius: 999px;
background: #f5f8fc;
color: #304866;
font-size: 12px;
}
.error-inline {
color: #b42318;
line-height: 1.6;
}
@media (max-width: 1180px) {
.summary-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 980px) {
.filter-bar,
.summary-grid {
grid-template-columns: minmax(0, 1fr);
display: grid;
}
.table-card {
overflow-x: auto;
}
.data-table {
min-width: 1200px;
}
}
</style>