fix(platform): 持久化并完善斗鱼兑换结果图片

This commit is contained in:
yml
2026-11-21 11:39:04 +08:00
parent 9c90a452c5
commit cd7eb78e01
14 changed files with 870 additions and 50 deletions
+9
View File
@@ -1,6 +1,7 @@
import api from './client';
import type {
DouyuConfig,
DouyuExchangeResultImage,
DouyuGoodsItem,
DouyuRechargeChannel,
DouyuTaskAccountItem,
@@ -55,6 +56,14 @@ export const douyuApi = {
listTasksPaged: (params: PageParams & { batch_id?: string; include_detail?: boolean }) =>
api.get<PaginatedResponse<DouyuTaskItem>, PaginatedResponse<DouyuTaskItem>>('/douyu/tasks', { params }),
getTask: (taskId: number) => api.get<DouyuTaskItem, DouyuTaskItem>(`/douyu/tasks/${taskId}`),
saveExchangeResultImage: (taskId: number, file: File) => {
const form = new FormData();
form.append('file', file);
return api.post<DouyuExchangeResultImage, DouyuExchangeResultImage>(
`/douyu/tasks/${taskId}/exchange-result-image`,
form,
);
},
cleanupOrphans: () =>
api.post<{ message: string; cleaned: number; success: boolean }, { message: string; cleaned: number; success: boolean }>('/douyu/tasks/cleanup-orphans'),
stopBatch: (batchId: string) => api.post<MessageResponse, MessageResponse>(`/douyu/stop/${batchId}`),
+12
View File
@@ -790,6 +790,12 @@ export interface DouyuTaskItem {
finished_at: string | null;
}
export interface DouyuExchangeResultImage {
object_key: string;
url: string;
saved_at: string;
}
export interface DouyuGoodsItem {
id: number;
commodity_id: string;
@@ -2238,6 +2244,12 @@ export interface PlatformFulfillmentTask {
account: PlatformFulfillmentAccount | null;
lease: { id: number; status: string; expiresAt: string | null } | null;
bindTask: PlatformFulfillmentBindTask | null;
exchangeTaskId: number | null;
exchangeResultImage: {
objectKey: string;
url: string;
savedAt: string | null;
} | null;
}
export interface PlatformFulfillmentEvent {
@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import { Button, Spin } from 'antd';
import type { DouyuTaskItem } from '../api/types';
import { getExchangeImage } from '../utils/exchangeImage';
import { getExchangeImage, savedExchangeImage } from '../utils/exchangeImage';
interface Props {
task: DouyuTaskItem;
@@ -13,15 +13,22 @@ export default function ExchangeResultImage({ task, onClick, variant = 'compact'
const [url, setUrl] = useState('');
const [failed, setFailed] = useState(false);
const [gen, setGen] = useState(0);
const savedObjectKey = savedExchangeImage(task)?.objectKey || '';
const taskRef = useRef(task);
useEffect(() => {
taskRef.current = task;
}, [task]);
useEffect(() => {
let alive = true;
setUrl('');
setFailed(false);
getExchangeImage(task)
getExchangeImage(taskRef.current)
.then(({ url }) => { if (alive) setUrl(url); })
.catch(() => { if (alive) setFailed(true); });
return () => { alive = false; };
}, [task, gen]);
}, [task.id, task.finished_at, savedObjectKey, gen]);
if (failed) {
return (
@@ -55,7 +62,7 @@ export default function ExchangeResultImage({ task, onClick, variant = 'compact'
detail
? {
width: '100%',
maxWidth: 320,
maxWidth: 480,
height: 'auto',
objectFit: 'contain',
borderRadius: 8,
@@ -1,13 +1,14 @@
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import { Alert, Button, Card, DatePicker, Descriptions, Drawer, Empty, Input, InputNumber, Modal, QRCode, Segmented, Select, Space, Switch, Table, Tabs, Tag, Timeline, Typography } from 'antd';
import { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons';
import { CheckCircleOutlined, CopyOutlined, CreditCardOutlined, DownloadOutlined, GiftOutlined, LinkOutlined, QrcodeOutlined, ReloadOutlined, SettingOutlined, ShoppingOutlined, SyncOutlined, UndoOutlined, UserSwitchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { douyuApi, platformFulfillmentApi } from '../api/modules';
import type { DouyuGoodsItem, DouyuTaskItem, PlatformFulfillmentDetail, PlatformFulfillmentMapping, PlatformFulfillmentSettings, PlatformFulfillmentTask } from '../api/modules';
import ExchangeResultImage from '../components/ExchangeResultImage';
import { copyImageToClipboard, fetchExchangeImageBlob, getExchangeImage, isExchangeTask } from '../utils/exchangeImage';
import { TASK_STATUS_COLORS, TASK_STATUS_LABELS, taskQrUrl } from './douyu-tasks/config';
import { getErrorMessage } from '../utils/error';
import { message } from '../utils/antdMessage';
@@ -342,6 +343,11 @@ export default function PlatformFulfillmentPage() {
const [douyuActionType, setDouyuActionType] = useState('');
const [douyuActionBatchId, setDouyuActionBatchId] = useState('');
const [douyuActionTask, setDouyuActionTask] = useState<DouyuTaskItem | null>(null);
const [exchangeImageViewer, setExchangeImageViewer] = useState<{
url: string;
title: string;
} | null>(null);
const exchangeImageSaveAttempts = useRef(new Set<number>());
const [goldAmount, setGoldAmount] = useState(30);
const [giftCount, setGiftCount] = useState(1);
@@ -427,6 +433,8 @@ export default function PlatformFulfillmentPage() {
}, [douyuActionBatchId]);
const selected = detail?.task || null;
const selectedExchangeTaskId = selected?.exchangeTaskId ?? null;
const selectedExchangeImageKey = selected?.exchangeResultImage?.objectKey || '';
const qrValue = selected?.bindTask?.qrUrl || '';
const douyuActionQrValue = douyuActionTask ? taskQrUrl(douyuActionTask) : '';
@@ -434,6 +442,31 @@ export default function PlatformFulfillmentPage() {
if (qrValue) setQrOpen(true);
}, [qrValue]);
useEffect(() => {
if (
!selectedId
|| !selectedExchangeTaskId
|| selectedExchangeImageKey
|| exchangeImageSaveAttempts.current.has(selectedExchangeTaskId)
) {
return;
}
exchangeImageSaveAttempts.current.add(selectedExchangeTaskId);
void douyuApi.getTask(selectedExchangeTaskId)
.then(async (task) => {
if (task.status !== 'success' || !isExchangeTask(task)) return false;
await getExchangeImage(task);
return true;
})
.then((saved) => {
if (saved) void loadDetail(selectedId, true);
})
.catch(() => {
// 图片补存失败不影响履约详情;下次重新打开详情时会再次尝试。
exchangeImageSaveAttempts.current.delete(selectedExchangeTaskId);
});
}, [selectedId, selectedExchangeTaskId, selectedExchangeImageKey, loadDetail]);
const sync = async () => {
setSyncing(true);
try {
@@ -652,6 +685,28 @@ export default function PlatformFulfillmentPage() {
void loadTasks();
};
const copyExchangeImageViewer = async (url = exchangeImageViewer?.url) => {
if (!url) return;
try {
const blob = await fetchExchangeImageBlob(url);
await copyImageToClipboard(blob);
message.success('兑换结果图片已复制');
} catch (error) {
message.error(`复制兑换结果图片失败:${getErrorMessage(error)}`);
}
};
const downloadExchangeImageViewer = (
url = exchangeImageViewer?.url,
title = exchangeImageViewer?.title,
) => {
if (!url) return;
const link = document.createElement('a');
link.href = url;
link.download = `${title || '斗鱼兑换结果'}.png`;
link.click();
};
const openMapping = async (task?: PlatformFulfillmentTask) => {
setMappingSku(task?.internalSkuKey || '');
setMappingGoodsId(task?.commodityId || '');
@@ -1147,6 +1202,55 @@ export default function PlatformFulfillmentPage() {
/>
) : null}
{selected.exchangeResultImage ? (
<Card
size="small"
title="兑换结果凭证"
extra={(
<Space>
<Button
size="small"
icon={<CopyOutlined />}
onClick={() => void copyExchangeImageViewer(selected.exchangeResultImage!.url)}
>
复制图片
</Button>
<Button
size="small"
icon={<DownloadOutlined />}
onClick={() => downloadExchangeImageViewer(
selected.exchangeResultImage!.url,
`斗鱼兑换结果-${selected.skuName || selected.platformOrderId}`,
)}
>
下载图片
</Button>
</Space>
)}
>
<div
onClick={() => setExchangeImageViewer({
url: selected.exchangeResultImage!.url,
title: `斗鱼兑换结果-${selected.skuName || selected.platformOrderId}`,
})}
style={{ cursor: 'zoom-in', textAlign: 'center' }}
title="点击查看大图"
>
<img
src={selected.exchangeResultImage.url}
alt="兑换结果凭证"
style={{
width: '100%',
maxWidth: 480,
height: 'auto',
borderRadius: 8,
border: '1px solid #f0f0f0',
}}
/>
</div>
</Card>
) : null}
<div
style={{
display: 'grid',
@@ -1348,7 +1452,14 @@ export default function PlatformFulfillmentPage() {
<QRCode value={douyuActionQrValue} size={260} />
) : null}
{douyuActionType === 'exchange_goods' && douyuActionTask.status === 'success' ? (
<ExchangeResultImage task={douyuActionTask} variant="detail" />
<ExchangeResultImage
task={douyuActionTask}
variant="detail"
onClick={(_task, url) => setExchangeImageViewer({
url,
title: `斗鱼兑换结果-${selected?.skuName || selected?.platformOrderId || douyuActionTask.id}`,
})}
/>
) : null}
</>
) : (
@@ -1357,6 +1468,33 @@ export default function PlatformFulfillmentPage() {
</Space>
</Modal>
<Modal
open={Boolean(exchangeImageViewer)}
title="兑换结果图片"
width={620}
centered
footer={(
<Space>
<Button onClick={() => setExchangeImageViewer(null)}>关闭</Button>
<Button icon={<CopyOutlined />} onClick={() => void copyExchangeImageViewer()}>
复制图片
</Button>
<Button icon={<DownloadOutlined />} onClick={() => downloadExchangeImageViewer()}>
下载图片
</Button>
</Space>
)}
onCancel={() => setExchangeImageViewer(null)}
>
{exchangeImageViewer ? (
<img
src={exchangeImageViewer.url}
alt="兑换结果"
style={{ width: '100%', maxHeight: '72vh', objectFit: 'contain', display: 'block' }}
/>
) : null}
</Modal>
<Modal open={qrOpen && Boolean(qrValue)} title="客户扫码绑定游戏角色" footer={null} onCancel={() => setQrOpen(false)}>
<Space direction="vertical" align="center" style={{ width: '100%' }}>
{qrValue ? <QRCode value={qrValue} size={260} /> : null}
+76 -3
View File
@@ -1,4 +1,5 @@
import type { DouyuTaskItem } from '../api/types';
import { douyuApi } from '../api/douyu';
const EXCHANGE_TASK_TYPES = new Set([
'exchange_goods',
@@ -124,6 +125,21 @@ function douyuImageData(task: DouyuTaskItem): ExchangeResultImageData {
};
}
export function savedExchangeImage(task: DouyuTaskItem): {
objectKey: string;
url: string;
} | null {
const saved = task.result?.exchange_result_image;
if (!saved || typeof saved !== 'object' || Array.isArray(saved)) return null;
const record = saved as Record<string, unknown>;
const objectKey = typeof record.object_key === 'string' ? record.object_key : '';
if (!objectKey) return null;
const url = typeof record.url === 'string' && record.url
? record.url
: `/api/files/object?key=${encodeURIComponent(objectKey)}`;
return { objectKey, url };
}
export async function drawExchangeResultImage(
data: ExchangeResultImageData,
): Promise<Blob> {
@@ -188,9 +204,9 @@ export async function drawExchangeResultImage(
ctx.stroke();
// 商品名(最多两行)
const nameLines = wrapText(ctx, info.goodsName || '未知商品', CARD_W - 56).slice(0, 2);
ctx.fillStyle = '#ffffff';
ctx.font = `bold 17px ${FONT_FAMILY}`;
const nameLines = wrapText(ctx, info.goodsName || '未知商品', CARD_W - 56).slice(0, 2);
let nameY = avatarY + avatarR + 26;
for (const line of nameLines) {
ctx.fillText(line, CARD_W / 2, nameY);
@@ -259,6 +275,14 @@ export async function copyImageToClipboard(blob: Blob): Promise<void> {
await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]);
}
export async function fetchExchangeImageBlob(url: string): Promise<Blob> {
const response = await fetch(url, { credentials: 'include' });
if (!response.ok) throw new Error(`图片读取失败(HTTP ${response.status})`);
const blob = await response.blob();
if (!blob.type.startsWith('image/')) throw new Error('返回内容不是图片');
return blob;
}
export function clipboardImageSupported(): boolean {
return typeof ClipboardItem !== 'undefined' && Boolean(navigator.clipboard?.write);
}
@@ -296,10 +320,59 @@ export async function getExchangeResultImage(
}
export async function getExchangeImage(task: DouyuTaskItem): Promise<CachedImage> {
return getExchangeResultImage(douyuImageData(task));
const saved = savedExchangeImage(task);
if (saved) {
const cacheKey = `douyu:${task.id}:saved:${saved.objectKey}`;
const cached = imageCache.get(cacheKey);
if (cached) return cached;
const pending = inflightImages.get(cacheKey);
if (pending) return pending;
const creating = fetchExchangeImageBlob(saved.url).then((blob) => {
const entry = { url: saved.url, blob };
imageCache.set(cacheKey, entry);
return entry;
});
inflightImages.set(cacheKey, creating);
try {
return await creating;
} finally {
inflightImages.delete(cacheKey);
}
}
const cacheKey = `douyu:${task.id}:generated`;
const cached = imageCache.get(cacheKey);
if (cached) return cached;
const pending = inflightImages.get(cacheKey);
if (pending) return pending;
const creating = (async () => {
const blob = await drawExchangeResultImage(douyuImageData(task));
let url = URL.createObjectURL(blob);
try {
const file = new File([blob], `douyu-exchange-result-${task.id}.png`, {
type: 'image/png',
});
const savedImage = await douyuApi.saveExchangeResultImage(task.id, file);
URL.revokeObjectURL(url);
url = savedImage.url;
} catch (error) {
console.warn('兑换结果图片保存失败,暂时保留本地图片', error);
}
const entry = { url, blob };
imageCache.set(cacheKey, entry);
return entry;
})();
inflightImages.set(cacheKey, creating);
try {
return await creating;
} finally {
inflightImages.delete(cacheKey);
}
}
export function clearExchangeImageCache(): void {
for (const entry of imageCache.values()) URL.revokeObjectURL(entry.url);
for (const entry of imageCache.values()) {
if (entry.url.startsWith('blob:')) URL.revokeObjectURL(entry.url);
}
imageCache.clear();
}