refactor: 按甲方确认重构为一款多码(档案编号标识款、批次码、按款统计)

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Nixevol
2026-06-30 12:02:44 +08:00
co-authored by Cursor
parent 67c5887f8f
commit a16e6f1165
34 changed files with 445 additions and 353 deletions
+1 -3
View File
@@ -46,12 +46,10 @@ export const artworkApi = {
};
export const traceCodeApi = {
generate: (data: { quantity: number; batchNo?: string; groupId?: number }) =>
generate: (data: { artworkId: number; quantity: number; batchNo?: string; groupId?: number }) =>
post('/trace-codes/batch', data),
batches: (params: object) => get<PageResult<any>>('/batches', params),
list: (params: object) => get<PageResult<any>>('/trace-codes', params),
bind: (id: string, artworkId: number) => put(`/trace-codes/${id}/bind`, { artworkId }),
unbind: (id: string) => put(`/trace-codes/${id}/unbind`, {}),
qrUrl: (id: string) => `/api/trace-codes/${id}/qrcode`,
onchain: (id: string) => post(`/trace-codes/${id}/onchain`, {}),
// 分组
+12 -5
View File
@@ -141,7 +141,7 @@
},
"dashboard": {
"totalArtworks": "Artworks",
"boundCodes": "Bound Codes",
"totalCodes": "Total Codes",
"activatedCodes": "Activated Codes",
"totalQueries": "Total Queries",
"todayQueries": "Today",
@@ -183,6 +183,16 @@
"title": "Title",
"artist": "Artist",
"template": "Template",
"archiveNo": "Archive No.",
"codeCount": "Codes",
"activeCount": "Activated",
"queryTotal": "Total Queries",
"traceCodes": "Trace Codes (multi-code)",
"genCodes": "Generate Codes",
"viewCodes": "View All Codes",
"batches": "Batches",
"selectArtwork": "Select Artwork",
"selectArtworkTip": "Search by archive no. / title to pick an artwork",
"images": "Images / Videos",
"mediaHint": "Images and videos supported. Drag to reorder (order = display order on the consumer page).",
"basicInfo": "Basic Info",
@@ -207,9 +217,7 @@
"certType": "Type",
"originFile": "Original File",
"watermarkPreview": "Watermark",
"watermarkPending": "Generating watermark…",
"bindCode": "Bind Trace Code",
"noTrace": "No trace code bound"
"watermarkPending": "Generating watermark…"
},
"traceCode": {
"batches": "Batches",
@@ -221,7 +229,6 @@
"shortCode": "Short Code",
"code": "Trace Code",
"url": "Short URL",
"archiveNo": "Archive No.",
"queryCount": "Queries",
"firstActivatedAt": "First Activated",
"exportBatch": "Export Batch",
+12 -5
View File
@@ -141,7 +141,7 @@
},
"dashboard": {
"totalArtworks": "作品总数",
"boundCodes": "已绑定追溯码",
"totalCodes": "追溯码总数",
"activatedCodes": "已激活追溯码",
"totalQueries": "总查询次数",
"todayQueries": "今日查询",
@@ -183,6 +183,16 @@
"title": "作品名称",
"artist": "艺术家",
"template": "所属模板",
"archiveNo": "档案编号",
"codeCount": "追溯码数",
"activeCount": "已激活",
"queryTotal": "查询总数",
"traceCodes": "追溯码(一款多码)",
"genCodes": "生成追溯码",
"viewCodes": "查看全部码",
"batches": "批次列表",
"selectArtwork": "选择作品",
"selectArtworkTip": "搜索档案号 / 作品名选择作品(款)",
"images": "作品图片 / 视频",
"mediaHint": "支持图片与视频,拖拽可调整顺序(顺序即 C 端展示顺序)",
"basicInfo": "基础信息",
@@ -207,9 +217,7 @@
"certType": "类型",
"originFile": "原始文件",
"watermarkPreview": "水印预览",
"watermarkPending": "水印生成中…",
"bindCode": "绑定追溯码",
"noTrace": "未绑定追溯码"
"watermarkPending": "水印生成中…"
},
"traceCode": {
"batches": "批次列表",
@@ -221,7 +229,6 @@
"shortCode": "短码",
"code": "追溯码",
"url": "短链",
"archiveNo": "档案编号",
"queryCount": "查询次数",
"firstActivatedAt": "首次激活时间",
"exportBatch": "导出本批",
+88 -82
View File
@@ -185,52 +185,56 @@
</n-card>
</n-grid-item>
<!-- 追溯码与区块链 -->
<!-- 追溯码(一款多码) -->
<n-grid-item>
<n-card :title="t('pages.artwork.traceCode') + ' / ' + t('pages.blockchain.title')" :bordered="false">
<div v-if="artwork?.traceCode">
<n-descriptions :column="3" label-placement="left" bordered size="small">
<n-descriptions-item :label="t('pages.traceCode.shortCode')">{{ artwork.traceCode.shortCode }}</n-descriptions-item>
<n-descriptions-item :label="t('common.label.status')">
<n-tag size="small" :type="statusType(artwork.traceCode.status)">{{ t(`common.status.${artwork.traceCode.status}`) }}</n-tag>
</n-descriptions-item>
<n-descriptions-item :label="t('pages.traceCode.queryCount')">{{ artwork.traceCode.queryCount }}</n-descriptions-item>
</n-descriptions>
<div style="margin-top:12px; display:flex; gap:8px; flex-wrap:wrap">
<n-button v-if="auth.canWrite" size="small" @click="unbind">{{ t('common.action.unbind') }}</n-button>
<n-button v-if="auth.canWrite" size="small" type="primary" :loading="onchainLoading" @click="onchain">
<template #icon><n-icon :component="LinkOutline" /></template>
{{ t('common.action.onchain') }}
<n-card :title="t('pages.artwork.traceCodes')" :bordered="false">
<template #header-extra>
<n-space>
<n-button v-if="auth.canWrite" size="small" type="primary" @click="genModal = true">
<template #icon><n-icon :component="AddOutline" /></template>
{{ t('pages.artwork.genCodes') }}
</n-button>
</div>
<n-data-table
v-if="artwork.traceCode.proofs?.length"
style="margin-top:12px"
size="small"
:columns="proofColumns"
:data="artwork.traceCode.proofs"
:row-key="(r) => r.id"
/>
</div>
<div v-else>
<n-empty :description="t('pages.artwork.noTrace')" />
<div v-if="auth.canWrite" style="margin-top:12px; display:flex; gap:8px; align-items:center">
<n-select
v-model:value="bindCodeId"
:options="unboundOptions"
filterable
:placeholder="t('pages.traceCode.shortCode')"
style="width: 240px"
@focus="loadUnbound"
/>
<n-button type="primary" :disabled="!bindCodeId" @click="bind">{{ t('pages.artwork.bindCode') }}</n-button>
</div>
</div>
<n-button size="small" @click="goCodes">{{ t('pages.artwork.viewCodes') }}</n-button>
</n-space>
</template>
<n-descriptions :column="4" label-placement="top" bordered size="small">
<n-descriptions-item :label="t('pages.artwork.archiveNo')">{{ artwork?.archiveNo || '-' }}</n-descriptions-item>
<n-descriptions-item :label="t('pages.artwork.codeCount')">{{ artwork?.codeStats?.total ?? 0 }}</n-descriptions-item>
<n-descriptions-item :label="t('pages.artwork.activeCount')">{{ artwork?.codeStats?.active ?? 0 }}</n-descriptions-item>
<n-descriptions-item :label="t('pages.artwork.queryTotal')">{{ artwork?.codeStats?.queryTotal ?? 0 }}</n-descriptions-item>
</n-descriptions>
<div class="batch-title">{{ t('pages.artwork.batches') }}</div>
<n-empty v-if="!artwork?.batches?.length" :description="t('common.msg.noData')" size="small" />
<n-data-table
v-else
size="small"
:columns="batchColumns"
:data="artwork.batches"
:row-key="(r) => r.id"
/>
</n-card>
</n-grid-item>
</template>
</n-grid>
<!-- 生码弹窗 -->
<n-modal v-model:show="genModal" preset="card" :title="t('pages.artwork.genCodes')" style="width:420px">
<n-form :model="genForm" label-placement="top">
<n-form-item :label="t('pages.traceCode.quantity')">
<n-input-number v-model:value="genForm.quantity" :min="1" :max="10000" style="width:100%" />
</n-form-item>
<n-form-item :label="t('pages.traceCode.batchNo')">
<n-input v-model:value="genForm.batchNo" placeholder="(auto)" />
</n-form-item>
</n-form>
<template #footer>
<div style="text-align:right">
<n-button class="mr8" @click="genModal = false">{{ t('common.action.cancel') }}</n-button>
<n-button type="primary" :loading="generating" @click="genCodes">{{ t('common.action.generate') }}</n-button>
</div>
</template>
</n-modal>
<!-- 节点弹窗 -->
<n-modal v-model:show="nodeModal" preset="card" :title="t('pages.artwork.addNode')" style="width:560px;max-width:94vw">
<n-form :model="nodeForm" label-placement="top">
@@ -297,9 +301,9 @@ import { computed, h, onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { NTag, type DataTableColumns, type FormInst, type FormRules } from 'naive-ui';
import { ArrowBackOutline, AddOutline, LinkOutline } from '@vicons/ionicons5';
import { ArrowBackOutline, AddOutline } from '@vicons/ionicons5';
import { ArtworkStatus, CertType, NodeType } from '@artveris/shared';
import { artworkApi, templateApi, traceCodeApi } from '@/api';
import { artworkApi, templateApi, traceCodeApi, jobApi } from '@/api';
import { useAuthStore } from '@/stores/auth';
import MediaUpload from '@/components/MediaUpload.vue';
import MediaSorter from '@/components/MediaSorter.vue';
@@ -334,18 +338,6 @@ const artwork = ref<any>(null);
const nodes = ref<any[]>([]);
const certs = ref<any[]>([]);
const proofColumns: DataTableColumns<any> = [
{ title: () => t('pages.blockchain.txHash'), key: 'txHash', ellipsis: { tooltip: true }, render: (r) => r.txHash || '-' },
{ title: () => t('pages.blockchain.blockHeight'), key: 'blockHeight', width: 120, render: (r) => r.blockHeight || '-' },
{
title: () => t('common.label.status'),
key: 'status',
width: 100,
render: (r) => h(NTag, { size: 'small', type: statusType(r.status) }, { default: () => t(`common.status.${r.status}`) }),
},
{ title: () => t('pages.blockchain.onchainAt'), key: 'onchainAt', width: 160, render: (r) => fmt(r.onchainAt) },
];
function onTemplateChange() {
form.dynamicFields = {};
}
@@ -515,39 +507,48 @@ function removeCert(c: any) {
});
}
/* 追溯码 / 区块链 */
const bindCodeId = ref<string | null>(null);
const unbound = ref<any[]>([]);
const unboundOptions = computed(() => unbound.value.map((c) => ({ label: c.shortCode, value: c.id })));
const onchainLoading = ref(false);
async function loadUnbound() {
const res: any = await traceCodeApi.list({ status: 'UNBOUND', pageSize: 50 });
unbound.value = res.list;
}
async function bind() {
if (!bindCodeId.value) return;
await traceCodeApi.bind(bindCodeId.value, artworkId.value);
message.success(t('common.msg.saved'));
bindCodeId.value = null;
await loadArtwork();
}
async function unbind() {
if (!artwork.value?.traceCode) return;
await traceCodeApi.unbind(String(artwork.value.traceCode.id));
message.success(t('common.msg.saved'));
await loadArtwork();
}
async function onchain() {
if (!artwork.value?.traceCode) return;
onchainLoading.value = true;
/* 追溯码(一款多码):生码 + 批次 */
const batchColumns: DataTableColumns<any> = [
{ title: () => t('pages.traceCode.batchNo'), key: 'batchNo' },
{ title: () => t('pages.traceCode.quantity'), key: 'quantity', width: 90 },
{ title: () => t('pages.traceCode.generatedCount'), key: 'generatedCount', width: 90 },
{
title: () => t('common.label.status'),
key: 'status',
width: 100,
render: (r) => h(NTag, { size: 'small', type: statusType(r.status) }, { default: () => t(`common.status.${r.status}`) }),
},
{ title: () => t('common.label.createdAt'), key: 'createdAt', width: 160, render: (r) => fmt(r.createdAt) },
];
const genModal = ref(false);
const generating = ref(false);
const genForm = reactive<{ quantity: number; batchNo: string }>({ quantity: 100, batchNo: '' });
async function genCodes() {
generating.value = true;
try {
await traceCodeApi.onchain(String(artwork.value.traceCode.id));
message.success(t('pages.blockchain.triggered'));
setTimeout(loadArtwork, 1500);
const res: any = await traceCodeApi.generate({
artworkId: artworkId.value,
quantity: genForm.quantity,
batchNo: genForm.batchNo || undefined,
});
message.success(t('pages.traceCode.genSuccess'));
for (let i = 0; i < 30; i++) {
await new Promise((r) => setTimeout(r, 700));
const job: any = await jobApi.get(res.jobId);
if (['SUCCESS', 'FAILED', 'PARTIAL'].includes(job.status)) break;
}
genModal.value = false;
genForm.batchNo = '';
await loadArtwork();
} finally {
onchainLoading.value = false;
generating.value = false;
}
}
function goCodes() {
router.push({ name: 'traceCodes', query: { artworkId: String(artworkId.value) } });
}
onMounted(async () => {
await loadTemplates();
@@ -563,6 +564,11 @@ onMounted(async () => {
.mr8 {
margin-right: 8px;
}
.batch-title {
font-size: 13px;
color: #6b7280;
margin: 14px 0 8px;
}
.node-head {
display: flex;
justify-content: space-between;
+5 -11
View File
@@ -75,18 +75,12 @@ const columns: DataTableColumns<any> = [
? h(NAvatar, { src: r.images[0].url, size: 44, style: 'border-radius:8px' })
: h(NAvatar, { size: 44, style: 'border-radius:8px' }, { default: () => '—' }),
},
{ title: () => t('pages.artwork.archiveNo'), key: 'archiveNo', width: 140, render: (r) => r.archiveNo || '-' },
{ title: () => t('pages.artwork.title'), key: 'title', ellipsis: { tooltip: true } },
{ title: () => t('pages.artwork.artist'), key: 'artist', width: 120, render: (r) => r.artist || '-' },
{ title: () => t('pages.artwork.template'), key: 'template', width: 130, render: (r) => r.template?.name || '-' },
{
title: () => t('pages.artwork.traceCode'),
key: 'traceCode',
width: 130,
render: (r) =>
r.traceCode
? h(NTag, { size: 'small', type: statusType(r.traceCode.status) }, { default: () => r.traceCode.shortCode })
: h(NTag, { size: 'small' }, { default: () => t('pages.artwork.noTrace') }),
},
{ title: () => t('pages.artwork.artist'), key: 'artist', width: 110, render: (r) => r.artist || '-' },
{ title: () => t('pages.artwork.template'), key: 'template', width: 120, render: (r) => r.template?.name || '-' },
{ title: () => t('pages.artwork.codeCount'), key: 'codeCount', width: 80, render: (r) => r.codeCount ?? 0 },
{ title: () => t('pages.artwork.queryTotal'), key: 'queryTotal', width: 90, render: (r) => r.queryTotal ?? 0 },
{
title: () => t('common.label.status'),
key: 'status',
+9 -2
View File
@@ -27,7 +27,9 @@
<n-list-item v-for="(item, i) in data.topArtworks" :key="i">
<div class="top-row">
<n-tag :type="i < 3 ? 'warning' : 'default'" size="small" round>{{ i + 1 }}</n-tag>
<span class="top-title text-ellipsis">{{ item.title }}</span>
<span class="top-title text-ellipsis">
<span v-if="item.archiveNo" class="top-archive">{{ item.archiveNo }}</span>{{ item.title }}
</span>
<span class="top-count">{{ item.queryCount }}</span>
</div>
</n-list-item>
@@ -63,7 +65,7 @@ const data = ref<any>(null);
const stats = computed(() => [
{ key: 'totalArtworks', label: t('pages.dashboard.totalArtworks'), icon: ImagesOutline, color: '#1f3864' },
{ key: 'boundCodes', label: t('pages.dashboard.boundCodes'), icon: QrCodeOutline, color: '#2e5496' },
{ key: 'totalCodes', label: t('pages.dashboard.totalCodes'), icon: QrCodeOutline, color: '#2e5496' },
{ key: 'activatedCodes', label: t('pages.dashboard.activatedCodes'), icon: CheckmarkCircleOutline, color: '#138a72' },
{ key: 'totalQueries', label: t('pages.dashboard.totalQueries'), icon: SearchOutline, color: '#3a7bd5' },
{ key: 'todayQueries', label: t('pages.dashboard.todayQueries'), icon: TodayOutline, color: '#b9851f' },
@@ -144,6 +146,11 @@ onMounted(async () => {
.top-title {
flex: 1 1 auto;
}
.top-archive {
color: var(--brand);
font-size: 12px;
margin-right: 6px;
}
.top-count {
font-weight: 600;
color: var(--brand);
+1 -13
View File
@@ -19,12 +19,6 @@
/>
</n-form-item>
<n-grid :cols="2" :x-gap="16">
<n-form-item-gi :label="t('pages.outbound.sku')">
<n-input v-model:value="form.sku" />
</n-form-item-gi>
<n-form-item-gi :label="t('pages.outbound.archiveNo')">
<n-input v-model:value="form.archiveNo" />
</n-form-item-gi>
<n-form-item-gi :label="t('pages.outbound.outTime')">
<n-date-picker v-model:formatted-value="form.outTime" value-format="yyyy-MM-dd HH:mm" type="datetime" clearable style="width: 100%" />
</n-form-item-gi>
@@ -120,8 +114,6 @@ const codeOptions = ref<{ label: string; value: string }[]>([]);
const outImages = ref<any[]>([]);
const form = reactive<any>({
traceCodeId: null,
sku: '',
archiveNo: '',
outTime: null,
remark: '',
txHash: '',
@@ -137,7 +129,7 @@ function searchCodes(keyword: string) {
try {
const res: any = await traceCodeApi.list({ keyword: keyword || undefined, pageSize: 20 });
codeOptions.value = res.list.map((c: any) => ({
label: `${c.shortCode}${c.artwork ? ' · ' + c.artwork.title : ''}${c.sku ? ' · ' + c.sku : ''}`,
label: `${c.shortCode}${c.artwork ? ' · ' + (c.artwork.archiveNo || c.artwork.title) : ''}`,
value: String(c.id),
raw: c,
}));
@@ -149,8 +141,6 @@ function searchCodes(keyword: string) {
function onPickCode(_id: string, opt: any) {
const c = opt?.raw;
if (!c) return;
form.sku = c.sku || '';
form.archiveNo = c.archiveNo || '';
form.remark = c.remark || '';
outImages.value = c.outImage ? [{ key: c.outImage, url: c.outImage, name: c.outImage }] : [];
}
@@ -159,8 +149,6 @@ async function saveSingle() {
saving.value = true;
try {
await outboundApi.updateSingle(form.traceCodeId, {
sku: form.sku || undefined,
archiveNo: form.archiveNo || undefined,
outTime: form.outTime ? new Date(form.outTime).toISOString() : undefined,
outImageKey: outImages.value[0]?.key || undefined,
txHash: form.txHash || undefined,
+7 -8
View File
@@ -9,10 +9,10 @@
@keyup.enter="onSearch"
/>
<n-input
v-model:value="query.sku"
placeholder="SKU"
v-model:value="query.archiveNo"
:placeholder="t('pages.artwork.archiveNo')"
clearable
style="width: 130px"
style="width: 150px"
@keyup.enter="onSearch"
/>
<n-input
@@ -69,9 +69,9 @@ const { t } = useI18n();
const rows = ref<any[]>([]);
const loading = ref(false);
const range = ref<[number, number] | null>(null);
const query = reactive<{ keyword: string; sku: string; batchNo: string; result: string | null; startTime?: string; endTime?: string; page: number; pageSize: number }>({
const query = reactive<{ keyword: string; archiveNo: string; batchNo: string; result: string | null; startTime?: string; endTime?: string; page: number; pageSize: number }>({
keyword: '',
sku: '',
archiveNo: '',
batchNo: '',
result: null,
page: 1,
@@ -82,8 +82,7 @@ const resultOptions = Object.values(QueryResult).map((v) => ({ label: t(`common.
const columns: DataTableColumns<any> = [
{ title: () => t('pages.traceCode.shortCode'), key: 'shortCode', width: 120, render: (r) => r.shortCode || '-' },
{ title: 'SKU', key: 'sku', width: 120, render: (r) => r.sku || '-' },
{ title: () => t('pages.traceCode.archiveNo'), key: 'archiveNo', width: 110, render: (r) => r.archiveNo || '-' },
{ title: () => t('pages.artwork.archiveNo'), key: 'archiveNo', width: 140, render: (r) => r.archiveNo || '-' },
{ title: () => t('pages.traceCode.batchNo'), key: 'batchNo', width: 130, render: (r) => r.batchNo || '-' },
{
title: () => t('pages.queryLog.result'),
@@ -113,7 +112,7 @@ async function load() {
try {
const res: any = await queryLogApi.list({
keyword: query.keyword || undefined,
sku: query.sku || undefined,
archiveNo: query.archiveNo || undefined,
batchNo: query.batchNo || undefined,
result: query.result || undefined,
startTime: query.startTime,
+50 -5
View File
@@ -82,6 +82,18 @@
<!-- 生成 -->
<n-modal v-model:show="genModal" preset="card" :title="t('pages.traceCode.generate')" style="width: 440px">
<n-form :model="genForm" label-placement="top">
<n-form-item :label="t('pages.artwork.selectArtwork')" required>
<n-select
v-model:value="genForm.artworkId"
filterable
remote
clearable
:loading="artworkSearching"
:options="artworkOptions"
:placeholder="t('pages.artwork.selectArtworkTip')"
@search="searchArtworks"
/>
</n-form-item>
<n-form-item :label="t('pages.traceCode.quantity')">
<n-input-number v-model:value="genForm.quantity" :min="1" :max="10000" style="width: 100%" />
</n-form-item>
@@ -135,23 +147,26 @@
<script setup lang="ts">
import { computed, h, onMounted, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { NButton, NIcon, NTag, NText, type DataTableColumns } from 'naive-ui';
import { SearchOutline, AddOutline, DownloadOutline, QrCodeOutline, FolderOutline, OpenOutline } from '@vicons/ionicons5';
import { TraceCodeStatus } from '@artveris/shared';
import { traceCodeApi, jobApi } from '@/api';
import { traceCodeApi, jobApi, artworkApi } from '@/api';
import { useAuthStore } from '@/stores/auth';
import { message, dialog } from '@/utils/feedback';
import { fmt, statusType } from '@/utils/format';
import { downloadFile } from '@/utils/download';
const { t } = useI18n();
const route = useRoute();
const auth = useAuthStore();
const rows = ref<any[]>([]);
const loading = ref(false);
const checkedKeys = ref<Array<string | number>>([]);
const query = reactive<{ groupId: number | null; batchId: number | null; status: string | null; keyword: string; page: number; pageSize: number }>({
const query = reactive<{ artworkId: number | null; groupId: number | null; batchId: number | null; status: string | null; keyword: string; page: number; pageSize: number }>({
artworkId: null,
groupId: null,
batchId: null,
status: null,
@@ -174,7 +189,26 @@ const groupAssignOptions = computed(() => [
const genModal = ref(false);
const generating = ref(false);
const genForm = reactive<{ quantity: number; batchNo: string; groupId: number | null }>({ quantity: 100, batchNo: '', groupId: null });
const genForm = reactive<{ artworkId: number | null; quantity: number; batchNo: string; groupId: number | null }>({ artworkId: null, quantity: 100, batchNo: '', groupId: null });
const artworkSearching = ref(false);
const artworkOptions = ref<{ label: string; value: number }[]>([]);
let artworkTimer: ReturnType<typeof setTimeout> | null = null;
function searchArtworks(keyword: string) {
if (artworkTimer) clearTimeout(artworkTimer);
artworkTimer = setTimeout(async () => {
artworkSearching.value = true;
try {
const res: any = await artworkApi.list({ keyword: keyword || undefined, pageSize: 20 });
artworkOptions.value = res.list.map((a: any) => ({
label: `${a.archiveNo || '-'} · ${a.title}`,
value: a.id,
}));
} finally {
artworkSearching.value = false;
}
}, 300);
}
const qrModal = ref(false);
const qrSrc = ref('');
@@ -198,8 +232,9 @@ const columns = computed<DataTableColumns<any>>(() => [
[r.url, h(NIcon, { component: OpenOutline, style: 'vertical-align:-2px;margin-left:4px' })],
),
},
{ title: () => t('pages.traceCode.group'), key: 'group', width: 110, render: (r) => r.group?.name || h(NText, { depth: 3 }, { default: () => t('pages.traceCode.noGroup') }) },
{ title: () => t('pages.artwork.title'), key: 'artwork', width: 140, render: (r) => r.artwork?.title || '-' },
{ title: () => t('pages.traceCode.group'), key: 'group', width: 100, render: (r) => r.group?.name || h(NText, { depth: 3 }, { default: () => t('pages.traceCode.noGroup') }) },
{ title: () => t('pages.artwork.archiveNo'), key: 'archiveNo', width: 130, render: (r) => r.artwork?.archiveNo || '-' },
{ title: () => t('pages.artwork.title'), key: 'artwork', width: 130, render: (r) => r.artwork?.title || '-' },
{
title: () => t('common.label.status'),
key: 'status',
@@ -230,6 +265,7 @@ async function load() {
checkedKeys.value = [];
try {
const res: any = await traceCodeApi.list({
artworkId: query.artworkId || undefined,
groupId: query.groupId || undefined,
batchId: query.batchId || undefined,
status: query.status || undefined,
@@ -254,9 +290,14 @@ function onPage(p: number) {
}
async function generate() {
if (!genForm.artworkId) {
message.error(t('pages.artwork.selectArtworkTip'));
return;
}
generating.value = true;
try {
const res: any = await traceCodeApi.generate({
artworkId: genForm.artworkId,
quantity: genForm.quantity,
batchNo: genForm.batchNo || undefined,
groupId: genForm.groupId || undefined,
@@ -300,6 +341,7 @@ async function onExport(key: string) {
if (scope === 'selected') {
params.ids = checkedKeys.value.map(String).join(',');
} else {
if (query.artworkId) params.artworkId = query.artworkId;
if (query.groupId) params.groupId = query.groupId;
if (query.batchId) params.batchId = query.batchId;
if (query.status) params.status = query.status;
@@ -356,6 +398,9 @@ function removeGroup(g: any) {
}
onMounted(async () => {
// 支持从作品详情跳转:?artworkId=xx 直接筛选该款的码
const aid = Number(route.query.artworkId);
if (aid) query.artworkId = aid;
await Promise.all([loadBatches(), loadGroups()]);
await load();
});
@@ -1,18 +0,0 @@
-- AlterTable
ALTER TABLE `trace_code` ADD COLUMN `group_id` INTEGER NULL;
-- CreateTable
CREATE TABLE `trace_code_group` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(191) NOT NULL,
`remark` VARCHAR(191) NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateIndex
CREATE INDEX `trace_code_group_id_idx` ON `trace_code`(`group_id`);
-- AddForeignKey
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_group_id_fkey` FOREIGN KEY (`group_id`) REFERENCES `trace_code_group`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
@@ -1,24 +0,0 @@
-- AlterTable
ALTER TABLE `artwork` ADD COLUMN `audit_remark` VARCHAR(191) NULL,
ADD COLUMN `audit_status` ENUM('PENDING', 'APPROVED', 'REJECTED') NOT NULL DEFAULT 'PENDING',
ADD COLUMN `audited_at` DATETIME(3) NULL,
ADD COLUMN `audited_by` INTEGER NULL;
-- AlterTable
ALTER TABLE `query_log` ADD COLUMN `archive_no` VARCHAR(191) NULL,
ADD COLUMN `batch_no` VARCHAR(191) NULL,
ADD COLUMN `browser` VARCHAR(191) NULL,
ADD COLUMN `code` VARCHAR(191) NULL,
ADD COLUMN `first_activated_at` DATETIME(3) NULL,
ADD COLUMN `os` VARCHAR(191) NULL,
ADD COLUMN `query_count` INTEGER NULL,
ADD COLUMN `sku` VARCHAR(191) NULL;
-- CreateIndex
CREATE INDEX `artwork_audit_status_idx` ON `artwork`(`audit_status`);
-- CreateIndex
CREATE INDEX `query_log_sku_idx` ON `query_log`(`sku`);
-- CreateIndex
CREATE INDEX `query_log_batch_no_idx` ON `query_log`(`batch_no`);
@@ -47,16 +47,23 @@ CREATE TABLE `artwork` (
`template_id` INTEGER NOT NULL,
`title` VARCHAR(191) NOT NULL,
`artist` VARCHAR(191) NULL,
`archive_no` VARCHAR(191) NULL,
`dynamic_fields` JSON NULL,
`images` JSON NULL,
`status` ENUM('DRAFT', 'ACTIVE', 'DISABLED') NOT NULL DEFAULT 'DRAFT',
`audit_status` ENUM('PENDING', 'APPROVED', 'REJECTED') NOT NULL DEFAULT 'PENDING',
`audit_remark` VARCHAR(191) NULL,
`audited_by` INTEGER NULL,
`audited_at` DATETIME(3) NULL,
`created_by` INTEGER NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL,
`deleted_at` DATETIME(3) NULL,
UNIQUE INDEX `artwork_archive_no_key`(`archive_no`),
INDEX `artwork_template_id_idx`(`template_id`),
INDEX `artwork_status_idx`(`status`),
INDEX `artwork_audit_status_idx`(`audit_status`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
@@ -92,10 +99,21 @@ CREATE TABLE `certificate` (
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `trace_code_group` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`name` VARCHAR(191) NOT NULL,
`remark` VARCHAR(191) NULL,
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
-- CreateTable
CREATE TABLE `batch` (
`id` INTEGER NOT NULL AUTO_INCREMENT,
`batch_no` VARCHAR(191) NOT NULL,
`artwork_id` INTEGER NOT NULL,
`quantity` INTEGER NOT NULL,
`generated_count` INTEGER NOT NULL DEFAULT 0,
`status` ENUM('PENDING', 'GENERATING', 'DONE', 'FAILED') NOT NULL DEFAULT 'PENDING',
@@ -103,6 +121,7 @@ CREATE TABLE `batch` (
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
UNIQUE INDEX `batch_batch_no_key`(`batch_no`),
INDEX `batch_artwork_id_idx`(`artwork_id`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
@@ -111,14 +130,13 @@ CREATE TABLE `trace_code` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`code` VARCHAR(191) NOT NULL,
`short_code` VARCHAR(191) NOT NULL,
`artwork_id` INTEGER NULL,
`batch_id` INTEGER NULL,
`sku` VARCHAR(191) NULL,
`archive_no` VARCHAR(191) NULL,
`artwork_id` INTEGER NOT NULL,
`batch_id` INTEGER NOT NULL,
`group_id` INTEGER NULL,
`out_time` DATETIME(3) NULL,
`out_image` VARCHAR(191) NULL,
`remark` VARCHAR(191) NULL,
`status` ENUM('UNBOUND', 'INACTIVE', 'ACTIVE', 'DISABLED', 'ABNORMAL') NOT NULL DEFAULT 'UNBOUND',
`status` ENUM('INACTIVE', 'ACTIVE', 'DISABLED', 'ABNORMAL') NOT NULL DEFAULT 'INACTIVE',
`query_count` INTEGER NOT NULL DEFAULT 0,
`first_activated_at` DATETIME(3) NULL,
`last_queried_at` DATETIME(3) NULL,
@@ -127,8 +145,9 @@ CREATE TABLE `trace_code` (
UNIQUE INDEX `trace_code_code_key`(`code`),
UNIQUE INDEX `trace_code_short_code_key`(`short_code`),
UNIQUE INDEX `trace_code_artwork_id_key`(`artwork_id`),
INDEX `trace_code_artwork_id_idx`(`artwork_id`),
INDEX `trace_code_batch_id_idx`(`batch_id`),
INDEX `trace_code_group_id_idx`(`group_id`),
INDEX `trace_code_status_idx`(`status`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
@@ -158,15 +177,24 @@ CREATE TABLE `query_log` (
`trace_code_id` BIGINT NULL,
`artwork_id` INTEGER NULL,
`short_code` VARCHAR(191) NULL,
`code` VARCHAR(191) NULL,
`archive_no` VARCHAR(191) NULL,
`batch_no` VARCHAR(191) NULL,
`query_count` INTEGER NULL,
`first_activated_at` DATETIME(3) NULL,
`queried_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`query_result` ENUM('FIRST_ACTIVATE', 'REPEAT', 'INVALID', 'DISABLED', 'ABNORMAL') NOT NULL,
`ip` VARCHAR(191) NULL,
`region` VARCHAR(191) NULL,
`user_agent` TEXT NULL,
`device_type` VARCHAR(191) NULL,
`browser` VARCHAR(191) NULL,
`os` VARCHAR(191) NULL,
INDEX `query_log_trace_code_id_idx`(`trace_code_id`),
INDEX `query_log_queried_at_idx`(`queried_at`),
INDEX `query_log_archive_no_idx`(`archive_no`),
INDEX `query_log_batch_no_idx`(`batch_no`),
PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
@@ -215,10 +243,16 @@ ALTER TABLE `trace_node` ADD CONSTRAINT `trace_node_artwork_id_fkey` FOREIGN KEY
ALTER TABLE `certificate` ADD CONSTRAINT `certificate_artwork_id_fkey` FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_artwork_id_fkey` FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE `batch` ADD CONSTRAINT `batch_artwork_id_fkey` FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_batch_id_fkey` FOREIGN KEY (`batch_id`) REFERENCES `batch`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_artwork_id_fkey` FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_batch_id_fkey` FOREIGN KEY (`batch_id`) REFERENCES `batch`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `trace_code` ADD CONSTRAINT `trace_code_group_id_fkey` FOREIGN KEY (`group_id`) REFERENCES `trace_code_group`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE `blockchain_proof` ADD CONSTRAINT `blockchain_proof_trace_code_id_fkey` FOREIGN KEY (`trace_code_id`) REFERENCES `trace_code`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
+13 -11
View File
@@ -68,7 +68,6 @@ enum BatchStatus {
}
enum TraceCodeStatus {
UNBOUND
INACTIVE
ACTIVE
DISABLED
@@ -155,6 +154,7 @@ model Artwork {
templateId Int @map("template_id")
title String
artist String?
archiveNo String? @unique @map("archive_no")
dynamicFields Json? @map("dynamic_fields")
images Json?
status ArtworkStatus @default(DRAFT)
@@ -171,7 +171,8 @@ model Artwork {
creator SysUser? @relation(fields: [createdBy], references: [id])
traceNodes TraceNode[]
certificates Certificate[]
traceCode TraceCode?
batches Batch[]
traceCodes TraceCode[]
@@index([templateId])
@@index([status])
@@ -227,14 +228,17 @@ model TraceCodeGroup {
model Batch {
id Int @id @default(autoincrement())
batchNo String @unique @map("batch_no")
artworkId Int @map("artwork_id")
quantity Int
generatedCount Int @default(0) @map("generated_count")
status BatchStatus @default(PENDING)
createdBy Int? @map("created_by")
createdAt DateTime @default(now()) @map("created_at")
artwork Artwork @relation(fields: [artworkId], references: [id])
traceCodes TraceCode[]
@@index([artworkId])
@@map("batch")
}
@@ -242,27 +246,26 @@ model TraceCode {
id BigInt @id @default(autoincrement())
code String @unique
shortCode String @unique @map("short_code")
artworkId Int? @unique @map("artwork_id")
batchId Int? @map("batch_id")
artworkId Int @map("artwork_id")
batchId Int @map("batch_id")
groupId Int? @map("group_id")
sku String?
archiveNo String? @map("archive_no")
outTime DateTime? @map("out_time")
outImage String? @map("out_image")
remark String?
status TraceCodeStatus @default(UNBOUND)
status TraceCodeStatus @default(INACTIVE)
queryCount Int @default(0) @map("query_count")
firstActivatedAt DateTime? @map("first_activated_at")
lastQueriedAt DateTime? @map("last_queried_at")
url String?
createdAt DateTime @default(now()) @map("created_at")
artwork Artwork? @relation(fields: [artworkId], references: [id])
batch Batch? @relation(fields: [batchId], references: [id])
artwork Artwork @relation(fields: [artworkId], references: [id])
batch Batch @relation(fields: [batchId], references: [id])
group TraceCodeGroup? @relation(fields: [groupId], references: [id])
proofs BlockchainProof[]
queryLogs QueryLog[]
@@index([artworkId])
@@index([batchId])
@@index([groupId])
@@index([status])
@@ -295,7 +298,6 @@ model QueryLog {
artworkId Int? @map("artwork_id")
shortCode String? @map("short_code")
code String?
sku String?
archiveNo String? @map("archive_no")
batchNo String? @map("batch_no")
queryCount Int? @map("query_count")
@@ -313,7 +315,7 @@ model QueryLog {
@@index([traceCodeId])
@@index([queriedAt])
@@index([sku])
@@index([archiveNo])
@@index([batchNo])
@@map("query_log")
}
+72 -45
View File
@@ -98,7 +98,10 @@ async function ensureSampleData(): Promise<void> {
{ title: '影青刻花碗', artist: '陈一川', bg: '#2f6b5e', craft: '刻花 / 影青釉', material: '瓷石', size: '口径 18cm', year: '2024' },
];
let codeSeq = 0;
const base = (process.env.BASE_URL || 'http://localhost:3000').replace(/\/$/, '');
const CODES_PER_ARTWORK = 3; // 每款示例生码数(演示一款多码)
let artworkSeq = 0;
let totalCodes = 0;
for (const s of samples) {
const imgKey = writeStorage(`seed/${shortId()}.jpg`, await placeholder(s.title, s.bg));
const img2 = writeStorage(`seed/${shortId()}.jpg`, await placeholder('细节图', s.bg));
@@ -127,6 +130,11 @@ async function ensureSampleData(): Promise<void> {
},
},
});
// 档案编号(款级,按 id 生成)
await prisma.artwork.update({
where: { id: artwork.id },
data: { archiveNo: `ARTVERIS-${String(artwork.id).padStart(6, '0')}` },
});
// 证书 + 水印
const certOriginKey = writeStorage(`seed/${shortId()}.jpg`, await placeholder(`${s.title} 鉴定证书`, '#444c5a'));
@@ -143,62 +151,81 @@ async function ensureSampleData(): Promise<void> {
},
});
// 追溯码(一物一码)
const shortCode = shortId();
const isActive = codeSeq < 2; // 前两件设为已激活并带查询记录
const code = await prisma.traceCode.create({
// 一款多码:建一个批次 + 多套独立编码
const batch = await prisma.batch.create({
data: {
code: codeId(),
shortCode,
batchNo: `B-SEED-${String(artwork.id).padStart(4, '0')}`,
artworkId: artwork.id,
url: `${(process.env.BASE_URL || 'http://localhost:3000').replace(/\/$/, '')}/t/${shortCode}`,
status: isActive ? 'ACTIVE' : 'INACTIVE',
queryCount: isActive ? 3 + codeSeq * 2 : 0,
firstActivatedAt: isActive ? new Date(Date.now() - 86400000) : null,
lastQueriedAt: isActive ? new Date() : null,
sku: `SKU-${1000 + codeSeq}`,
archiveNo: `AW-${1000 + codeSeq}`,
quantity: CODES_PER_ARTWORK,
generatedCount: CODES_PER_ARTWORK,
status: 'DONE',
createdBy: admin?.id,
},
});
if (isActive) {
// 查询日志
for (let i = 0; i < 3; i++) {
await prisma.queryLog.create({
const artworkActive = artworkSeq < 2; // 前两款带激活码与查询记录
for (let k = 0; k < CODES_PER_ARTWORK; k++) {
const shortCode = shortId();
const isActive = artworkActive && k < 2; // 该款前两套已激活
const code = await prisma.traceCode.create({
data: {
code: codeId(),
shortCode,
artworkId: artwork.id,
batchId: batch.id,
url: `${base}/t/${shortCode}`,
status: isActive ? 'ACTIVE' : 'INACTIVE',
queryCount: isActive ? 3 + k : 0,
firstActivatedAt: isActive ? new Date(Date.now() - 86400000) : null,
lastQueriedAt: isActive ? new Date() : null,
},
});
totalCodes++;
if (isActive) {
for (let i = 0; i < 3; i++) {
await prisma.queryLog.create({
data: {
traceCodeId: code.id,
artworkId: artwork.id,
shortCode,
code: code.code,
archiveNo: `ARTVERIS-${String(artwork.id).padStart(6, '0')}`,
batchNo: batch.batchNo,
queryCount: 3 + k,
firstActivatedAt: new Date(Date.now() - 86400000),
queryResult: i === 0 ? 'FIRST_ACTIVATE' : 'REPEAT',
ip: `120.0.0.${10 + i}`,
region: '未知地区',
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X)',
deviceType: 'Mobile',
browser: 'Safari',
os: 'iOS',
queriedAt: new Date(Date.now() - (3 - i) * 3600000),
},
});
}
const dataHash = '0x' + createHash('sha256').update(JSON.stringify({ c: code.code })).digest('hex');
const txHash = '0x' + randomBytes(32).toString('hex');
await prisma.blockchainProof.create({
data: {
traceCodeId: code.id,
artworkId: artwork.id,
shortCode,
queryResult: i === 0 ? 'FIRST_ACTIVATE' : 'REPEAT',
ip: `120.0.0.${10 + i}`,
region: '未知地区',
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X)',
deviceType: 'Mobile',
queriedAt: new Date(Date.now() - (3 - i) * 3600000),
dataHash,
txHash,
blockHash: '0x' + createHash('sha256').update(txHash).digest('hex'),
blockHeight: BigInt(8_500_000 + totalCodes),
chainName: 'MockChain',
explorerUrl: `https://mock-explorer.local/tx/${txHash}`,
onchainAt: new Date(Date.now() - 86400000),
status: 'ONCHAIN',
rawResponse: { provider: 'mock-chain', code: 0, message: 'success' },
},
});
}
// 区块链存证
const dataHash = '0x' + createHash('sha256').update(JSON.stringify({ t: s.title })).digest('hex');
const txHash = '0x' + randomBytes(32).toString('hex');
await prisma.blockchainProof.create({
data: {
traceCodeId: code.id,
dataHash,
txHash,
blockHash: '0x' + createHash('sha256').update(txHash).digest('hex'),
blockHeight: BigInt(8_500_000 + codeSeq),
chainName: 'MockChain',
explorerUrl: `https://mock-explorer.local/tx/${txHash}`,
onchainAt: new Date(Date.now() - 86400000),
status: 'ONCHAIN',
rawResponse: { provider: 'mock-chain', code: 0, message: 'success' },
},
});
}
codeSeq++;
artworkSeq++;
}
console.log(`已创建示例:模板 1、作品 ${samples.length}、证书与追溯码、查询日志与存证。`);
console.log(`已创建示例:模板 1、作品 ${samples.length}(每款 ${CODES_PER_ARTWORK} 码,共 ${totalCodes} 码)、证书、查询日志与存证。`);
}
async function main(): Promise<void> {
+32 -2
View File
@@ -27,6 +27,11 @@ export class ArtworkService {
.map((i) => ({ ...i, url: this.storage.getUrl(i.key) }));
}
// 档案编号:款级唯一标识,按作品 id 生成,如 ARTVERIS-000001
private buildArchiveNo(id: number): string {
return `ARTVERIS-${String(id).padStart(6, '0')}`;
}
async create(dto: CreateArtworkDto, userId: number) {
const tpl = await this.prisma.template.findFirst({
where: { id: dto.templateId, deletedAt: null },
@@ -42,6 +47,11 @@ export class ArtworkService {
createdBy: userId,
},
});
// 创建后回填档案编号(需要自增 id)
await this.prisma.artwork.update({
where: { id: artwork.id },
data: { archiveNo: this.buildArchiveNo(artwork.id) },
});
return this.get(artwork.id);
}
@@ -51,6 +61,7 @@ export class ArtworkService {
where.OR = [
{ title: { contains: query.keyword } },
{ artist: { contains: query.keyword } },
{ archiveNo: { contains: query.keyword } },
];
}
if (query.status) where.status = query.status;
@@ -62,7 +73,7 @@ export class ArtworkService {
where,
include: {
template: { select: { id: true, name: true } },
traceCode: { select: { id: true, code: true, shortCode: true, status: true } },
_count: { select: { traceCodes: true } },
},
orderBy: { id: 'desc' },
skip: query.skip,
@@ -70,9 +81,21 @@ export class ArtworkService {
}),
this.prisma.artwork.count({ where }),
]);
// 每款查询总次数 = 该款所有码 queryCount 之和(PRD 6.5:按款统计)
const ids = rows.map((r) => r.id);
const sums = ids.length
? await this.prisma.traceCode.groupBy({
by: ['artworkId'],
where: { artworkId: { in: ids } },
_sum: { queryCount: true },
})
: [];
const sumMap = new Map(sums.map((s) => [s.artworkId, s._sum.queryCount ?? 0]));
const list = rows.map((a) => ({
...a,
images: this.mapMedia(a.images),
codeCount: a._count.traceCodes,
queryTotal: sumMap.get(a.id) ?? 0,
}));
return buildPage(list, total, query.page, query.pageSize);
}
@@ -84,10 +107,16 @@ export class ArtworkService {
template: { include: { fields: { orderBy: { sortOrder: 'asc' } } } },
traceNodes: { orderBy: { sortOrder: 'asc' } },
certificates: { orderBy: { id: 'asc' } },
traceCode: { include: { proofs: { orderBy: { id: 'desc' } } } },
batches: { orderBy: { id: 'desc' } },
},
});
if (!a) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
// 码统计:总数、已激活数、查询总次数(按款聚合)
const [total, active, agg] = await this.prisma.$transaction([
this.prisma.traceCode.count({ where: { artworkId: id } }),
this.prisma.traceCode.count({ where: { artworkId: id, status: 'ACTIVE' } }),
this.prisma.traceCode.aggregate({ where: { artworkId: id }, _sum: { queryCount: true } }),
]);
return {
...a,
images: this.mapMedia(a.images),
@@ -97,6 +126,7 @@ export class ArtworkService {
originUrl: c.originFileUrl ? this.storage.getUrl(c.originFileUrl) : null,
watermarkUrl: c.watermarkFileUrl ? this.storage.getUrl(c.watermarkFileUrl) : null,
})),
codeStats: { total, active, queryTotal: agg._sum.queryCount ?? 0 },
};
}
@@ -31,9 +31,8 @@ export class AttestationService {
code: code.code,
title: code.artwork.title,
artist: code.artwork.artist,
archiveNo: code.artwork.archiveNo,
dynamicFields: code.artwork.dynamicFields,
sku: code.sku,
archiveNo: code.archiveNo,
nodes: code.artwork.traceNodes.map((n) => ({ type: n.nodeType, title: n.title })),
certificates: code.artwork.certificates.map((c) => c.name),
};
+20 -13
View File
@@ -12,14 +12,14 @@ export class DashboardService {
const [
totalArtworks,
boundCodes,
totalCodes,
activatedCodes,
totalQueries,
todayQueries,
abnormalQueries,
] = await this.prisma.$transaction([
this.prisma.artwork.count({ where: { deletedAt: null } }),
this.prisma.traceCode.count({ where: { artworkId: { not: null } } }),
this.prisma.traceCode.count(),
this.prisma.traceCode.count({ where: { status: TraceCodeStatus.ACTIVE } }),
this.prisma.queryLog.count(),
this.prisma.queryLog.count({ where: { queriedAt: { gte: todayStart } } }),
@@ -30,7 +30,7 @@ export class DashboardService {
return {
totalArtworks,
boundCodes,
totalCodes,
activatedCodes,
totalQueries,
todayQueries,
@@ -58,19 +58,26 @@ export class DashboardService {
return Object.entries(buckets).map(([date, count]) => ({ date, count }));
}
// 高频查询作品榜
// 高频查询作品榜:按款聚合(该款所有码查询次数之和)
async topArtworks(limit: number) {
const codes = await this.prisma.traceCode.findMany({
where: { artworkId: { not: null }, queryCount: { gt: 0 } },
orderBy: { queryCount: 'desc' },
const grouped = await this.prisma.traceCode.groupBy({
by: ['artworkId'],
_sum: { queryCount: true },
orderBy: { _sum: { queryCount: 'desc' } },
take: limit,
include: { artwork: { select: { id: true, title: true } } },
});
return codes.map((c) => ({
artworkId: c.artworkId,
title: c.artwork?.title ?? '-',
shortCode: c.shortCode,
queryCount: c.queryCount,
const ids = grouped.map((g) => g.artworkId);
if (!ids.length) return [];
const artworks = await this.prisma.artwork.findMany({
where: { id: { in: ids } },
select: { id: true, title: true, archiveNo: true },
});
const map = new Map(artworks.map((a) => [a.id, a]));
return grouped.map((g) => ({
artworkId: g.artworkId,
title: map.get(g.artworkId)?.title ?? '-',
archiveNo: map.get(g.artworkId)?.archiveNo ?? '',
queryCount: g._sum.queryCount ?? 0,
}));
}
}
-12
View File
@@ -3,18 +3,6 @@ import { Type } from 'class-transformer';
import { IsDateString, IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
export class OutboundDto {
@ApiPropertyOptional({ description: 'SKU' })
@IsOptional()
@IsString()
@MaxLength(80)
sku?: string;
@ApiPropertyOptional({ description: '档案编号' })
@IsOptional()
@IsString()
@MaxLength(80)
archiveNo?: string;
@ApiPropertyOptional({ description: '出库时间' })
@IsOptional()
@IsDateString()
@@ -136,8 +136,6 @@ export class ImportProcessor extends WorkerHost {
await this.prisma.traceCode.update({
where: { id: code.id },
data: {
sku: row.values.sku || undefined,
archiveNo: row.values.archiveNo || undefined,
outTime: outTime ?? undefined,
outImage: row.values.outImage || undefined,
remark: row.values.remark || undefined,
@@ -38,8 +38,6 @@ export class OutboundService {
const updated = await this.prisma.traceCode.update({
where: { id: traceCodeId },
data: {
sku: dto.sku,
archiveNo: dto.archiveNo,
outTime: dto.outTime ? new Date(dto.outTime) : undefined,
outImage: dto.outImageKey,
remark: dto.remark,
@@ -8,7 +8,7 @@ import { GeoService } from '../geo/geo.service';
import { REDIS_CLIENT } from '../redis/redis.module';
import { parseUserAgent } from '../common/utils/ua.util';
type TraceCodeWithBatch = Prisma.TraceCodeGetPayload<{ include: { batch: true } }>;
type TraceCodeWithRel = Prisma.TraceCodeGetPayload<{ include: { batch: true; artwork: true } }>;
export interface TraceContext {
ip: string;
@@ -55,9 +55,12 @@ export class PublicTraceService {
return { status: 'INVALID' as const };
}
const code = await this.prisma.traceCode.findUnique({ where: { id }, include: { batch: true } });
if (!code || !code.artworkId || code.status === TraceCodeStatus.UNBOUND) {
await this.writeLog(id, null, shortCode, QueryResult.INVALID, ctx, code ?? undefined);
const code = await this.prisma.traceCode.findUnique({
where: { id },
include: { batch: true, artwork: true },
});
if (!code) {
await this.writeLog(id, null, shortCode, QueryResult.INVALID, ctx);
return { status: 'INVALID' as const };
}
if (code.status === TraceCodeStatus.DISABLED) {
@@ -129,6 +132,7 @@ export class PublicTraceService {
artwork: {
title: artwork.title,
artist: artwork.artist,
archiveNo: artwork.archiveNo,
images: this.mapMedia(artwork.images),
fields: this.buildFields(artwork.template.fields, artwork.dynamicFields),
},
@@ -189,7 +193,7 @@ export class PublicTraceService {
shortCode: string,
result: QueryResult,
ctx: TraceContext,
code?: Partial<TraceCodeWithBatch>,
code?: Partial<TraceCodeWithRel>,
): Promise<void> {
try {
const device = parseUserAgent(ctx.userAgent);
@@ -199,8 +203,7 @@ export class PublicTraceService {
artworkId: artworkId ?? undefined,
shortCode,
code: code?.code ?? undefined,
sku: code?.sku ?? undefined,
archiveNo: code?.archiveNo ?? undefined,
archiveNo: code?.artwork?.archiveNo ?? undefined,
batchNo: code?.batch?.batchNo ?? undefined,
queryCount: code?.queryCount ?? undefined,
firstActivatedAt: code?.firstActivatedAt ?? undefined,
@@ -13,10 +13,10 @@ class QueryLogQueryDto extends PaginationDto {
@IsString()
keyword?: string;
@ApiPropertyOptional({ description: 'SKU' })
@ApiPropertyOptional({ description: '档案编号' })
@IsOptional()
@IsString()
sku?: string;
archiveNo?: string;
@ApiPropertyOptional({ description: '批次编号' })
@IsOptional()
@@ -53,11 +53,10 @@ export class QueryLogController {
where.OR = [
{ shortCode: { contains: query.keyword } },
{ code: { contains: query.keyword } },
{ sku: { contains: query.keyword } },
{ archiveNo: { contains: query.keyword } },
];
}
if (query.sku) where.sku = { contains: query.sku };
if (query.archiveNo) where.archiveNo = { contains: query.archiveNo };
if (query.batchNo) where.batchNo = { contains: query.batchNo };
if (query.result) where.queryResult = query.result;
if (query.startTime || query.endTime) {
+17 -7
View File
@@ -17,6 +17,11 @@ import { TraceCodeStatus } from '@artveris/shared';
import { PaginationDto } from '../../common/dto/pagination.dto';
export class GenerateBatchDto {
@ApiProperty({ description: '所属作品(款)ID' })
@Type(() => Number)
@IsInt()
artworkId!: number;
@ApiProperty({ description: '生成数量', minimum: 1, maximum: 10000 })
@Type(() => Number)
@IsInt()
@@ -38,6 +43,12 @@ export class GenerateBatchDto {
}
export class QueryTraceCodeDto extends PaginationDto {
@ApiPropertyOptional({ description: '作品(款)ID' })
@IsOptional()
@Type(() => Number)
@IsInt()
artworkId?: number;
@ApiPropertyOptional({ description: '批次 ID' })
@IsOptional()
@Type(() => Number)
@@ -105,13 +116,6 @@ export class BatchStatusDto {
abnormal?: boolean;
}
export class BindArtworkDto {
@ApiProperty({ description: '艺术品 ID' })
@Type(() => Number)
@IsInt()
artworkId!: number;
}
export class QueryBatchDto extends PaginationDto {
@ApiPropertyOptional({ description: '关键词(批次编号)' })
@IsOptional()
@@ -125,6 +129,12 @@ export class ExportTraceCodeDto {
@IsIn(['xlsx', 'csv'])
format?: 'xlsx' | 'csv';
@ApiPropertyOptional({ description: '作品(款)ID' })
@IsOptional()
@Type(() => Number)
@IsInt()
artworkId?: number;
@ApiPropertyOptional({ description: '分组 ID' })
@IsOptional()
@Type(() => Number)
@@ -13,6 +13,7 @@ const codeId = customAlphabet(ALPHABET, 18);
interface GenJobData {
batchId: number;
artworkId: number;
jobId: string;
quantity: number;
groupId?: number | null;
@@ -31,7 +32,7 @@ export class GenCodeProcessor extends WorkerHost {
}
async process(job: Job<GenJobData>): Promise<void> {
const { batchId, jobId, quantity, groupId } = job.data;
const { batchId, artworkId, jobId, quantity, groupId } = job.data;
await this.jobs.start(jobId);
await this.prisma.batch.update({ where: { id: batchId }, data: { status: BatchStatus.GENERATING } });
@@ -45,6 +46,7 @@ export class GenCodeProcessor extends WorkerHost {
return {
code: codeId(),
shortCode,
artworkId,
batchId,
groupId: groupId ?? null,
url: this.traceCode.buildTraceUrl(shortCode),
@@ -17,7 +17,6 @@ import { TraceCodeService } from './trace-code.service';
import {
BatchGroupDto,
BatchStatusDto,
BindArtworkDto,
ExportTraceCodeDto,
GenerateBatchDto,
GroupDto,
@@ -110,17 +109,4 @@ export class TraceCodeController {
res.end(buf);
}
@Put('trace-codes/:id/bind')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '绑定艺术品' })
bind(@Param('id') id: string, @Body() dto: BindArtworkDto) {
return this.service.bind(BigInt(id), dto.artworkId);
}
@Put('trace-codes/:id/unbind')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '解绑艺术品' })
unbind(@Param('id') id: string) {
return this.service.unbind(BigInt(id));
}
}
+29 -42
View File
@@ -7,7 +7,7 @@ import { Response } from 'express';
import * as ExcelJS from 'exceljs';
import * as QRCode from 'qrcode';
import dayjs from 'dayjs';
import { ErrorCode, JobType, QUEUE_NAMES, TraceCodeStatus } from '@artveris/shared';
import { ArtworkStatus, ErrorCode, JobType, QUEUE_NAMES, TraceCodeStatus } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { buildPage } from '../common/utils/pagination.util';
@@ -38,20 +38,28 @@ export class TraceCodeService {
}
async generateBatch(dto: GenerateBatchDto, userId: number) {
// 必须指定作品(款):生码即归属该款(一款多码)
const artwork = await this.prisma.artwork.findFirst({
where: { id: dto.artworkId, deletedAt: null },
});
if (!artwork) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
const batchNo = dto.batchNo || `B${dayjs().format('YYYYMMDDHHmmss')}`;
const exists = await this.prisma.batch.findUnique({ where: { batchNo } });
if (exists) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '批次编号已存在');
}
const batch = await this.prisma.batch.create({
data: { batchNo, quantity: dto.quantity, createdBy: userId },
data: { batchNo, artworkId: dto.artworkId, quantity: dto.quantity, createdBy: userId },
});
const job = await this.jobs.create(JobType.GEN_CODE, dto.quantity, userId, {
batchId: batch.id,
artworkId: dto.artworkId,
groupId: dto.groupId ?? null,
});
await this.genQueue.add('generate', {
batchId: batch.id,
artworkId: dto.artworkId,
jobId: job.id,
quantity: dto.quantity,
groupId: dto.groupId ?? null,
@@ -113,20 +121,16 @@ export class TraceCodeService {
data: { status: TraceCodeStatus.DISABLED },
});
} else {
// 启用:按是否已激活/已绑定恢复对应状态
// 启用:已激活过的恢复为 ACTIVE,否则恢复为 INACTIVE
await this.prisma.$transaction([
this.prisma.traceCode.updateMany({
where: { id: { in: ids }, firstActivatedAt: { not: null } },
data: { status: TraceCodeStatus.ACTIVE },
}),
this.prisma.traceCode.updateMany({
where: { id: { in: ids }, firstActivatedAt: null, artworkId: { not: null } },
where: { id: { in: ids }, firstActivatedAt: null },
data: { status: TraceCodeStatus.INACTIVE },
}),
this.prisma.traceCode.updateMany({
where: { id: { in: ids }, firstActivatedAt: null, artworkId: null },
data: { status: TraceCodeStatus.UNBOUND },
}),
]);
}
return { success: true, count: ids.length };
@@ -149,6 +153,7 @@ export class TraceCodeService {
async list(query: QueryTraceCodeDto) {
const where: Prisma.TraceCodeWhereInput = {};
if (query.artworkId) where.artworkId = query.artworkId;
if (query.batchId) where.batchId = query.batchId;
if (query.groupId) where.groupId = query.groupId;
if (query.status) where.status = query.status;
@@ -156,15 +161,16 @@ export class TraceCodeService {
where.OR = [
{ shortCode: { contains: query.keyword } },
{ code: { contains: query.keyword } },
{ sku: { contains: query.keyword } },
{ archiveNo: { contains: query.keyword } },
{ artwork: { archiveNo: { contains: query.keyword } } },
{ artwork: { title: { contains: query.keyword } } },
];
}
const [list, total] = await this.prisma.$transaction([
this.prisma.traceCode.findMany({
where,
include: {
artwork: { select: { id: true, title: true } },
artwork: { select: { id: true, title: true, archiveNo: true } },
batch: { select: { id: true, batchNo: true } },
group: { select: { id: true, name: true } },
},
orderBy: { id: 'desc' },
@@ -176,34 +182,6 @@ export class TraceCodeService {
return buildPage(list, total, query.page, query.pageSize);
}
async bind(id: bigint, artworkId: number) {
const code = await this.prisma.traceCode.findUnique({ where: { id } });
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
const artwork = await this.prisma.artwork.findFirst({ where: { id: artworkId, deletedAt: null } });
if (!artwork) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
const bound = await this.prisma.traceCode.findUnique({ where: { artworkId } });
if (bound && bound.id !== id) {
throw new BusinessException(ErrorCode.TRACE_CODE_ALREADY_BOUND, '该艺术品已绑定其他追溯码');
}
const next =
code.status === TraceCodeStatus.UNBOUND ? TraceCodeStatus.INACTIVE : code.status;
return this.prisma.traceCode.update({
where: { id },
data: { artworkId, status: next },
});
}
async unbind(id: bigint) {
const code = await this.prisma.traceCode.findUnique({ where: { id } });
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
return this.prisma.traceCode.update({
where: { id },
data: { artworkId: null, status: TraceCodeStatus.UNBOUND },
});
}
async getQrPng(id: bigint): Promise<Buffer> {
const code = await this.prisma.traceCode.findUnique({ where: { id } });
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
@@ -224,6 +202,7 @@ export class TraceCodeService {
.map((s) => BigInt(s));
where.id = { in: idList };
} else {
if (dto.artworkId) where.artworkId = dto.artworkId;
if (dto.batchId) where.batchId = dto.batchId;
if (dto.groupId) where.groupId = dto.groupId;
if (dto.status) where.status = dto.status;
@@ -231,21 +210,27 @@ export class TraceCodeService {
where.OR = [
{ shortCode: { contains: dto.keyword } },
{ code: { contains: dto.keyword } },
{ sku: { contains: dto.keyword } },
{ archiveNo: { contains: dto.keyword } },
{ artwork: { archiveNo: { contains: dto.keyword } } },
{ artwork: { title: { contains: dto.keyword } } },
];
}
}
const codes = await this.prisma.traceCode.findMany({
where,
include: { batch: { select: { batchNo: true } }, group: { select: { name: true } } },
include: {
batch: { select: { batchNo: true } },
group: { select: { name: true } },
artwork: { select: { title: true, archiveNo: true } },
},
orderBy: { id: 'asc' },
});
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet('追溯码');
ws.columns = [
{ header: '档案编号', key: 'archiveNo', width: 18 },
{ header: '作品名称', key: 'title', width: 20 },
{ header: '批次编号', key: 'batchNo', width: 22 },
{ header: '分组', key: 'group', width: 14 },
{ header: '追溯码', key: 'code', width: 24 },
@@ -260,6 +245,8 @@ export class TraceCodeService {
const url = c.url || this.buildTraceUrl(c.shortCode);
const qr = await QRCode.toDataURL(url, { margin: 1, width: 200 });
ws.addRow({
archiveNo: c.artwork?.archiveNo ?? '',
title: c.artwork?.title ?? '',
batchNo: c.batch?.batchNo ?? '',
group: c.group?.name ?? '',
code: c.code,
+1
View File
@@ -18,6 +18,7 @@
"chain": "Digital Identity & Blockchain"
},
"chain": {
"archiveNo": "Archive No.",
"code": "Trace Code",
"hash": "Tx Hash",
"dataHash": "Data Hash",
+1
View File
@@ -18,6 +18,7 @@
"chain": "数字身份与区块链存证"
},
"chain": {
"archiveNo": "档案编号",
"code": "唯一追溯码",
"hash": "交易哈希",
"dataHash": "数据哈希",
+4
View File
@@ -135,6 +135,10 @@
<!-- 数字身份与区块链存证 -->
<section class="card">
<h2 class="section-title">{{ t('section.chain') }}</h2>
<div v-if="data.artwork.archiveNo" class="chain-row">
<span class="chain-k">{{ t('chain.archiveNo') }}</span>
<span class="chain-v mono">{{ data.artwork.archiveNo }}</span>
</div>
<div class="chain-row">
<span class="chain-k">{{ t('chain.code') }}</span>
<span class="chain-v mono">{{ data.code || '-' }}</span>