feat(ops): v4.0.2 活动图模板、合伙人选择持久化与用户管理主图

HQ 上传底图与码栏;合伙人单选写入 partner_account.activity_poster_id,用户管理下次登录仍显示同一张图。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-08-30 21:36:43 +08:00
parent 0ff61c2cd1
commit 3166467518
39 changed files with 1872 additions and 35 deletions
@@ -0,0 +1,188 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { activityPosterQrSlotPx } from '@dukang/shared-types';
import sharp from 'sharp';
import { PrismaService } from '../../common/prisma/prisma.module';
import { serializeBigInt } from '../../common/decorators/current-user.decorator';
import { PartnerAssocService } from '../store/partner-assoc.service';
import type {
ActivityPosterQueryDto,
UpdateActivityPosterStatusDto,
UpsertActivityPosterDto,
} from './dto/activity-poster.dto';
type PosterRow = {
id: bigint;
title: string;
copyText: string;
imageUrl: string;
qrXPct: Prisma.Decimal;
qrYPct: Prisma.Decimal;
qrSizePct: Prisma.Decimal;
sortOrder: number;
status: string;
createdAt: Date;
updatedAt: Date;
};
@Injectable()
export class ActivityPosterService {
constructor(
private readonly prisma: PrismaService,
private readonly partnerAssoc: PartnerAssocService,
) {}
async adminList(query: ActivityPosterQueryDto) {
const page = query.page ?? 1;
const pageSize = query.pageSize ?? 20;
const where: Prisma.ActivityPosterWhereInput = {};
if (query.status) where.status = query.status;
const [items, total] = await Promise.all([
this.prisma.activityPoster.findMany({
where,
orderBy: [{ sortOrder: 'asc' }, { id: 'desc' }],
skip: (page - 1) * pageSize,
take: pageSize,
}),
this.prisma.activityPoster.count({ where }),
]);
return serializeBigInt({
items: items.map((row) => this.format(row)),
total,
page,
pageSize,
});
}
async adminDetail(id: bigint) {
return serializeBigInt(this.format(await this.require(id)));
}
async create(dto: UpsertActivityPosterDto) {
const row = await this.prisma.activityPoster.create({
data: this.toCreateData(dto),
});
return serializeBigInt(this.format(row));
}
async update(id: bigint, dto: UpsertActivityPosterDto) {
await this.require(id);
const row = await this.prisma.activityPoster.update({
where: { id },
data: this.toCreateData(dto),
});
return serializeBigInt(this.format(row));
}
async updateStatus(id: bigint, dto: UpdateActivityPosterStatusDto) {
await this.require(id);
const row = await this.prisma.activityPoster.update({
where: { id },
data: { status: dto.status },
});
return serializeBigInt(this.format(row));
}
async remove(id: bigint) {
await this.require(id);
await this.prisma.activityPoster.delete({ where: { id } });
return { ok: true };
}
async listForPartner() {
const items = await this.prisma.activityPoster.findMany({
where: { status: 'ACTIVE' },
orderBy: [{ sortOrder: 'asc' }, { id: 'desc' }],
});
return serializeBigInt(items.map((row) => this.format(row)));
}
getSelection(partnerAccountId: bigint) {
return this.partnerAssoc.getSelectedActivityPosterId(partnerAccountId).then((posterId) => ({ posterId }));
}
setSelection(partnerAccountId: bigint, posterId: bigint | null) {
return this.partnerAssoc.setSelectedActivityPoster(partnerAccountId, posterId);
}
async composeForPartner(partnerAccountId: bigint, posterId: bigint) {
const poster = await this.require(posterId);
if (poster.status !== 'ACTIVE') {
throw new NotFoundException('活动图不存在或已下架');
}
let qr: { buffer: Buffer; fileName: string };
try {
qr = await this.partnerAssoc.getQrcodeBuffer(partnerAccountId);
} catch (e) {
if (e instanceof NotFoundException) {
throw new BadRequestException('关联码尚未生成,无法合成活动图');
}
throw e;
}
const template = await this.fetchPngLike(poster.imageUrl, '活动图底图下载失败');
const buffer = await this.compose(template, qr.buffer, poster);
return { buffer, fileName: `activity-poster-${poster.id}.png` };
}
private async compose(template: Buffer, qrPng: Buffer, poster: PosterRow) {
const base = sharp(template);
const meta = await base.metadata();
if (!meta.width || !meta.height) {
throw new BadRequestException('活动图底图无法读取尺寸');
}
const { left, top, size } = activityPosterQrSlotPx(
meta.width,
meta.height,
Number(poster.qrXPct),
Number(poster.qrYPct),
Number(poster.qrSizePct),
);
const qr = await sharp(qrPng).resize(size, size, { fit: 'fill' }).png().toBuffer();
return base.composite([{ input: qr, left, top }]).png().toBuffer();
}
private async fetchPngLike(url: string, failMessage: string) {
const res = await fetch(url);
if (!res.ok) throw new BadRequestException(failMessage);
return Buffer.from(await res.arrayBuffer());
}
private async require(id: bigint) {
const row = await this.prisma.activityPoster.findUnique({ where: { id } });
if (!row) throw new NotFoundException('活动图不存在');
return row;
}
private toCreateData(dto: UpsertActivityPosterDto): Prisma.ActivityPosterCreateInput {
return {
title: dto.title.trim(),
copyText: (dto.copyText ?? '').trim(),
imageUrl: dto.imageUrl.trim(),
qrXPct: new Prisma.Decimal(dto.qrXPct.toFixed(2)),
qrYPct: new Prisma.Decimal(dto.qrYPct.toFixed(2)),
qrSizePct: new Prisma.Decimal(dto.qrSizePct.toFixed(2)),
sortOrder: dto.sortOrder ?? 0,
status: dto.status ?? 'ACTIVE',
};
}
private format(row: PosterRow) {
return {
id: row.id.toString(),
title: row.title,
copyText: row.copyText,
imageUrl: row.imageUrl,
qrXPct: Number(row.qrXPct),
qrYPct: Number(row.qrYPct),
qrSizePct: Number(row.qrSizePct),
sortOrder: row.sortOrder,
status: row.status,
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
}
}
@@ -0,0 +1,71 @@
import { Body, Controller, Delete, Get, Param, Post, Put, Query, UseGuards } from '@nestjs/common';
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
import { HqPermissionGuard, RequireHqPermissions } from '../../common/guards/hq-permission.guard';
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
import { ActivityPosterService } from './activity-poster.service';
import {
ActivityPosterQueryDto,
UpdateActivityPosterStatusDto,
UpsertActivityPosterDto,
} from './dto/activity-poster.dto';
@Controller('admin/activity-posters')
@UseGuards(HqAuthGuard, HqPermissionGuard)
@RequireHqPermissions('activity_posters')
export class AdminActivityPostersController {
constructor(private readonly service: ActivityPosterService) {}
@Get()
list(@Query() query: ActivityPosterQueryDto) {
return this.service.adminList(query);
}
@Get(':id')
detail(@Param('id') id: string) {
return this.service.adminDetail(BigInt(id));
}
@Post()
@HqOperation({
action: HqOperationAction.ACTIVITY_POSTER_CREATE,
refType: 'ACTIVITY_POSTER',
refIdField: 'id',
includeBody: true,
})
create(@Body() dto: UpsertActivityPosterDto) {
return this.service.create(dto);
}
@Put(':id')
@HqOperation({
action: HqOperationAction.ACTIVITY_POSTER_UPDATE,
refType: 'ACTIVITY_POSTER',
refIdParam: 'id',
includeBody: true,
})
update(@Param('id') id: string, @Body() dto: UpsertActivityPosterDto) {
return this.service.update(BigInt(id), dto);
}
@Put(':id/status')
@HqOperation({
action: HqOperationAction.ACTIVITY_POSTER_UPDATE_STATUS,
refType: 'ACTIVITY_POSTER',
refIdParam: 'id',
includeBody: true,
})
updateStatus(@Param('id') id: string, @Body() dto: UpdateActivityPosterStatusDto) {
return this.service.updateStatus(BigInt(id), dto);
}
@Delete(':id')
@HqOperation({
action: HqOperationAction.ACTIVITY_POSTER_DELETE,
refType: 'ACTIVITY_POSTER',
refIdParam: 'id',
})
remove(@Param('id') id: string) {
return this.service.remove(BigInt(id));
}
}
@@ -0,0 +1,78 @@
import { Type } from 'class-transformer';
import {
IsIn,
IsInt,
IsNumber,
IsOptional,
IsString,
Max,
MaxLength,
Min,
MinLength,
ValidateIf,
} from 'class-validator';
import { ACTIVITY_POSTER_STATUSES } from '@dukang/shared-types';
import { PaginationQueryDto } from './admin-query.dto';
export class ActivityPosterQueryDto extends PaginationQueryDto {
@IsOptional()
@IsIn([...ACTIVITY_POSTER_STATUSES])
status?: string;
}
export class UpsertActivityPosterDto {
@IsString()
@MinLength(1)
@MaxLength(128)
title!: string;
@IsOptional()
@IsString()
@MaxLength(4000)
copyText?: string;
@IsString()
@MinLength(1)
@MaxLength(512)
imageUrl!: string;
@Type(() => Number)
@IsNumber()
@Min(0)
@Max(100)
qrXPct!: number;
@Type(() => Number)
@IsNumber()
@Min(0)
@Max(100)
qrYPct!: number;
@Type(() => Number)
@IsNumber()
@Min(5)
@Max(50)
qrSizePct!: number;
@IsOptional()
@Type(() => Number)
@IsInt()
@Min(0)
sortOrder?: number;
@IsOptional()
@IsIn([...ACTIVITY_POSTER_STATUSES])
status?: string;
}
export class UpdateActivityPosterStatusDto {
@IsIn([...ACTIVITY_POSTER_STATUSES])
status!: string;
}
export class ActivityPosterSelectionDto {
@IsOptional()
@ValidateIf((_, value) => value != null)
@IsString()
posterId?: string | null;
}
@@ -82,6 +82,9 @@ import { AdminFulfillmentProvidersController } from './admin-fulfillment-provide
import { AdminDomainEventsController } from './admin-domain-events.controller';
import { AdminDomainEventsService } from './admin-domain-events.service';
import { AdminTestWhitelistController } from './admin-test-whitelist.controller';
import { ActivityPosterService } from './activity-poster.service';
import { AdminActivityPostersController } from './admin-activity-posters.controller';
import { PartnerActivityPostersController } from './partner-activity-posters.controller';
@Module({
imports: [CityScopeModule, IamModule, TradeModule, AnalyticsModule, FulfillmentModule, BenefitModule, CommonModule, IntegrationsModule, WecomModule, LlmModule, RedeemModule, StoreModule, DevPlanModule],
@@ -132,6 +135,8 @@ import { AdminTestWhitelistController } from './admin-test-whitelist.controller'
AdminDevPlanController,
AdminFulfillmentProvidersController,
AdminTestWhitelistController,
AdminActivityPostersController,
PartnerActivityPostersController,
],
providers: [
AdminDashboardService,
@@ -165,6 +170,7 @@ import { AdminTestWhitelistController } from './admin-test-whitelist.controller'
AdminLlmConfigsService,
AdminKnowledgeBasesService,
SuperAdminGuard,
ActivityPosterService,
],
exports: [CityScopeModule],
})
@@ -0,0 +1,38 @@
import { Body, Controller, Get, Param, Put, Res, UseGuards } from '@nestjs/common';
import type { Response } from 'express';
import { JwtAuthGuard, AuthUser } from '../../common/guards/jwt-auth.guard';
import { PartnerPrimaryGuard } from '../../common/guards/partner-primary.guard';
import { CurrentUser } from '../../common/decorators/current-user.decorator';
import { ActivityPosterService } from './activity-poster.service';
import { ActivityPosterSelectionDto } from './dto/activity-poster.dto';
@Controller('partner/activity-posters')
@UseGuards(JwtAuthGuard, PartnerPrimaryGuard)
export class PartnerActivityPostersController {
constructor(private readonly service: ActivityPosterService) {}
@Get()
list() {
return this.service.listForPartner();
}
@Get('selection')
getSelection(@CurrentUser() user: AuthUser) {
return this.service.getSelection(user.actorId);
}
@Put('selection')
setSelection(@CurrentUser() user: AuthUser, @Body() dto: ActivityPosterSelectionDto) {
const raw = dto.posterId?.trim();
const posterId = raw && /^\d+$/.test(raw) ? BigInt(raw) : null;
return this.service.setSelection(user.actorId, posterId);
}
@Get(':id/image')
async image(@CurrentUser() user: AuthUser, @Param('id') id: string, @Res() res: Response) {
const { buffer, fileName } = await this.service.composeForPartner(user.actorId, BigInt(id));
res.setHeader('Content-Type', 'image/png');
res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
res.send(buffer);
}
}