feat(admin): country drag-sort + always-available member detail sync

- Country 加 sort_order(默认 0 保持 id 序);PATCH /countries/sort 批量保存
  顺序(对齐 /tags/sort 模式);findAll 与公开 /public/countries 均按
  sortOrder 排序
- CountriesView 表格改为可拖拽行列表:拖动松开即全量保存新顺序,失败回滚
- 商品编辑弹窗成员展开面板:同步详情按钮常驻(已同步显示 重新同步详情),
  不再只在未同步态出现
- goods.service.spec 的 FamilyRecomputeService mock 补齐 syncFamilyTags 等
  方法(全量并行时其他套件的扫名归族会把本套件夹具收进族,create/update
  会调用到,mock 缺方法导致偶发 TypeError)
- api 164/164、admin typecheck+22/22+构建全绿
This commit is contained in:
yeuimu
2026-08-28 20:00:56 +08:00
parent 77f9c05346
commit 1e07c62fc8
12 changed files with 261 additions and 60 deletions
+5
View File
@@ -32,4 +32,9 @@ export const countriesApi = {
deleteCountry: (id: string) => {
return request.delete(`/countries/${id}`)
},
// Batch save drag-reorder (items = full list in the new order)
sortCountries: (items: Array<{ id: string; sortOrder: number }>) => {
return request.patch<any, Country[]>('/countries/sort', { items })
},
}
+146 -52
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Refresh, Search } from '@element-plus/icons-vue'
import { Plus, Edit, Delete, Refresh, Search, Rank } from '@element-plus/icons-vue'
import type {
Country,
CreateCountryRequest,
@@ -44,6 +44,38 @@ function handleReset() {
fetchList()
}
// ─── 拖拽排序:松开即按新顺序全量保存(sortOrder = 下标) ───
const dragIndex = ref<number | null>(null)
const sorting = ref(false)
function onRowDragStart(index: number) {
dragIndex.value = index
}
async function onRowDrop(index: number) {
const from = dragIndex.value
dragIndex.value = null
if (from === null || from === index || sorting.value) return
const next = [...list.value]
const [moved] = next.splice(from, 1)
next.splice(index, 0, moved)
list.value = next
sorting.value = true
try {
const updated = await countriesApi.sortCountries(
next.map((c, i) => ({ id: String(c.id), sortOrder: i })),
)
const arr = Array.isArray(updated) ? updated : []
if (arr.length) list.value = arr
ElMessage.success('排序已保存')
} catch {
ElMessage.error('排序保存失败')
await fetchList()
} finally {
sorting.value = false
}
}
const dialogRef = ref()
const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
@@ -145,54 +177,43 @@ onMounted(fetchList)
</el-button>
</div>
<el-table v-loading="loading" :data="list" border stripe>
<el-table-column label="图标" width="80">
<template #default="{ row }: any">
<el-image
v-if="row.countryIcon"
:src="row.countryIcon"
:preview-src-list="[row.countryIcon]"
fit="cover"
style="width: 32px; height: 32px; border-radius: 4px;"
/>
<span v-else>-</span>
</template>
</el-table-column>
<el-table-column prop="countryName" label="名称" min-width="200" />
<el-table-column label="创建时间" width="180">
<template #default="{ row }: any">
{{ new Date(row.createdAt).toLocaleString() }}
</template>
</el-table-column>
<el-table-column label="操作" width="180" fixed="right">
<template #default="{ row }: any">
<div class="table-actions">
<el-button size="small" type="primary" plain @click="openEditDialog(row)">
<el-icon><Edit /></el-icon>
<span>编辑</span>
</el-button>
<el-button size="small" type="danger" plain @click="handleDelete(row)">
<el-icon><Delete /></el-icon>
<span>删除</span>
</el-button>
</div>
</template>
</el-table-column>
<template #empty>
<el-empty description="暂无国家" />
</template>
</el-table>
<el-pagination
class="pagination"
v-model:current-page="filter.page"
v-model:page-size="filter.pageSize"
:total="total"
:page-sizes="[10, 20, 50, 100]"
layout="total, sizes, prev, pager, next, jumper"
@current-change="(p: number) => { filter.page = p; fetchList() }"
@size-change="(s: number) => { filter.pageSize = s; filter.page = 1; fetchList() }"
/>
<ul v-loading="loading" class="country-list">
<li
v-for="(row, index) in list"
:key="row.id"
class="country-row"
:class="{ 'is-dragging': dragIndex === index }"
draggable="true"
title="拖拽调整顺序,松开即保存"
@dragstart="onRowDragStart(index)"
@dragover.prevent
@drop="onRowDrop(index)"
@dragend="dragIndex = null"
>
<el-icon class="drag-handle"><Rank /></el-icon>
<el-image
v-if="row.countryIcon"
:src="row.countryIcon"
:preview-src-list="[row.countryIcon]"
fit="cover"
class="row-icon"
/>
<span v-else class="row-icon row-icon-placeholder">-</span>
<span class="row-name">{{ row.countryName }}</span>
<span class="row-time">{{ new Date(row.createdAt).toLocaleString() }}</span>
<div class="table-actions">
<el-button size="small" type="primary" plain @click="openEditDialog(row)">
<el-icon><Edit /></el-icon>
<span>编辑</span>
</el-button>
<el-button size="small" type="danger" plain @click="handleDelete(row)">
<el-icon><Delete /></el-icon>
<span>删除</span>
</el-button>
</div>
</li>
<li v-if="!loading && !list.length" class="country-empty">暂无国家</li>
</ul>
</div>
<el-dialog
@@ -224,8 +245,81 @@ onMounted(fetchList)
flex: 1;
}
.pagination {
margin-top: 16px;
justify-content: flex-end;
.country-list {
list-style: none;
margin: 0;
padding: 0;
}
.country-row {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 16px;
background: var(--el-bg-color);
border: 1px solid var(--el-border-color-lighter);
border-top: none;
cursor: grab;
}
.country-row:first-child {
border-top: 1px solid var(--el-border-color-lighter);
border-radius: 4px 4px 0 0;
}
.country-row:last-child {
border-radius: 0 0 4px 4px;
}
.country-row:only-child {
border-radius: 4px;
}
.country-row.is-dragging {
opacity: 0.5;
}
.country-row:hover {
background: var(--el-fill-color-light);
}
.drag-handle {
color: var(--el-text-color-secondary);
font-size: 16px;
}
.row-icon {
width: 32px;
height: 32px;
border-radius: 4px;
flex: none;
}
.row-icon-placeholder {
display: inline-flex;
align-items: center;
justify-content: center;
color: var(--el-text-color-secondary);
border: 1px dashed var(--el-border-color);
}
.row-name {
font-weight: 500;
}
.row-time {
margin-left: auto;
color: var(--el-text-color-secondary);
font-size: 13px;
}
.table-actions {
flex: none;
}
.country-empty {
padding: 32px 0;
text-align: center;
color: var(--el-text-color-secondary);
}
</style>
@@ -647,12 +647,17 @@ async function handleDeleteGood() {
</el-table>
</div>
<div v-if="row.source === 'SDS'" class="member-extra">
<div v-if="!memberDetail(row.id) || memberDetail(row.id).loading" class="md-empty">详情加载中</div>
<div v-else-if="!memberDetail(row.id).hasDetail" class="md-empty">
尚未同步详情
<el-button size="small" :icon="Refresh" :loading="detailSyncing === row.id" @click="handleSyncMemberDetail(row)">同步详情</el-button>
<div class="member-detail-head">
<span v-if="!memberDetail(row.id) || memberDetail(row.id).loading" class="md-empty">详情加载中</span>
<span v-else-if="!memberDetail(row.id).hasDetail" class="md-empty">尚未同步详情</span>
<el-button
size="small"
:icon="Refresh"
:loading="detailSyncing === row.id"
@click="handleSyncMemberDetail(row)"
>{{ memberDetail(row.id)?.hasDetail ? '重新同步详情' : '同步详情' }}</el-button>
</div>
<el-tabs v-else class="member-detail-tabs">
<el-tabs v-if="memberDetail(row.id) && memberDetail(row.id).hasDetail" class="member-detail-tabs">
<el-tab-pane label="商品详情">
<el-descriptions :column="2" border size="small">
<el-descriptions-item label="商品编码">{{ memberDetail(row.id).detail.productCode || '-' }}</el-descriptions-item>
@@ -908,6 +913,11 @@ async function handleDeleteGood() {
display: flex; align-items: center; justify-content: space-between; gap: 8px;
font-size: 12px; color: var(--el-text-color-placeholder); padding: 4px 0;
}
.member-detail-head {
display: flex; align-items: center; justify-content: space-between; gap: 8px;
margin-bottom: 4px;
}
.member-detail-head .md-empty { padding: 0; }
.member-detail-tabs :deep(.el-tabs__header) { margin-bottom: 8px; }
.edit-family-loading { color: var(--el-text-color-placeholder); font-size: 12px; padding: 4px 0; }
.family-detail-tabs { margin-top: 10px; }
@@ -0,0 +1,2 @@
-- 国家自定义排序:默认 0 保持既有 id 序,后台可拖拽调整
ALTER TABLE "countries" ADD COLUMN "sort_order" INTEGER NOT NULL DEFAULT 0;
+1
View File
@@ -143,6 +143,7 @@ model Country {
id BigInt @id @default(autoincrement()) @map("country_id")
countryName String @unique @map("country_name")
countryIcon String? @map("country_icon")
sortOrder Int @default(0) @map("sort_order")
createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz(6)
updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz(6)
@@ -18,6 +18,7 @@ import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { CountriesService } from './countries.service';
import { CreateCountryDto } from './dto/create-country.dto';
import { UpdateCountryDto } from './dto/update-country.dto';
import { ReorderCountriesDto } from './dto/reorder-countries.dto';
@ApiTags('countries')
@ApiBearerAuth()
@@ -32,6 +33,13 @@ export class CountriesController {
return this.service.findAll();
}
// 注意:'sort' 静态路由必须声明在 ':id' 之前,否则会被参数路由吞掉
@Patch('sort')
@ApiOperation({ summary: 'Batch update country sort order (drag reorder)' })
reorder(@Body() dto: ReorderCountriesDto) {
return this.service.reorder(dto);
}
@Get(':id')
@ApiOperation({ summary: 'Get one country' })
findOne(@Param('id', ParseIntPipe) id: string) {
@@ -112,4 +112,30 @@ describe('CountriesService', () => {
const idx = created.indexOf(`${name}-v2`);
if (idx !== -1) created.splice(idx, 1);
});
it('reorder persists sortOrder and findAll honors it', async () => {
const stamp = Date.now();
const a = await service.create({ countryName: `Sort A ${stamp}` });
const b = await service.create({ countryName: `Sort B ${stamp}` });
const c = await service.create({ countryName: `Sort C ${stamp}` });
created.push(a.countryName, b.countryName, c.countryName);
// 新顺序 C, A, Bid 序与 sortOrder 无关时也能稳定验证)
const reordered = await service.reorder({
items: [
{ id: Number(c.id), sortOrder: 0 },
{ id: Number(a.id), sortOrder: 1 },
{ id: Number(b.id), sortOrder: 2 },
],
});
const ours = reordered.filter((r) =>
[a.id, b.id, c.id].some((id) => id.toString() === r.id.toString()),
);
expect(ours.map((r) => r.id.toString())).toEqual([c.id.toString(), a.id.toString(), b.id.toString()]);
const list = await service.findAll();
const pos = (id: bigint) => list.findIndex((r) => r.id.toString() === id.toString());
expect(pos(c.id)).toBeLessThan(pos(a.id));
expect(pos(a.id)).toBeLessThan(pos(b.id));
});
});
+17 -1
View File
@@ -8,13 +8,29 @@ import {
import { PrismaService } from '../prisma/prisma.service';
import { CreateCountryDto } from './dto/create-country.dto';
import { UpdateCountryDto } from './dto/update-country.dto';
import { ReorderCountriesDto } from './dto/reorder-countries.dto';
@Injectable()
export class CountriesService {
constructor(private readonly prisma: PrismaService) {}
findAll() {
return this.prisma.country.findMany({ orderBy: { id: 'asc' } });
return this.prisma.country.findMany({
orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }],
});
}
/** 批量保存拖拽后的顺序(全量提交,sortOrder = 目标下标) */
async reorder(dto: ReorderCountriesDto) {
await this.prisma.$transaction(
dto.items.map((item) =>
this.prisma.country.update({
where: { id: BigInt(item.id) },
data: { sortOrder: item.sortOrder },
}),
),
);
return this.findAll();
}
async findOne(id: bigint) {
@@ -0,0 +1,30 @@
import { ApiProperty } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import {
ArrayMinSize,
IsArray,
IsInt,
Min,
ValidateNested,
} from 'class-validator';
export class CountryOrderItem {
@ApiProperty()
@IsInt()
@Min(1)
id!: number;
@ApiProperty()
@IsInt()
@Min(0)
sortOrder!: number;
}
export class ReorderCountriesDto {
@ApiProperty({ type: [CountryOrderItem] })
@IsArray()
@ArrayMinSize(1)
@ValidateNested({ each: true })
@Type(() => CountryOrderItem)
items!: CountryOrderItem[];
}
+9 -1
View File
@@ -33,7 +33,15 @@ describe('GoodsService', () => {
},
{
provide: FamilyRecomputeService,
useValue: { enqueue: jest.fn() },
// 全量并行跑时其他套件的扫名归族可能把本套件夹具链接收进族,
// create/update 会调用 syncFamilyTags —— mock 必须覆盖全部被调方法
useValue: {
enqueue: jest.fn(),
recomputeFamily: jest.fn().mockResolvedValue(undefined),
syncFamilyTags: jest.fn().mockResolvedValue({ goodsUpdated: 0, linksUpdated: 0 }),
refreshLinkTags: jest.fn().mockResolvedValue(undefined),
mirrorLinkTagsToGoods: jest.fn().mockResolvedValue(undefined),
},
},
],
}).compile();
+1 -1
View File
@@ -111,7 +111,7 @@ export class PublicService {
async getCountries(): Promise<PublicCountryDto[]> {
const rows = await this.prisma.country.findMany({
where: { goods: { some: { familyId: { not: null }, originGood: { delisted: false } } } },
orderBy: { id: 'asc' },
orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }],
});
return rows.map(PublicCountryDto.from);
}