feat(deploy): production deployment setup and fixes

- Debian-based api image (bookworm-slim), docker/debian mirrors, prisma
  binaryTargets for openssl 3.0
- nginx: admin SPA under /admin, TLS via acme.sh (ZeroSSL) + auto-renewal
  cron, http->https redirect
- prisma: add origin_goods.delisted migration, sync missing schema
  (good_image/tag_font_color/good_tags), fix users.createdAt Timestamptz
- api: CORS wildcard reflection, helmet CORP cross-origin, price
  backfill in persistProductDetail, categoryIcon ancestor fallback,
  mediaByColor per-color gallery in public goods detail
- admin: /admin base path (vite + router)
- import-data.mjs: udt_name casting, serial sequence advance fix
This commit is contained in:
yeuimu
2026-08-26 14:23:09 +08:00
parent be0b90e68f
commit 6c61a4e871
982 changed files with 74156 additions and 179393 deletions
+24 -24
View File
@@ -1,33 +1,33 @@
import { ApiProperty } from '@nestjs/swagger';
import type { Category as PrismaCategory } from '@prisma/client';
export class PublicCategoryNodeDto {
@ApiProperty()
id!: string;
@ApiProperty()
categoryName!: string;
@ApiProperty({ nullable: true })
categoryIcon!: string | null;
@ApiProperty({ nullable: true })
parentCategoryId!: string | null;
import { ApiProperty } from '@nestjs/swagger';
import type { Category as PrismaCategory } from '@prisma/client';
export class PublicCategoryNodeDto {
@ApiProperty()
id!: string;
@ApiProperty()
categoryName!: string;
@ApiProperty({ nullable: true })
categoryIcon!: string | null;
@ApiProperty({ nullable: true })
parentCategoryId!: string | null;
@ApiProperty({ type: [PublicCategoryNodeDto] })
children!: PublicCategoryNodeDto[];
@ApiProperty({ description: '当前节点及其后代分类的商品数量' })
productCount!: number;
static from(category: PrismaCategory, children: PublicCategoryNodeDto[] = []): PublicCategoryNodeDto {
return {
id: category.id.toString(),
categoryName: category.categoryName,
categoryIcon: category.categoryIcon,
parentCategoryId: category.parentCategoryId
? category.parentCategoryId.toString()
: null,
return {
id: category.id.toString(),
categoryName: category.categoryName,
categoryIcon: category.categoryIcon,
parentCategoryId: category.parentCategoryId
? category.parentCategoryId.toString()
: null,
children,
productCount: 0,
};
+21 -21
View File
@@ -1,21 +1,21 @@
import { ApiProperty } from '@nestjs/swagger';
import type { Country as PrismaCountry } from '@prisma/client';
export class PublicCountryDto {
@ApiProperty()
id!: string;
@ApiProperty()
countryName!: string;
@ApiProperty({ nullable: true })
countryIcon!: string | null;
static from(country: PrismaCountry): PublicCountryDto {
return {
id: country.id.toString(),
countryName: country.countryName,
countryIcon: country.countryIcon,
};
}
}
import { ApiProperty } from '@nestjs/swagger';
import type { Country as PrismaCountry } from '@prisma/client';
export class PublicCountryDto {
@ApiProperty()
id!: string;
@ApiProperty()
countryName!: string;
@ApiProperty({ nullable: true })
countryIcon!: string | null;
static from(country: PrismaCountry): PublicCountryDto {
return {
id: country.id.toString(),
countryName: country.countryName,
countryIcon: country.countryIcon,
};
}
}
@@ -20,6 +20,14 @@ export class PublicGoodDetailDto extends PublicGoodDto {
@ApiProperty({ nullable: true, type: Object })
media!: Record<string, unknown> | null;
@ApiProperty({ type: Array, description: 'Variant images grouped by color' })
mediaByColor!: Array<{
colorId: string | null;
colorName: string | null;
colorHex: string | null;
images: string[];
}>;
@ApiProperty({ nullable: true, type: Object })
options!: Record<string, unknown> | null;
+32 -32
View File
@@ -1,36 +1,36 @@
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty } from '@nestjs/swagger';
export class PublicGoodDto {
@ApiProperty()
goodId!: string;
@ApiProperty()
goodName!: string;
@ApiProperty()
goodPriority!: number;
@ApiProperty()
country!: { id: string; countryName: string; countryIcon: string | null };
@ApiProperty()
category!: { id: string; categoryName: string; categoryIcon: string | null };
@ApiProperty({ nullable: true })
tag!: { id: string; tagName: string; tagColor: string | null; tagFontColor: string | null; group: { id: string; groupName: string; sortOrder: number } | null } | null;
@ApiProperty({ type: Array })
tags!: Array<{ id: string; tagName: string; tagColor: string | null; tagFontColor: string | null; group: { id: string; groupName: string; sortOrder: number } | null }>;
@ApiProperty({ nullable: true })
position!: { id: string; indexVal: number } | null;
@ApiProperty({ nullable: true })
image!: string | null;
@ApiProperty({ nullable: true })
price!: string | null;
@ApiProperty()
createdAt!: string;
@ApiProperty()
goodName!: string;
@ApiProperty()
goodPriority!: number;
@ApiProperty()
country!: { id: string; countryName: string; countryIcon: string | null };
@ApiProperty()
category!: { id: string; categoryName: string; categoryIcon: string | null };
@ApiProperty({ nullable: true })
tag!: { id: string; tagName: string; tagColor: string | null; tagFontColor: string | null; group: { id: string; groupName: string; sortOrder: number } | null } | null;
@ApiProperty({ type: Array })
tags!: Array<{ id: string; tagName: string; tagColor: string | null; tagFontColor: string | null; group: { id: string; groupName: string; sortOrder: number } | null }>;
@ApiProperty({ nullable: true })
position!: { id: string; indexVal: number } | null;
@ApiProperty({ nullable: true })
image!: string | null;
@ApiProperty({ nullable: true })
price!: string | null;
@ApiProperty()
createdAt!: string;
}
+29 -29
View File
@@ -1,29 +1,29 @@
import { ApiProperty } from '@nestjs/swagger';
import type { TagGroup as PrismaTagGroup } from '@prisma/client';
export class PublicTagGroupDto {
@ApiProperty()
id!: string;
@ApiProperty()
groupName!: string;
@ApiProperty({ nullable: true })
groupIcon!: string | null;
@ApiProperty({ nullable: true })
groupColor!: string | null;
@ApiProperty()
sortOrder!: number;
static from(g: PrismaTagGroup): PublicTagGroupDto {
return {
id: g.id.toString(),
groupName: g.groupName,
groupIcon: g.groupIcon,
groupColor: g.groupColor,
sortOrder: g.sortOrder,
};
}
}
import { ApiProperty } from '@nestjs/swagger';
import type { TagGroup as PrismaTagGroup } from '@prisma/client';
export class PublicTagGroupDto {
@ApiProperty()
id!: string;
@ApiProperty()
groupName!: string;
@ApiProperty({ nullable: true })
groupIcon!: string | null;
@ApiProperty({ nullable: true })
groupColor!: string | null;
@ApiProperty()
sortOrder!: number;
static from(g: PrismaTagGroup): PublicTagGroupDto {
return {
id: g.id.toString(),
groupName: g.groupName,
groupIcon: g.groupIcon,
groupColor: g.groupColor,
sortOrder: g.sortOrder,
};
}
}
+39 -39
View File
@@ -1,39 +1,39 @@
import { ApiProperty } from '@nestjs/swagger';
import type { Tag as PrismaTag } from '@prisma/client';
export class PublicTagDto {
@ApiProperty()
id!: string;
@ApiProperty()
tagName!: string;
@ApiProperty({ nullable: true })
tagColor!: string | null;
@ApiProperty({ nullable: true })
tagFontColor!: string | null;
@ApiProperty()
sortOrder!: number;
@ApiProperty({ nullable: true })
group!: { id: string; groupName: string; sortOrder: number } | null;
static from(tag: PrismaTag & { tagGroup?: { id: bigint; groupName: string; sortOrder: number } | null }): PublicTagDto {
return {
id: tag.id.toString(),
tagName: tag.tagName,
tagColor: tag.tagColor,
tagFontColor: tag.tagFontColor,
sortOrder: tag.sortOrder,
group: tag.tagGroup
? {
id: tag.tagGroup.id.toString(),
groupName: tag.tagGroup.groupName,
sortOrder: tag.tagGroup.sortOrder,
}
: null,
};
}
}
import { ApiProperty } from '@nestjs/swagger';
import type { Tag as PrismaTag } from '@prisma/client';
export class PublicTagDto {
@ApiProperty()
id!: string;
@ApiProperty()
tagName!: string;
@ApiProperty({ nullable: true })
tagColor!: string | null;
@ApiProperty({ nullable: true })
tagFontColor!: string | null;
@ApiProperty()
sortOrder!: number;
@ApiProperty({ nullable: true })
group!: { id: string; groupName: string; sortOrder: number } | null;
static from(tag: PrismaTag & { tagGroup?: { id: bigint; groupName: string; sortOrder: number } | null }): PublicTagDto {
return {
id: tag.id.toString(),
tagName: tag.tagName,
tagColor: tag.tagColor,
tagFontColor: tag.tagFontColor,
sortOrder: tag.sortOrder,
group: tag.tagGroup
? {
id: tag.tagGroup.id.toString(),
groupName: tag.tagGroup.groupName,
sortOrder: tag.tagGroup.sortOrder,
}
: null,
};
}
}
+22 -22
View File
@@ -13,48 +13,48 @@ import {
ApiTags,
getSchemaPath,
} from '@nestjs/swagger';
import { PublicService } from './public.service';
import { PublicService } from './public.service';
import {
PublicCountryQueryDto,
PublicHomeGoodsQueryDto,
PublicQueryGoodDto,
PublicTagFilterDto,
} from './dto/public-query-good.dto';
import { PublicTagDto } from './dto/public-tag.dto';
import { PublicTagDto } from './dto/public-tag.dto';
import { PublicGoodDetailDto, PublicTagGroupFilterDto } from './dto/public-good-detail.dto';
import { PublicGoodDto } from './dto/public-good.dto';
@ApiTags('public')
@ApiExtraModels(PublicTagFilterDto)
@Controller('public')
export class PublicController {
constructor(private readonly service: PublicService) {}
export class PublicController {
constructor(private readonly service: PublicService) {}
@Get('categories')
@ApiOperation({ summary: '获取商品分类树;countryId 不传时返回全部国家' })
getCategories(@Query() query: PublicCountryQueryDto) {
return this.service.getCategoriesTree(query.countryId);
}
@Get('countries')
@ApiOperation({ summary: 'Public list of countries that have goods' })
getCountries() {
return this.service.getCountries();
}
@Get('tags')
@ApiOperation({ summary: 'Public list of tags that have goods' })
getTags(): Promise<PublicTagDto[]> {
return this.service.getTags();
}
}
@Get('countries')
@ApiOperation({ summary: 'Public list of countries that have goods' })
getCountries() {
return this.service.getCountries();
}
@Get('tags')
@ApiOperation({ summary: 'Public list of tags that have goods' })
getTags(): Promise<PublicTagDto[]> {
return this.service.getTags();
}
@Get('tag-groups')
@ApiOperation({ summary: '获取标签组及标签筛选项;countryId 不传时返回全部国家' })
@ApiOkResponse({ type: [PublicTagGroupFilterDto] })
getTagGroups(@Query() query: PublicCountryQueryDto): Promise<PublicTagGroupFilterDto[]> {
return this.service.getTagGroups(query.countryId);
}
}
@Get('goods')
@ApiOperation({ summary: '分页获取商品' })
@ApiQuery({
+9 -9
View File
@@ -1,9 +1,9 @@
import { Module } from '@nestjs/common';
import { PublicController } from './public.controller';
import { PublicService } from './public.service';
@Module({
controllers: [PublicController],
providers: [PublicService],
})
export class PublicModule {}
import { Module } from '@nestjs/common';
import { PublicController } from './public.controller';
import { PublicService } from './public.service';
@Module({
controllers: [PublicController],
providers: [PublicService],
})
export class PublicModule {}
+228 -228
View File
@@ -1,103 +1,103 @@
import { Test } from '@nestjs/testing';
import { Test } from '@nestjs/testing';
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { PublicService } from './public.service';
import { PrismaService } from '../prisma/prisma.service';
describe('PublicService', () => {
let service: PublicService;
let prisma: PrismaService;
const stamp = Date.now();
let countryId: bigint;
let categoryId: bigint;
let childCategoryId: bigint;
let otherCategoryId: bigint;
import { PublicService } from './public.service';
import { PrismaService } from '../prisma/prisma.service';
describe('PublicService', () => {
let service: PublicService;
let prisma: PrismaService;
const stamp = Date.now();
let countryId: bigint;
let categoryId: bigint;
let childCategoryId: bigint;
let otherCategoryId: bigint;
let tagId: bigint;
let filterGroupIds: bigint[] = [];
let filterTagIds: bigint[] = [];
let originGoodId: bigint;
let goodIds: bigint[] = [];
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
providers: [PublicService, PrismaService],
}).compile();
service = moduleRef.get(PublicService);
prisma = moduleRef.get(PrismaService);
await prisma.onModuleInit();
const country = await prisma.country.create({
data: { countryName: `Pub Country ${stamp}` },
});
countryId = country.id;
const cat = await prisma.category.create({
data: { categoryName: `Pub Cat ${stamp}` },
});
categoryId = cat.id;
const child = await prisma.category.create({
data: { categoryName: `Pub Child ${stamp}`, parentCategoryId: cat.id },
});
childCategoryId = child.id;
const otherCat = await prisma.category.create({
data: { categoryName: `Pub Other ${stamp}` },
});
otherCategoryId = otherCat.id;
const tag = await prisma.tag.create({
data: { tagName: `Pub Tag ${stamp}`, tagColor: '#0000FF' },
});
tagId = tag.id;
const og = await prisma.originGood.create({
data: {
sdsGoodId: `pub-sds-${stamp}`,
goodName: `Origin ${stamp}`,
goodImage: 'http://img',
},
});
originGoodId = og.id;
// Seed 3 goods:
// high priority + position.indexVal=1
// mid priority + position.indexVal=5
// no priority + no position (falls back to createdAt)
const pos1 = await prisma.position.create({
data: { indexVal: 1, countryId, categoryId },
});
const pos2 = await prisma.position.create({
data: { indexVal: 5, countryId, categoryId },
});
const g1 = await prisma.good.create({
data: {
goodName: `Pub High ${stamp}`,
originGoodId,
countryId,
categoryId,
goodPriority: 10,
positionId: pos1.id,
},
});
const g2 = await prisma.good.create({
data: {
goodName: `Pub Mid ${stamp}`,
originGoodId,
countryId,
categoryId,
goodPriority: 5,
positionId: pos2.id,
},
});
const g3 = await prisma.good.create({
data: {
goodName: `Pub NoPos ${stamp}`,
originGoodId,
countryId,
categoryId,
tagId,
goodPriority: 1,
},
});
let originGoodId: bigint;
let goodIds: bigint[] = [];
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
providers: [PublicService, PrismaService],
}).compile();
service = moduleRef.get(PublicService);
prisma = moduleRef.get(PrismaService);
await prisma.onModuleInit();
const country = await prisma.country.create({
data: { countryName: `Pub Country ${stamp}` },
});
countryId = country.id;
const cat = await prisma.category.create({
data: { categoryName: `Pub Cat ${stamp}` },
});
categoryId = cat.id;
const child = await prisma.category.create({
data: { categoryName: `Pub Child ${stamp}`, parentCategoryId: cat.id },
});
childCategoryId = child.id;
const otherCat = await prisma.category.create({
data: { categoryName: `Pub Other ${stamp}` },
});
otherCategoryId = otherCat.id;
const tag = await prisma.tag.create({
data: { tagName: `Pub Tag ${stamp}`, tagColor: '#0000FF' },
});
tagId = tag.id;
const og = await prisma.originGood.create({
data: {
sdsGoodId: `pub-sds-${stamp}`,
goodName: `Origin ${stamp}`,
goodImage: 'http://img',
},
});
originGoodId = og.id;
// Seed 3 goods:
// high priority + position.indexVal=1
// mid priority + position.indexVal=5
// no priority + no position (falls back to createdAt)
const pos1 = await prisma.position.create({
data: { indexVal: 1, countryId, categoryId },
});
const pos2 = await prisma.position.create({
data: { indexVal: 5, countryId, categoryId },
});
const g1 = await prisma.good.create({
data: {
goodName: `Pub High ${stamp}`,
originGoodId,
countryId,
categoryId,
goodPriority: 10,
positionId: pos1.id,
},
});
const g2 = await prisma.good.create({
data: {
goodName: `Pub Mid ${stamp}`,
originGoodId,
countryId,
categoryId,
goodPriority: 5,
positionId: pos2.id,
},
});
const g3 = await prisma.good.create({
data: {
goodName: `Pub NoPos ${stamp}`,
originGoodId,
countryId,
categoryId,
tagId,
goodPriority: 1,
},
});
goodIds = [g1.id, g2.id, g3.id];
const craftGroup = await prisma.tagGroup.create({
@@ -143,102 +143,102 @@ describe('PublicService', () => {
price: 38,
},
});
// Seed a good in `otherCategory` so the "onlyHaveGoods" filter
// returns more than one category.
await prisma.good.create({
data: {
goodName: `Pub Other ${stamp}`,
originGoodId,
countryId,
categoryId: otherCategoryId,
goodPriority: 1,
},
});
// And seed a good in the *child* category, to verify categoryId
// recursion.
await prisma.good.create({
data: {
goodName: `Pub ChildGood ${stamp}`,
originGoodId,
countryId,
categoryId: childCategoryId,
goodPriority: 0,
},
});
});
afterAll(async () => {
if (goodIds.length) {
await prisma.good.deleteMany({ where: { id: { in: goodIds } } });
}
await prisma.good.deleteMany({
where: { goodName: { contains: `Pub ` } },
});
await prisma.position.deleteMany({
where: { countryId },
});
// Seed a good in `otherCategory` so the "onlyHaveGoods" filter
// returns more than one category.
await prisma.good.create({
data: {
goodName: `Pub Other ${stamp}`,
originGoodId,
countryId,
categoryId: otherCategoryId,
goodPriority: 1,
},
});
// And seed a good in the *child* category, to verify categoryId
// recursion.
await prisma.good.create({
data: {
goodName: `Pub ChildGood ${stamp}`,
originGoodId,
countryId,
categoryId: childCategoryId,
goodPriority: 0,
},
});
});
afterAll(async () => {
if (goodIds.length) {
await prisma.good.deleteMany({ where: { id: { in: goodIds } } });
}
await prisma.good.deleteMany({
where: { goodName: { contains: `Pub ` } },
});
await prisma.position.deleteMany({
where: { countryId },
});
await prisma.tag.delete({ where: { id: tagId } });
await prisma.tag.deleteMany({ where: { id: { in: filterTagIds } } });
await prisma.tagGroup.deleteMany({ where: { id: { in: filterGroupIds } } });
await prisma.originGood.delete({ where: { id: originGoodId } });
// Delete children before parent (FK self-relation is RESTRICT).
await prisma.category.delete({ where: { id: childCategoryId } });
await prisma.category.delete({ where: { id: otherCategoryId } });
await prisma.category.delete({ where: { id: categoryId } });
await prisma.country.delete({ where: { id: countryId } });
await prisma.onModuleDestroy();
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('getCategoriesTree returns only categories that have goods', async () => {
const tree = await service.getCategoriesTree();
const allIds = new Set<string>();
const walk = (list: Array<{ id: string; children: Array<{ id: string }> }>) => {
for (const n of list) {
allIds.add(n.id);
walk(n.children as any);
}
};
walk(tree as any);
// We seeded goods in `categoryId`, `childCategoryId`, `otherCategoryId`.
expect(allIds.has(categoryId.toString())).toBe(true);
expect(allIds.has(childCategoryId.toString())).toBe(true);
expect(allIds.has(otherCategoryId.toString())).toBe(true);
});
it('getCountries returns only countries that have goods', async () => {
const countries = await service.getCountries();
expect(countries.find((c) => c.id === countryId.toString())).toBeDefined();
});
it('filters by countryId, tagId, keyword and categoryId (recursively)', async () => {
const filtered = await service.getGoods({
page: 1,
pageSize: 50,
await prisma.originGood.delete({ where: { id: originGoodId } });
// Delete children before parent (FK self-relation is RESTRICT).
await prisma.category.delete({ where: { id: childCategoryId } });
await prisma.category.delete({ where: { id: otherCategoryId } });
await prisma.category.delete({ where: { id: categoryId } });
await prisma.country.delete({ where: { id: countryId } });
await prisma.onModuleDestroy();
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('getCategoriesTree returns only categories that have goods', async () => {
const tree = await service.getCategoriesTree();
const allIds = new Set<string>();
const walk = (list: Array<{ id: string; children: Array<{ id: string }> }>) => {
for (const n of list) {
allIds.add(n.id);
walk(n.children as any);
}
};
walk(tree as any);
// We seeded goods in `categoryId`, `childCategoryId`, `otherCategoryId`.
expect(allIds.has(categoryId.toString())).toBe(true);
expect(allIds.has(childCategoryId.toString())).toBe(true);
expect(allIds.has(otherCategoryId.toString())).toBe(true);
});
it('getCountries returns only countries that have goods', async () => {
const countries = await service.getCountries();
expect(countries.find((c) => c.id === countryId.toString())).toBeDefined();
});
it('filters by countryId, tagId, keyword and categoryId (recursively)', async () => {
const filtered = await service.getGoods({
page: 1,
pageSize: 50,
countryId: countryId.toString(),
categoryId: categoryId.toString(), // includes child
keyword: `Pub `,
});
expect(filtered.total).toBeGreaterThanOrEqual(4); // High, Mid, NoPos, ChildGood
expect(filtered.items.every((g) => g.country.id === countryId.toString())).toBe(true);
});
keyword: `Pub `,
});
expect(filtered.total).toBeGreaterThanOrEqual(4); // High, Mid, NoPos, ChildGood
expect(filtered.items.every((g) => g.country.id === countryId.toString())).toBe(true);
});
it('sorts by priority DESC, position.indexVal ASC, createdAt DESC', async () => {
const result = await service.getGoods({
page: 1,
pageSize: 50,
const result = await service.getGoods({
page: 1,
pageSize: 50,
countryId: countryId.toString(),
keyword: `Pub `,
});
const priorities = result.items.map((g) => g.goodPriority);
// First verify primary descending priority.
const sorted = [...priorities].sort((a, b) => b - a);
expect(priorities).toEqual(sorted);
keyword: `Pub `,
});
const priorities = result.items.map((g) => g.goodPriority);
// First verify primary descending priority.
const sorted = [...priorities].sort((a, b) => b - a);
expect(priorities).toEqual(sorted);
});
it('uses OR within one tag group and AND across tag groups', async () => {
@@ -292,16 +292,16 @@ describe('PublicService', () => {
}),
).rejects.toBeInstanceOf(BadRequestException);
});
it('returns the SDS product id as the public product id', async () => {
const result = await service.getGoods({
page: 1,
pageSize: 1,
const result = await service.getGoods({
page: 1,
pageSize: 1,
countryId: countryId.toString(),
keyword: `Pub High ${stamp}`,
});
expect(result.items).toHaveLength(1);
keyword: `Pub High ${stamp}`,
});
expect(result.items).toHaveLength(1);
expect(result.items[0].goodId).toBe(`pub-sds-${stamp}`);
expect(result.items[0].goodId).not.toBe(goodIds[0].toString());
});
@@ -335,15 +335,15 @@ describe('PublicService', () => {
await prisma.originGood.delete({ where: { id: origin.id } });
}
});
it('getGood returns detail and 404 for unknown id', async () => {
const first = await service.getGoods({
page: 1,
pageSize: 1,
it('getGood returns detail and 404 for unknown id', async () => {
const first = await service.getGoods({
page: 1,
pageSize: 1,
countryId: countryId.toString(),
keyword: `Pub `,
});
expect(first.items.length).toBe(1);
keyword: `Pub `,
});
expect(first.items.length).toBe(1);
const detail = await service.getGood(`pub-sds-${stamp}`);
expect(detail.goodId).toBe(first.items[0].goodId);
expect(detail.productCode).toBe('OZ10827003');
@@ -353,30 +353,30 @@ describe('PublicService', () => {
expect(detail.variants).toHaveLength(1);
await expect(service.getGood('99999999')).rejects.toBeInstanceOf(
NotFoundException,
);
});
it('getTags returns tags with their group info, sorted by group then order', async () => {
const tags = await service.getTags();
expect(tags.length).toBeGreaterThan(0);
// Each tag in our seed (包邮/不包邮/...) should have a group
const grouped = tags.find((t) => t.tagName === '包邮');
if (grouped) {
expect(grouped.group).not.toBeNull();
expect(grouped.group!.groupName).toBe('物流渠道');
}
});
it('getTagGroups returns only groups that have goods', async () => {
const groups = await service.getTagGroups();
expect(groups.length).toBeGreaterThan(0);
const names = groups.map((g) => g.groupName);
expect(names).toContain('物流渠道');
expect(names).toContain('印刷位置');
expect(names).toContain('印刷工艺');
// Sorted by sortOrder
const sortOrders = groups.map((g) => g.sortOrder);
expect([...sortOrders].sort((a, b) => a - b)).toEqual(sortOrders);
});
});
NotFoundException,
);
});
it('getTags returns tags with their group info, sorted by group then order', async () => {
const tags = await service.getTags();
expect(tags.length).toBeGreaterThan(0);
// Each tag in our seed (包邮/不包邮/...) should have a group
const grouped = tags.find((t) => t.tagName === '包邮');
if (grouped) {
expect(grouped.group).not.toBeNull();
expect(grouped.group!.groupName).toBe('物流渠道');
}
});
it('getTagGroups returns only groups that have goods', async () => {
const groups = await service.getTagGroups();
expect(groups.length).toBeGreaterThan(0);
const names = groups.map((g) => g.groupName);
expect(names).toContain('物流渠道');
expect(names).toContain('印刷位置');
expect(names).toContain('印刷工艺');
// Sorted by sortOrder
const sortOrders = groups.map((g) => g.sortOrder);
expect([...sortOrders].sort((a, b) => a - b)).toEqual(sortOrders);
});
});
+64 -1
View File
@@ -205,7 +205,9 @@ export class PublicService {
if (!good) {
throw new NotFoundException({ message: '不存在商品', error: 'PRODUCT_NOT_FOUND' });
}
return this.toPublicGoodDetail(good);
const dto = this.toPublicGoodDetail(good);
dto.category.categoryIcon = await this.resolveCategoryIcon(good.category);
return dto;
}
async getHomeGoods(query: PublicHomeGoodsQueryDto): Promise<PublicGoodDto[]> {
@@ -270,6 +272,66 @@ export class PublicService {
};
}
/** Group distinct variant images by color so the frontend can switch media per color.
* Only color-specific photos are included (main / result / detail images);
* design-layer素材图 and the product-level blank garment photo are excluded
* because they are not per-color gallery photos. */
private groupImagesByColor(
variants: PublicGoodRow['originGood']['variants'],
): Array<{ colorId: string | null; colorName: string | null; colorHex: string | null; images: string[] }> {
const groups = new Map<string, {
colorId: string | null;
colorName: string | null;
colorHex: string | null;
images: string[];
}>();
for (const variant of variants) {
const key = variant.colorId ?? `variant:${variant.sdsVariantId}`;
let group = groups.get(key);
if (!group) {
group = {
colorId: variant.colorId,
colorName: variant.colorName,
colorHex: variant.colorHex,
images: [],
};
groups.set(key, group);
}
const design = (variant.designData ?? {}) as {
detailImgUrls?: Array<{ imageUrl?: unknown }>;
prototypeResultGroups?: Array<{ resultImage?: unknown }>;
};
const urls: unknown[] = [
variant.imageUrl,
...(design.prototypeResultGroups ?? []).map((item) => item?.resultImage),
...(design.detailImgUrls ?? []).map((image) => image?.imageUrl),
];
for (const url of urls) {
const value = typeof url === 'string' ? url.trim() : '';
if (value && !group.images.includes(value)) {
group.images.push(value);
}
}
}
return [...groups.values()];
}
/** Leaf categories often have no icon upstream; fall back to the nearest ancestor that has one. */
private async resolveCategoryIcon(category: PublicGoodRow['category']): Promise<string | null> {
if (category.categoryIcon) return category.categoryIcon;
let cursor = category.parentCategoryId;
for (let depth = 0; cursor !== null && depth < 10; depth++) {
const parent = await this.prisma.category.findUnique({
where: { id: cursor },
select: { categoryIcon: true, parentCategoryId: true },
});
if (!parent) break;
if (parent.categoryIcon) return parent.categoryIcon;
cursor = parent.parentCategoryId;
}
return null;
}
private toPublicGoodDetail(good: PublicGoodRow): PublicGoodDetailDto {
const base = this.toPublicGood(good);
const detail = good.originGood.detail;
@@ -292,6 +354,7 @@ export class PublicService {
pictureRequest: detail?.pictureRequest ?? null,
},
media: (detail?.media as Record<string, unknown> | null) ?? null,
mediaByColor: this.groupImagesByColor(good.originGood.variants),
options: (detail?.options as Record<string, unknown> | null) ?? null,
sizeChart: (detail?.sizeChart as Record<string, unknown> | null) ?? null,
packageSpecs: (detail?.packageSpecs as Record<string, unknown> | null) ?? null,