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:
@@ -1,4 +1,4 @@
|
|||||||
import { useState } from 'react';
|
import { useMemo, useRef, useState } from 'react';
|
||||||
import {
|
import {
|
||||||
Button, Descriptions, Divider, Drawer, Form, Input, InputNumber, Modal, Popconfirm, Select, Space,
|
Button, Descriptions, Divider, Drawer, Form, Input, InputNumber, Modal, Popconfirm, Select, Space,
|
||||||
Switch, Table, Tabs, Tag, Typography, message,
|
Switch, Table, Tabs, Tag, Typography, message,
|
||||||
@@ -32,6 +32,8 @@ type Row = {
|
|||||||
status: string;
|
status: string;
|
||||||
sortOrder: number;
|
sortOrder: number;
|
||||||
allowOnSitePickup?: boolean;
|
allowOnSitePickup?: boolean;
|
||||||
|
visibilityWhitelistEnabled?: boolean;
|
||||||
|
visibilityPhones?: string[];
|
||||||
mainImageUrl?: string | null;
|
mainImageUrl?: string | null;
|
||||||
carouselUrls?: string[];
|
carouselUrls?: string[];
|
||||||
detailImageUrls?: string[];
|
detailImageUrls?: string[];
|
||||||
@@ -51,6 +53,8 @@ type ProductFormValues = {
|
|||||||
status?: string;
|
status?: string;
|
||||||
sortOrder?: number;
|
sortOrder?: number;
|
||||||
allowOnSitePickup?: boolean;
|
allowOnSitePickup?: boolean;
|
||||||
|
visibilityWhitelistEnabled?: boolean;
|
||||||
|
visibilityPhones?: string[];
|
||||||
coverUrl?: string;
|
coverUrl?: string;
|
||||||
carouselUrls?: string[];
|
carouselUrls?: string[];
|
||||||
detailImageUrls?: string[];
|
detailImageUrls?: string[];
|
||||||
@@ -59,6 +63,13 @@ type ProductFormValues = {
|
|||||||
features?: Array<{ icon?: string; title?: string; desc?: string }>;
|
features?: Array<{ icon?: string; title?: string; desc?: string }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type UserPickRow = {
|
||||||
|
id: string;
|
||||||
|
phone?: string | null;
|
||||||
|
nickname?: string | null;
|
||||||
|
userNo?: string;
|
||||||
|
};
|
||||||
|
|
||||||
function mapDetailToForm(d: Record<string, unknown>) {
|
function mapDetailToForm(d: Record<string, unknown>) {
|
||||||
const detail = (d.detailContent ?? {}) as ProductDetailContentDto;
|
const detail = (d.detailContent ?? {}) as ProductDetailContentDto;
|
||||||
return {
|
return {
|
||||||
@@ -66,6 +77,8 @@ function mapDetailToForm(d: Record<string, unknown>) {
|
|||||||
coverUrl: (d as { mainImageUrl?: string }).mainImageUrl,
|
coverUrl: (d as { mainImageUrl?: string }).mainImageUrl,
|
||||||
carouselUrls: ((d as Row).carouselUrls?.length ? (d as Row).carouselUrls : ['']) as string[],
|
carouselUrls: ((d as Row).carouselUrls?.length ? (d as Row).carouselUrls : ['']) as string[],
|
||||||
detailImageUrls: ((d as Row).detailImageUrls?.length ? (d as Row).detailImageUrls : ['']) as string[],
|
detailImageUrls: ((d as Row).detailImageUrls?.length ? (d as Row).detailImageUrls : ['']) as string[],
|
||||||
|
visibilityWhitelistEnabled: !!(d as Row).visibilityWhitelistEnabled,
|
||||||
|
visibilityPhones: ((d as Row).visibilityPhones ?? []) as string[],
|
||||||
storyTitle: detail.storyTitle ?? '',
|
storyTitle: detail.storyTitle ?? '',
|
||||||
storyText: detail.storyText ?? '',
|
storyText: detail.storyText ?? '',
|
||||||
features: detail.features?.length
|
features: detail.features?.length
|
||||||
@@ -91,6 +104,10 @@ function buildProductPayload(v: ProductFormValues) {
|
|||||||
features: features.length ? features : undefined,
|
features: features.length ? features : undefined,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const visibilityPhones = (v.visibilityPhones ?? [])
|
||||||
|
.map((p) => String(p || '').replace(/\D/g, '').trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
skuCode: v.skuCode,
|
skuCode: v.skuCode,
|
||||||
barcode69: v.barcode69,
|
barcode69: v.barcode69,
|
||||||
@@ -103,6 +120,8 @@ function buildProductPayload(v: ProductFormValues) {
|
|||||||
status: v.status,
|
status: v.status,
|
||||||
sortOrder: v.sortOrder,
|
sortOrder: v.sortOrder,
|
||||||
allowOnSitePickup: !!v.allowOnSitePickup,
|
allowOnSitePickup: !!v.allowOnSitePickup,
|
||||||
|
visibilityWhitelistEnabled: !!v.visibilityWhitelistEnabled,
|
||||||
|
visibilityPhones,
|
||||||
coverUrl: v.coverUrl,
|
coverUrl: v.coverUrl,
|
||||||
carouselUrls,
|
carouselUrls,
|
||||||
detailImageUrls,
|
detailImageUrls,
|
||||||
@@ -183,7 +202,88 @@ function ProductDetailFields({ form, aromaType }: { form: FormInstance; aromaTyp
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function BaseInfoFields({ mode }: { mode: 'create' | 'edit' }) {
|
function VisibilityWhitelistFields({ form }: { form: FormInstance }) {
|
||||||
|
const [userOptions, setUserOptions] = useState<UserPickRow[]>([]);
|
||||||
|
const [userSearching, setUserSearching] = useState(false);
|
||||||
|
const searchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
|
async function searchUsers(keyword: string) {
|
||||||
|
const q = keyword.trim();
|
||||||
|
if (searchTimer.current) clearTimeout(searchTimer.current);
|
||||||
|
if (!q) {
|
||||||
|
setUserOptions([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
searchTimer.current = setTimeout(() => {
|
||||||
|
void (async () => {
|
||||||
|
setUserSearching(true);
|
||||||
|
try {
|
||||||
|
const qs = new URLSearchParams({ page: '1', pageSize: '20', phone: q });
|
||||||
|
const res = await request<{ items: UserPickRow[] }>(`/admin/users?${qs}`);
|
||||||
|
setUserOptions((res.items ?? []).filter((u) => !!u.phone));
|
||||||
|
} catch {
|
||||||
|
setUserOptions([]);
|
||||||
|
} finally {
|
||||||
|
setUserSearching(false);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}, 300);
|
||||||
|
}
|
||||||
|
|
||||||
|
const enabled = Form.useWatch('visibilityWhitelistEnabled', form);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Form.Item
|
||||||
|
name="visibilityWhitelistEnabled"
|
||||||
|
label="可见白名单"
|
||||||
|
valuePropName="checked"
|
||||||
|
extra="开启后仅名单内手机号在 C 端可见/可购,用于在线测试"
|
||||||
|
>
|
||||||
|
<Switch checkedChildren="开" unCheckedChildren="关" />
|
||||||
|
</Form.Item>
|
||||||
|
{enabled ? (
|
||||||
|
<>
|
||||||
|
<Form.Item
|
||||||
|
name="visibilityPhones"
|
||||||
|
label="白名单手机号"
|
||||||
|
rules={[{ required: true, message: '请至少添加一个手机号' }]}
|
||||||
|
extra="可直接输入多个手机号回车添加,或从下方用户库选择"
|
||||||
|
>
|
||||||
|
<Select
|
||||||
|
mode="tags"
|
||||||
|
tokenSeparators={[',', ' ', ',', ';', ';']}
|
||||||
|
placeholder="输入手机号后回车"
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
<Form.Item label="从用户库添加">
|
||||||
|
<Select
|
||||||
|
showSearch
|
||||||
|
filterOption={false}
|
||||||
|
placeholder="按手机号搜索用户"
|
||||||
|
loading={userSearching}
|
||||||
|
options={userOptions.map((u) => ({
|
||||||
|
value: u.phone!,
|
||||||
|
label: `${u.phone}${u.nickname ? ` · ${u.nickname}` : ''}${u.userNo ? `(${u.userNo})` : ''}`,
|
||||||
|
}))}
|
||||||
|
onSearch={searchUsers}
|
||||||
|
onSelect={(phone: string) => {
|
||||||
|
const cur = (form.getFieldValue('visibilityPhones') as string[] | undefined) ?? [];
|
||||||
|
if (!cur.includes(phone)) {
|
||||||
|
form.setFieldsValue({ visibilityPhones: [...cur, phone] });
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
notFoundContent={userSearching ? '搜索中…' : '输入手机号搜索'}
|
||||||
|
/>
|
||||||
|
</Form.Item>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function BaseInfoFields({ mode, form }: { mode: 'create' | 'edit'; form: FormInstance }) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{mode === 'create' && (
|
{mode === 'create' && (
|
||||||
@@ -223,6 +323,7 @@ function BaseInfoFields({ mode }: { mode: 'create' | 'edit' }) {
|
|||||||
<Form.Item name="allowOnSitePickup" label="允许现场取货" valuePropName="checked">
|
<Form.Item name="allowOnSitePickup" label="允许现场取货" valuePropName="checked">
|
||||||
<Switch checkedChildren="开" unCheckedChildren="关" />
|
<Switch checkedChildren="开" unCheckedChildren="关" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
|
<VisibilityWhitelistFields form={form} />
|
||||||
<Form.Item name="coverUrl" label="封面">
|
<Form.Item name="coverUrl" label="封面">
|
||||||
<OssUpload bizType="COVER" mediaType="IMAGE" />
|
<OssUpload bizType="COVER" mediaType="IMAGE" />
|
||||||
</Form.Item>
|
</Form.Item>
|
||||||
@@ -264,7 +365,7 @@ export default function ProductsPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const columns: ColumnsType<Row> = [
|
const columns: ColumnsType<Row> = useMemo(() => [
|
||||||
{ title: 'SKU', dataIndex: 'skuCode', width: 90 },
|
{ title: 'SKU', dataIndex: 'skuCode', width: 90 },
|
||||||
{ title: '商品名', dataIndex: 'name', width: 180, ellipsis: true },
|
{ title: '商品名', dataIndex: 'name', width: 180, ellipsis: true },
|
||||||
{ title: '香型', dataIndex: 'aromaType', width: 80, render: (v) => AROMA_TYPE_LABELS[v] || v },
|
{ title: '香型', dataIndex: 'aromaType', width: 80, render: (v) => AROMA_TYPE_LABELS[v] || v },
|
||||||
@@ -274,6 +375,13 @@ export default function ProductsPage() {
|
|||||||
{ title: '状态', dataIndex: 'status', width: 80, render: (s) => (
|
{ title: '状态', dataIndex: 'status', width: 80, render: (s) => (
|
||||||
<Tag color={s === 'ON_SALE' ? 'green' : undefined}>{PRODUCT_STATUS_LABELS[s] || s}</Tag>
|
<Tag color={s === 'ON_SALE' ? 'green' : undefined}>{PRODUCT_STATUS_LABELS[s] || s}</Tag>
|
||||||
) },
|
) },
|
||||||
|
{
|
||||||
|
title: '白名单',
|
||||||
|
dataIndex: 'visibilityWhitelistEnabled',
|
||||||
|
width: 90,
|
||||||
|
render: (v: boolean, row) =>
|
||||||
|
v ? <Tag color="orange">限{row.visibilityPhones?.length ?? 0}人</Tag> : <Tag>公开</Tag>,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
title: '现场取货',
|
title: '现场取货',
|
||||||
dataIndex: 'allowOnSitePickup',
|
dataIndex: 'allowOnSitePickup',
|
||||||
@@ -305,7 +413,7 @@ export default function ProductsPage() {
|
|||||||
</Space>
|
</Space>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
];
|
], [detail, editForm]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
@@ -323,7 +431,7 @@ export default function ProductsPage() {
|
|||||||
</Form.Item>
|
</Form.Item>
|
||||||
<Form.Item><Button type="primary" htmlType="submit">查询</Button></Form.Item>
|
<Form.Item><Button type="primary" htmlType="submit">查询</Button></Form.Item>
|
||||||
</Form>
|
</Form>
|
||||||
<Table rowKey="id" className="admin-table-nowrap" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 1140 }}
|
<Table rowKey="id" className="admin-table-nowrap" loading={loading} columns={columns} dataSource={data?.items ?? []} scroll={{ x: 1240 }}
|
||||||
pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
|
pagination={{ current: page, pageSize, total: data?.total ?? 0, showSizeChanger: true, onChange: (p, ps) => { setPage(p); setPageSize(ps); } }} />
|
||||||
<Drawer title="编辑商品" width={720} open={drawerOpen} onClose={() => setDrawerOpen(false)}
|
<Drawer title="编辑商品" width={720} open={drawerOpen} onClose={() => setDrawerOpen(false)}
|
||||||
extra={detail && (
|
extra={detail && (
|
||||||
@@ -345,7 +453,7 @@ export default function ProductsPage() {
|
|||||||
</Descriptions>
|
</Descriptions>
|
||||||
<Form form={editForm} layout="vertical">
|
<Form form={editForm} layout="vertical">
|
||||||
<Tabs items={[
|
<Tabs items={[
|
||||||
{ key: 'base', label: '基础信息', children: <BaseInfoFields mode="edit" /> },
|
{ key: 'base', label: '基础信息', children: <BaseInfoFields mode="edit" form={editForm} /> },
|
||||||
{
|
{
|
||||||
key: 'detail',
|
key: 'detail',
|
||||||
label: '详情页',
|
label: '详情页',
|
||||||
@@ -372,11 +480,12 @@ export default function ProductsPage() {
|
|||||||
}} width={720}>
|
}} width={720}>
|
||||||
<Form form={createForm} layout="vertical" initialValues={{
|
<Form form={createForm} layout="vertical" initialValues={{
|
||||||
aromaType: 'QINGXIANG', status: 'DRAFT', sortOrder: 0, allowOnSitePickup: false,
|
aromaType: 'QINGXIANG', status: 'DRAFT', sortOrder: 0, allowOnSitePickup: false,
|
||||||
|
visibilityWhitelistEnabled: false, visibilityPhones: [],
|
||||||
carouselUrls: [''], detailImageUrls: [''],
|
carouselUrls: [''], detailImageUrls: [''],
|
||||||
features: [{ icon: 'water_drop', title: '', desc: '' }],
|
features: [{ icon: 'water_drop', title: '', desc: '' }],
|
||||||
}}>
|
}}>
|
||||||
<Tabs items={[
|
<Tabs items={[
|
||||||
{ key: 'base', label: '基础信息', children: <BaseInfoFields mode="create" /> },
|
{ key: 'base', label: '基础信息', children: <BaseInfoFields mode="create" form={createForm} /> },
|
||||||
{
|
{
|
||||||
key: 'detail',
|
key: 'detail',
|
||||||
label: '详情页',
|
label: '详情页',
|
||||||
|
|||||||
@@ -593,6 +593,8 @@ model CommonProductItem {
|
|||||||
status ProductStatus @default(DRAFT)
|
status ProductStatus @default(DRAFT)
|
||||||
sortOrder Int @default(0) @map("sort_order")
|
sortOrder Int @default(0) @map("sort_order")
|
||||||
allowOnSitePickup Boolean @default(false) @map("allow_on_site_pickup")
|
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
|
coverResourceId BigInt? @map("cover_resource_id") @db.UnsignedBigInt
|
||||||
detailContent Json? @map("detail_content")
|
detailContent Json? @map("detail_content")
|
||||||
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
|
||||||
@@ -600,11 +602,26 @@ model CommonProductItem {
|
|||||||
|
|
||||||
coverResource CommonResource? @relation("ProductCover", fields: [coverResourceId], references: [id], onDelete: SetNull)
|
coverResource CommonResource? @relation("ProductCover", fields: [coverResourceId], references: [id], onDelete: SetNull)
|
||||||
orders Order[]
|
orders Order[]
|
||||||
|
visibilityPhones CommonProductVisibilityPhone[]
|
||||||
|
|
||||||
@@index([status, aromaType])
|
@@index([status, aromaType])
|
||||||
@@map("common_product_item")
|
@@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 {
|
model CommonProductDetailTemplate {
|
||||||
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
|
||||||
code String @unique @db.VarChar(32)
|
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 { 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')
|
@Controller('catalog')
|
||||||
export class CatalogController {
|
export class CatalogController {
|
||||||
@@ -11,12 +14,25 @@ export class CatalogController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Get('products')
|
@Get('products')
|
||||||
products(@Query('aromaType') aromaType?: string, @Query('cityCode') cityCode?: string) {
|
@UseGuards(OptionalJwtAuthGuard)
|
||||||
return this.catalogService.listProducts(aromaType, cityCode);
|
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')
|
@Get('products/:id')
|
||||||
product(@Param('id') id: string) {
|
@UseGuards(OptionalJwtAuthGuard)
|
||||||
return this.catalogService.getProduct(BigInt(id));
|
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 { Module } from '@nestjs/common';
|
||||||
|
import { IamModule } from '../iam/iam.module';
|
||||||
import { CatalogController } from './catalog.controller';
|
import { CatalogController } from './catalog.controller';
|
||||||
import { CatalogService } from './catalog.service';
|
import { CatalogService } from './catalog.service';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
|
imports: [IamModule],
|
||||||
controllers: [CatalogController],
|
controllers: [CatalogController],
|
||||||
providers: [CatalogService],
|
providers: [CatalogService],
|
||||||
exports: [CatalogService],
|
exports: [CatalogService],
|
||||||
|
|||||||
@@ -3,6 +3,17 @@ import { PrismaService } from '../../common/prisma/prisma.module';
|
|||||||
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
|
||||||
import { groupResourcesByProductId, mapProductMedia } from './catalog.mapper';
|
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()
|
@Injectable()
|
||||||
export class CatalogService {
|
export class CatalogService {
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
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) {
|
if (cityCode) {
|
||||||
const city = await this.prisma.commonCity.findFirst({
|
const city = await this.prisma.commonCity.findFirst({
|
||||||
where: { code: cityCode, status: 'ACTIVE' },
|
where: { code: cityCode, status: 'ACTIVE' },
|
||||||
@@ -45,10 +56,15 @@ export class CatalogService {
|
|||||||
const products = await this.prisma.commonProductItem.findMany({
|
const products = await this.prisma.commonProductItem.findMany({
|
||||||
where: { status: 'ON_SALE', ...(aromaType ? { aromaType: aromaType as never } : {}) },
|
where: { status: 'ON_SALE', ...(aromaType ? { aromaType: aromaType as never } : {}) },
|
||||||
orderBy: { sortOrder: 'asc' },
|
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
|
const resources = productIds.length
|
||||||
? await this.prisma.commonResource.findMany({
|
? await this.prisma.commonResource.findMany({
|
||||||
where: {
|
where: {
|
||||||
@@ -63,10 +79,13 @@ export class CatalogService {
|
|||||||
const resourceMap = groupResourcesByProductId(resources);
|
const resourceMap = groupResourcesByProductId(resources);
|
||||||
|
|
||||||
return serializeBigInt(
|
return serializeBigInt(
|
||||||
products.map((p) => {
|
visible.map((p) => {
|
||||||
const media = mapProductMedia(p, resourceMap.get(p.id.toString()) ?? []);
|
const media = mapProductMedia(p, resourceMap.get(p.id.toString()) ?? []);
|
||||||
|
const { visibilityPhones, ...rest } = p;
|
||||||
return {
|
return {
|
||||||
...p,
|
...rest,
|
||||||
|
visibilityWhitelistEnabled: p.visibilityWhitelistEnabled,
|
||||||
|
visibilityPhones: visibilityPhones.map((row) => row.phone),
|
||||||
benefitAmount: p.benefitAmount ?? p.price,
|
benefitAmount: p.benefitAmount ?? p.price,
|
||||||
price: Number(p.price),
|
price: Number(p.price),
|
||||||
benefitDisplay: Number(p.benefitAmount ?? 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({
|
const product = await this.prisma.commonProductItem.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
include: { coverResource: true },
|
include: {
|
||||||
|
coverResource: true,
|
||||||
|
visibilityPhones: { select: { phone: true } },
|
||||||
|
},
|
||||||
});
|
});
|
||||||
if (!product) return null;
|
if (!product) return null;
|
||||||
|
if (!this.isVisibleToViewer(product, viewer)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
const resources = await this.prisma.commonResource.findMany({
|
const resources = await this.prisma.commonResource.findMany({
|
||||||
where: {
|
where: {
|
||||||
@@ -94,11 +119,51 @@ export class CatalogService {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const media = mapProductMedia(product, resources);
|
const media = mapProductMedia(product, resources);
|
||||||
|
const { visibilityPhones, ...rest } = product;
|
||||||
return serializeBigInt({
|
return serializeBigInt({
|
||||||
...product,
|
...rest,
|
||||||
|
visibilityWhitelistEnabled: product.visibilityWhitelistEnabled,
|
||||||
|
visibilityPhones: visibilityPhones.map((row) => row.phone),
|
||||||
benefitAmount: product.benefitAmount ?? product.price,
|
benefitAmount: product.benefitAmount ?? product.price,
|
||||||
price: Number(product.price),
|
price: Number(product.price),
|
||||||
...media,
|
...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 { AdminProductsQueryDto } from './dto/admin-query.dto';
|
||||||
import type { CreateProductDto, UpdateProductDto } from './dto/admin-mutate.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()
|
@Injectable()
|
||||||
export class AdminProductsService {
|
export class AdminProductsService {
|
||||||
constructor(private readonly prisma: PrismaService) {}
|
constructor(private readonly prisma: PrismaService) {}
|
||||||
@@ -24,7 +42,10 @@ export class AdminProductsService {
|
|||||||
orderBy: { sortOrder: 'asc' },
|
orderBy: { sortOrder: 'asc' },
|
||||||
skip: (page - 1) * pageSize,
|
skip: (page - 1) * pageSize,
|
||||||
take: pageSize,
|
take: pageSize,
|
||||||
include: { coverResource: true },
|
include: {
|
||||||
|
coverResource: true,
|
||||||
|
visibilityPhones: { select: { phone: true }, orderBy: { phone: 'asc' } },
|
||||||
|
},
|
||||||
}),
|
}),
|
||||||
this.prisma.commonProductItem.count({ where }),
|
this.prisma.commonProductItem.count({ where }),
|
||||||
]);
|
]);
|
||||||
@@ -54,7 +75,10 @@ export class AdminProductsService {
|
|||||||
async detail(id: bigint) {
|
async detail(id: bigint) {
|
||||||
const product = await this.prisma.commonProductItem.findUnique({
|
const product = await this.prisma.commonProductItem.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
include: { coverResource: true },
|
include: {
|
||||||
|
coverResource: true,
|
||||||
|
visibilityPhones: { select: { phone: true }, orderBy: { phone: 'asc' } },
|
||||||
|
},
|
||||||
});
|
});
|
||||||
if (!product) throw new NotFoundException('商品不存在');
|
if (!product) throw new NotFoundException('商品不存在');
|
||||||
|
|
||||||
@@ -77,6 +101,9 @@ export class AdminProductsService {
|
|||||||
});
|
});
|
||||||
if (exists) throw new BadRequestException('SKU 或 69 码已存在');
|
if (exists) throw new BadRequestException('SKU 或 69 码已存在');
|
||||||
|
|
||||||
|
const phones = normalizePhones(dto.visibilityPhones);
|
||||||
|
const whitelistEnabled = !!dto.visibilityWhitelistEnabled;
|
||||||
|
|
||||||
const product = await this.prisma.commonProductItem.create({
|
const product = await this.prisma.commonProductItem.create({
|
||||||
data: {
|
data: {
|
||||||
skuCode: dto.skuCode,
|
skuCode: dto.skuCode,
|
||||||
@@ -90,9 +117,17 @@ export class AdminProductsService {
|
|||||||
status: (dto.status ?? 'DRAFT') as 'DRAFT' | 'ON_SALE' | 'OFF_SALE',
|
status: (dto.status ?? 'DRAFT') as 'DRAFT' | 'ON_SALE' | 'OFF_SALE',
|
||||||
sortOrder: dto.sortOrder ?? 0,
|
sortOrder: dto.sortOrder ?? 0,
|
||||||
allowOnSitePickup: dto.allowOnSitePickup ?? false,
|
allowOnSitePickup: dto.allowOnSitePickup ?? false,
|
||||||
|
visibilityWhitelistEnabled: whitelistEnabled,
|
||||||
...(dto.detailContent !== undefined
|
...(dto.detailContent !== undefined
|
||||||
? { detailContent: dto.detailContent as Prisma.InputJsonValue }
|
? { 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.status !== undefined ? { status: dto.status as 'DRAFT' | 'ON_SALE' | 'OFF_SALE' } : {}),
|
||||||
...(dto.sortOrder !== undefined ? { sortOrder: dto.sortOrder } : {}),
|
...(dto.sortOrder !== undefined ? { sortOrder: dto.sortOrder } : {}),
|
||||||
...(dto.allowOnSitePickup !== undefined ? { allowOnSitePickup: dto.allowOnSitePickup } : {}),
|
...(dto.allowOnSitePickup !== undefined ? { allowOnSitePickup: dto.allowOnSitePickup } : {}),
|
||||||
|
...(dto.visibilityWhitelistEnabled !== undefined
|
||||||
|
? { visibilityWhitelistEnabled: !!dto.visibilityWhitelistEnabled }
|
||||||
|
: {}),
|
||||||
...(dto.detailContent !== undefined
|
...(dto.detailContent !== undefined
|
||||||
? { detailContent: dto.detailContent as Prisma.InputJsonValue }
|
? { detailContent: dto.detailContent as Prisma.InputJsonValue }
|
||||||
: {}),
|
: {}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (dto.visibilityPhones !== undefined) {
|
||||||
|
await this.syncVisibilityPhones(id, normalizePhones(dto.visibilityPhones));
|
||||||
|
}
|
||||||
|
|
||||||
if (dto.coverUrl) {
|
if (dto.coverUrl) {
|
||||||
await this.syncCover(id, dto.coverUrl);
|
await this.syncCover(id, dto.coverUrl);
|
||||||
}
|
}
|
||||||
@@ -154,13 +196,30 @@ export class AdminProductsService {
|
|||||||
return { ok: true };
|
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(
|
private formatProduct(
|
||||||
product: Prisma.CommonProductItemGetPayload<{ include: { coverResource: true } }>,
|
product: Prisma.CommonProductItemGetPayload<{
|
||||||
|
include: {
|
||||||
|
coverResource: true;
|
||||||
|
visibilityPhones: { select: { phone: true } };
|
||||||
|
};
|
||||||
|
}>,
|
||||||
extraResources: Prisma.CommonResourceGetPayload<object>[],
|
extraResources: Prisma.CommonResourceGetPayload<object>[],
|
||||||
) {
|
) {
|
||||||
const media = mapProductMedia(product, extraResources);
|
const media = mapProductMedia(product, extraResources);
|
||||||
|
const phones = product.visibilityPhones?.map((row) => row.phone) ?? [];
|
||||||
return {
|
return {
|
||||||
...product,
|
...product,
|
||||||
|
visibilityPhones: phones,
|
||||||
price: Number(product.price),
|
price: Number(product.price),
|
||||||
benefitAmount: Number(product.benefitAmount ?? product.price),
|
benefitAmount: Number(product.benefitAmount ?? product.price),
|
||||||
...media,
|
...media,
|
||||||
|
|||||||
@@ -1110,6 +1110,17 @@ export class CreateProductDto {
|
|||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
allowOnSitePickup?: boolean;
|
allowOnSitePickup?: boolean;
|
||||||
|
|
||||||
|
/** 开启后仅白名单手机号在 C 端可见/可购 */
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
visibilityWhitelistEnabled?: boolean;
|
||||||
|
|
||||||
|
/** 可见白名单手机号列表 */
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
visibilityPhones?: string[];
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
coverUrl?: string;
|
coverUrl?: string;
|
||||||
@@ -1162,6 +1173,17 @@ export class UpdateProductDto {
|
|||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
allowOnSitePickup?: boolean;
|
allowOnSitePickup?: boolean;
|
||||||
|
|
||||||
|
/** 开启后仅白名单手机号在 C 端可见/可购 */
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
visibilityWhitelistEnabled?: boolean;
|
||||||
|
|
||||||
|
/** 可见白名单手机号列表 */
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
visibilityPhones?: string[];
|
||||||
|
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsString()
|
@IsString()
|
||||||
coverUrl?: string;
|
coverUrl?: string;
|
||||||
|
|||||||
@@ -57,7 +57,8 @@ export class TradeService {
|
|||||||
userId: bigint,
|
userId: bigint,
|
||||||
body: { productId: string; quantity: number; addressId?: string; onSitePickup?: boolean },
|
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') {
|
if (!product || product.status !== 'ON_SALE') {
|
||||||
throw new BadRequestException('商品不可购买');
|
throw new BadRequestException('商品不可购买');
|
||||||
}
|
}
|
||||||
@@ -1035,7 +1036,7 @@ export class TradeService {
|
|||||||
async getPartnerProxyOrderOptions(partnerAccountId: bigint) {
|
async getPartnerProxyOrderOptions(partnerAccountId: bigint) {
|
||||||
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
|
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
|
||||||
const [products, promoCodes, stores] = await Promise.all([
|
const [products, promoCodes, stores] = await Promise.all([
|
||||||
this.catalogService.listProducts(),
|
this.catalogService.listProducts(undefined, undefined, { bypassWhitelist: true }),
|
||||||
this.promoCodeService.listActiveOptions(),
|
this.promoCodeService.listActiveOptions(),
|
||||||
this.prisma.store.findMany({
|
this.prisma.store.findMany({
|
||||||
where: { partnerAccountId: primary.id },
|
where: { partnerAccountId: primary.id },
|
||||||
@@ -1083,7 +1084,9 @@ export class TradeService {
|
|||||||
receiverCity?: string;
|
receiverCity?: string;
|
||||||
receiverDistrict?: 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') {
|
if (!product || product.status !== 'ON_SALE') {
|
||||||
throw new BadRequestException('商品不可购买');
|
throw new BadRequestException('商品不可购买');
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user