feat(catalog): product visibility whitelist by phone
Admin can limit ON_SALE products to test phones; C-end filters by user phone. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -593,18 +593,35 @@ model CommonProductItem {
|
||||
status ProductStatus @default(DRAFT)
|
||||
sortOrder Int @default(0) @map("sort_order")
|
||||
allowOnSitePickup Boolean @default(false) @map("allow_on_site_pickup")
|
||||
/// Online test: only listed phones can see/buy when enabled
|
||||
visibilityWhitelistEnabled Boolean @default(false) @map("visibility_whitelist_enabled")
|
||||
coverResourceId BigInt? @map("cover_resource_id") @db.UnsignedBigInt
|
||||
detailContent Json? @map("detail_content")
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
|
||||
|
||||
coverResource CommonResource? @relation("ProductCover", fields: [coverResourceId], references: [id], onDelete: SetNull)
|
||||
orders Order[]
|
||||
coverResource CommonResource? @relation("ProductCover", fields: [coverResourceId], references: [id], onDelete: SetNull)
|
||||
orders Order[]
|
||||
visibilityPhones CommonProductVisibilityPhone[]
|
||||
|
||||
@@index([status, aromaType])
|
||||
@@map("common_product_item")
|
||||
}
|
||||
|
||||
/// Product visibility whitelist phones (match by bound phone)
|
||||
model CommonProductVisibilityPhone {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
productId BigInt @map("product_id") @db.UnsignedBigInt
|
||||
phone String @db.VarChar(20)
|
||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||
|
||||
product CommonProductItem @relation(fields: [productId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([productId, phone])
|
||||
@@index([phone])
|
||||
@@map("common_product_visibility_phone")
|
||||
}
|
||||
|
||||
model CommonProductDetailTemplate {
|
||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||
code String @unique @db.VarChar(32)
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { Controller, Get, Param, Query } from '@nestjs/common';
|
||||
import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
|
||||
import { CatalogService } from './catalog.service';
|
||||
import { OptionalJwtAuthGuard } from '../../common/guards/optional-jwt-auth.guard';
|
||||
import { CurrentUser } from '../../common/decorators/current-user.decorator';
|
||||
import type { AuthUser } from '../../common/guards/jwt-auth.guard';
|
||||
|
||||
@Controller('catalog')
|
||||
export class CatalogController {
|
||||
@@ -11,12 +14,25 @@ export class CatalogController {
|
||||
}
|
||||
|
||||
@Get('products')
|
||||
products(@Query('aromaType') aromaType?: string, @Query('cityCode') cityCode?: string) {
|
||||
return this.catalogService.listProducts(aromaType, cityCode);
|
||||
@UseGuards(OptionalJwtAuthGuard)
|
||||
async products(
|
||||
@CurrentUser() user: AuthUser | undefined,
|
||||
@Query('aromaType') aromaType?: string,
|
||||
@Query('cityCode') cityCode?: string,
|
||||
) {
|
||||
const viewerPhone = await this.resolveViewerPhone(user);
|
||||
return this.catalogService.listProducts(aromaType, cityCode, { phone: viewerPhone });
|
||||
}
|
||||
|
||||
@Get('products/:id')
|
||||
product(@Param('id') id: string) {
|
||||
return this.catalogService.getProduct(BigInt(id));
|
||||
@UseGuards(OptionalJwtAuthGuard)
|
||||
async product(@CurrentUser() user: AuthUser | undefined, @Param('id') id: string) {
|
||||
const viewerPhone = await this.resolveViewerPhone(user);
|
||||
return this.catalogService.getProduct(BigInt(id), { phone: viewerPhone });
|
||||
}
|
||||
|
||||
private async resolveViewerPhone(user?: AuthUser) {
|
||||
if (!user || user.actorType !== 'USER') return null;
|
||||
return this.catalogService.resolveUserPhone(user.actorId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { IamModule } from '../iam/iam.module';
|
||||
import { CatalogController } from './catalog.controller';
|
||||
import { CatalogService } from './catalog.service';
|
||||
|
||||
@Module({
|
||||
imports: [IamModule],
|
||||
controllers: [CatalogController],
|
||||
providers: [CatalogService],
|
||||
exports: [CatalogService],
|
||||
|
||||
@@ -3,6 +3,17 @@ import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||
import { groupResourcesByProductId, mapProductMedia } from './catalog.mapper';
|
||||
|
||||
export type CatalogViewer = {
|
||||
/** C 端用户手机号;无则无法看到白名单商品 */
|
||||
phone?: string | null;
|
||||
/** 合伙人代下单等内部场景跳过白名单 */
|
||||
bypassWhitelist?: boolean;
|
||||
};
|
||||
|
||||
function normalizePhone(phone: string | null | undefined): string {
|
||||
return (phone || '').replace(/\D/g, '').trim();
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class CatalogService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
@@ -34,7 +45,7 @@ export class CatalogService {
|
||||
);
|
||||
}
|
||||
|
||||
async listProducts(aromaType?: string, cityCode?: string) {
|
||||
async listProducts(aromaType?: string, cityCode?: string, viewer?: CatalogViewer) {
|
||||
if (cityCode) {
|
||||
const city = await this.prisma.commonCity.findFirst({
|
||||
where: { code: cityCode, status: 'ACTIVE' },
|
||||
@@ -45,10 +56,15 @@ export class CatalogService {
|
||||
const products = await this.prisma.commonProductItem.findMany({
|
||||
where: { status: 'ON_SALE', ...(aromaType ? { aromaType: aromaType as never } : {}) },
|
||||
orderBy: { sortOrder: 'asc' },
|
||||
include: { coverResource: true },
|
||||
include: {
|
||||
coverResource: true,
|
||||
visibilityPhones: { select: { phone: true } },
|
||||
},
|
||||
});
|
||||
|
||||
const productIds = products.map((p) => p.id);
|
||||
const visible = products.filter((p) => this.isVisibleToViewer(p, viewer));
|
||||
|
||||
const productIds = visible.map((p) => p.id);
|
||||
const resources = productIds.length
|
||||
? await this.prisma.commonResource.findMany({
|
||||
where: {
|
||||
@@ -63,10 +79,13 @@ export class CatalogService {
|
||||
const resourceMap = groupResourcesByProductId(resources);
|
||||
|
||||
return serializeBigInt(
|
||||
products.map((p) => {
|
||||
visible.map((p) => {
|
||||
const media = mapProductMedia(p, resourceMap.get(p.id.toString()) ?? []);
|
||||
const { visibilityPhones, ...rest } = p;
|
||||
return {
|
||||
...p,
|
||||
...rest,
|
||||
visibilityWhitelistEnabled: p.visibilityWhitelistEnabled,
|
||||
visibilityPhones: visibilityPhones.map((row) => row.phone),
|
||||
benefitAmount: p.benefitAmount ?? p.price,
|
||||
price: Number(p.price),
|
||||
benefitDisplay: Number(p.benefitAmount ?? p.price),
|
||||
@@ -76,12 +95,18 @@ export class CatalogService {
|
||||
);
|
||||
}
|
||||
|
||||
async getProduct(id: bigint) {
|
||||
async getProduct(id: bigint, viewer?: CatalogViewer) {
|
||||
const product = await this.prisma.commonProductItem.findUnique({
|
||||
where: { id },
|
||||
include: { coverResource: true },
|
||||
include: {
|
||||
coverResource: true,
|
||||
visibilityPhones: { select: { phone: true } },
|
||||
},
|
||||
});
|
||||
if (!product) return null;
|
||||
if (!this.isVisibleToViewer(product, viewer)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resources = await this.prisma.commonResource.findMany({
|
||||
where: {
|
||||
@@ -94,11 +119,51 @@ export class CatalogService {
|
||||
});
|
||||
|
||||
const media = mapProductMedia(product, resources);
|
||||
const { visibilityPhones, ...rest } = product;
|
||||
return serializeBigInt({
|
||||
...product,
|
||||
...rest,
|
||||
visibilityWhitelistEnabled: product.visibilityWhitelistEnabled,
|
||||
visibilityPhones: visibilityPhones.map((row) => row.phone),
|
||||
benefitAmount: product.benefitAmount ?? product.price,
|
||||
price: Number(product.price),
|
||||
...media,
|
||||
});
|
||||
}
|
||||
|
||||
/** 下单前校验:白名单商品仅白名单手机号可买 */
|
||||
async assertPurchasable(productId: bigint, viewerPhone?: string | null) {
|
||||
const product = await this.prisma.commonProductItem.findUnique({
|
||||
where: { id: productId },
|
||||
include: { visibilityPhones: { select: { phone: true } } },
|
||||
});
|
||||
if (!product || product.status !== 'ON_SALE') {
|
||||
throw new BadRequestException('商品不可购买');
|
||||
}
|
||||
if (!this.isVisibleToViewer(product, { phone: viewerPhone })) {
|
||||
throw new BadRequestException('该商品暂不对当前账号开放');
|
||||
}
|
||||
return product;
|
||||
}
|
||||
|
||||
async resolveUserPhone(userId: bigint): Promise<string | null> {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: { phone: true },
|
||||
});
|
||||
return user?.phone ?? null;
|
||||
}
|
||||
|
||||
isVisibleToViewer(
|
||||
product: {
|
||||
visibilityWhitelistEnabled: boolean;
|
||||
visibilityPhones: Array<{ phone: string }>;
|
||||
},
|
||||
viewer?: CatalogViewer,
|
||||
): boolean {
|
||||
if (viewer?.bypassWhitelist) return true;
|
||||
if (!product.visibilityWhitelistEnabled) return true;
|
||||
const phone = normalizePhone(viewer?.phone);
|
||||
if (!phone) return false;
|
||||
return product.visibilityPhones.some((row) => normalizePhone(row.phone) === phone);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,24 @@ import { groupResourcesByProductId, mapProductMedia } from '../catalog/catalog.m
|
||||
import type { AdminProductsQueryDto } from './dto/admin-query.dto';
|
||||
import type { CreateProductDto, UpdateProductDto } from './dto/admin-mutate.dto';
|
||||
|
||||
function normalizePhones(phones?: string[]): string[] {
|
||||
if (!phones?.length) return [];
|
||||
const out: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const raw of phones) {
|
||||
const phone = String(raw || '')
|
||||
.replace(/\D/g, '')
|
||||
.trim();
|
||||
if (!phone || seen.has(phone)) continue;
|
||||
if (!/^1\d{10}$/.test(phone)) {
|
||||
throw new BadRequestException(`手机号格式无效:${raw}`);
|
||||
}
|
||||
seen.add(phone);
|
||||
out.push(phone);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminProductsService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
@@ -24,7 +42,10 @@ export class AdminProductsService {
|
||||
orderBy: { sortOrder: 'asc' },
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
include: { coverResource: true },
|
||||
include: {
|
||||
coverResource: true,
|
||||
visibilityPhones: { select: { phone: true }, orderBy: { phone: 'asc' } },
|
||||
},
|
||||
}),
|
||||
this.prisma.commonProductItem.count({ where }),
|
||||
]);
|
||||
@@ -54,7 +75,10 @@ export class AdminProductsService {
|
||||
async detail(id: bigint) {
|
||||
const product = await this.prisma.commonProductItem.findUnique({
|
||||
where: { id },
|
||||
include: { coverResource: true },
|
||||
include: {
|
||||
coverResource: true,
|
||||
visibilityPhones: { select: { phone: true }, orderBy: { phone: 'asc' } },
|
||||
},
|
||||
});
|
||||
if (!product) throw new NotFoundException('商品不存在');
|
||||
|
||||
@@ -77,6 +101,9 @@ export class AdminProductsService {
|
||||
});
|
||||
if (exists) throw new BadRequestException('SKU 或 69 码已存在');
|
||||
|
||||
const phones = normalizePhones(dto.visibilityPhones);
|
||||
const whitelistEnabled = !!dto.visibilityWhitelistEnabled;
|
||||
|
||||
const product = await this.prisma.commonProductItem.create({
|
||||
data: {
|
||||
skuCode: dto.skuCode,
|
||||
@@ -90,9 +117,17 @@ export class AdminProductsService {
|
||||
status: (dto.status ?? 'DRAFT') as 'DRAFT' | 'ON_SALE' | 'OFF_SALE',
|
||||
sortOrder: dto.sortOrder ?? 0,
|
||||
allowOnSitePickup: dto.allowOnSitePickup ?? false,
|
||||
visibilityWhitelistEnabled: whitelistEnabled,
|
||||
...(dto.detailContent !== undefined
|
||||
? { detailContent: dto.detailContent as Prisma.InputJsonValue }
|
||||
: {}),
|
||||
...(phones.length
|
||||
? {
|
||||
visibilityPhones: {
|
||||
create: phones.map((phone) => ({ phone })),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -120,12 +155,19 @@ export class AdminProductsService {
|
||||
...(dto.status !== undefined ? { status: dto.status as 'DRAFT' | 'ON_SALE' | 'OFF_SALE' } : {}),
|
||||
...(dto.sortOrder !== undefined ? { sortOrder: dto.sortOrder } : {}),
|
||||
...(dto.allowOnSitePickup !== undefined ? { allowOnSitePickup: dto.allowOnSitePickup } : {}),
|
||||
...(dto.visibilityWhitelistEnabled !== undefined
|
||||
? { visibilityWhitelistEnabled: !!dto.visibilityWhitelistEnabled }
|
||||
: {}),
|
||||
...(dto.detailContent !== undefined
|
||||
? { detailContent: dto.detailContent as Prisma.InputJsonValue }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
|
||||
if (dto.visibilityPhones !== undefined) {
|
||||
await this.syncVisibilityPhones(id, normalizePhones(dto.visibilityPhones));
|
||||
}
|
||||
|
||||
if (dto.coverUrl) {
|
||||
await this.syncCover(id, dto.coverUrl);
|
||||
}
|
||||
@@ -154,13 +196,30 @@ export class AdminProductsService {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
private async syncVisibilityPhones(productId: bigint, phones: string[]) {
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.commonProductVisibilityPhone.deleteMany({ where: { productId } });
|
||||
if (!phones.length) return;
|
||||
await tx.commonProductVisibilityPhone.createMany({
|
||||
data: phones.map((phone) => ({ productId, phone })),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
private formatProduct(
|
||||
product: Prisma.CommonProductItemGetPayload<{ include: { coverResource: true } }>,
|
||||
product: Prisma.CommonProductItemGetPayload<{
|
||||
include: {
|
||||
coverResource: true;
|
||||
visibilityPhones: { select: { phone: true } };
|
||||
};
|
||||
}>,
|
||||
extraResources: Prisma.CommonResourceGetPayload<object>[],
|
||||
) {
|
||||
const media = mapProductMedia(product, extraResources);
|
||||
const phones = product.visibilityPhones?.map((row) => row.phone) ?? [];
|
||||
return {
|
||||
...product,
|
||||
visibilityPhones: phones,
|
||||
price: Number(product.price),
|
||||
benefitAmount: Number(product.benefitAmount ?? product.price),
|
||||
...media,
|
||||
|
||||
@@ -1110,6 +1110,17 @@ export class CreateProductDto {
|
||||
@IsBoolean()
|
||||
allowOnSitePickup?: boolean;
|
||||
|
||||
/** 开启后仅白名单手机号在 C 端可见/可购 */
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
|
||||
/** 可见白名单手机号列表 */
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
visibilityPhones?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
coverUrl?: string;
|
||||
@@ -1162,6 +1173,17 @@ export class UpdateProductDto {
|
||||
@IsBoolean()
|
||||
allowOnSitePickup?: boolean;
|
||||
|
||||
/** 开启后仅白名单手机号在 C 端可见/可购 */
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
visibilityWhitelistEnabled?: boolean;
|
||||
|
||||
/** 可见白名单手机号列表 */
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
visibilityPhones?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
coverUrl?: string;
|
||||
|
||||
@@ -57,7 +57,8 @@ export class TradeService {
|
||||
userId: bigint,
|
||||
body: { productId: string; quantity: number; addressId?: string; onSitePickup?: boolean },
|
||||
) {
|
||||
const product = await this.catalogService.getProduct(BigInt(body.productId));
|
||||
const viewerPhone = await this.catalogService.resolveUserPhone(userId);
|
||||
const product = await this.catalogService.getProduct(BigInt(body.productId), { phone: viewerPhone });
|
||||
if (!product || product.status !== 'ON_SALE') {
|
||||
throw new BadRequestException('商品不可购买');
|
||||
}
|
||||
@@ -1035,7 +1036,7 @@ export class TradeService {
|
||||
async getPartnerProxyOrderOptions(partnerAccountId: bigint) {
|
||||
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
|
||||
const [products, promoCodes, stores] = await Promise.all([
|
||||
this.catalogService.listProducts(),
|
||||
this.catalogService.listProducts(undefined, undefined, { bypassWhitelist: true }),
|
||||
this.promoCodeService.listActiveOptions(),
|
||||
this.prisma.store.findMany({
|
||||
where: { partnerAccountId: primary.id },
|
||||
@@ -1083,7 +1084,9 @@ export class TradeService {
|
||||
receiverCity?: string;
|
||||
receiverDistrict?: string;
|
||||
}) {
|
||||
const product = await this.catalogService.getProduct(BigInt(body.productId));
|
||||
const product = await this.catalogService.getProduct(BigInt(body.productId), {
|
||||
bypassWhitelist: true,
|
||||
});
|
||||
if (!product || product.status !== 'ON_SALE') {
|
||||
throw new BadRequestException('商品不可购买');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user