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
+1 -1
View File
@@ -17,7 +17,7 @@
| **benefit** | BenefitCoupon | jacy-dukang |
| **redeem** | RedeemRecord, StoreRating | 刘景尧 |
| **settlement** | StorePayout, PartnerBill | jacy-dukang |
| **ops** | 只读聚合 | jacy-dukang |
| **ops** | 只读聚合、ActivityPoster | jacy-dukang |
| **analytics** | LogUserAnalytics | jacy-dukang |
| **common** | CommonResource, CommonEvent, CommonTicket | jacy-dukang |
| **integrations** | 无表 | jacy-dukang |
+2 -1
View File
@@ -54,7 +54,8 @@
"pdfkit": "^0.19.1",
"qrcode": "^1.5.4",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1"
"rxjs": "^7.8.1",
"sharp": "^0.34.5"
},
"devDependencies": {
"@nestjs/cli": "^10.4.0",
@@ -0,0 +1,37 @@
-- v4.0.2:活动图模板(底图 + 方形码栏 + 文案)
ALTER TABLE `common_resource`
MODIFY COLUMN `biz_type` ENUM(
'COVER',
'ENV',
'CONTRACT',
'CAROUSEL',
'DETAIL',
'AVATAR',
'QRCODE',
'SIGN_PHOTO',
'VIDEO',
'REDEEM_PENDING_PHOTO',
'ACTIVITY_POSTER'
) NOT NULL;
CREATE TABLE IF NOT EXISTS `activity_poster` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`title` VARCHAR(128) NOT NULL,
`copy_text` TEXT NOT NULL,
`image_url` VARCHAR(512) NOT NULL,
`qr_x_pct` DECIMAL(5,2) NOT NULL,
`qr_y_pct` DECIMAL(5,2) NOT NULL,
`qr_size_pct` DECIMAL(5,2) NOT NULL,
`sort_order` INT NOT NULL DEFAULT 0,
`status` VARCHAR(16) NOT NULL DEFAULT 'ACTIVE',
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
`updated_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
PRIMARY KEY (`id`),
KEY `idx_activity_poster_status_sort` (`status`, `sort_order`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='HQ 活动图模板';
INSERT IGNORE INTO `hq_role_permission` (`admin_role`, `permission_key`)
SELECT 'OPS', 'activity_posters'
FROM DUAL
WHERE EXISTS (SELECT 1 FROM `hq_role_permission` WHERE `admin_role` = 'OPS');
@@ -0,0 +1,9 @@
-- v4.0.2:主合伙人记住所选活动图(空=仅二维码)
ALTER TABLE `partner_account`
ADD COLUMN `activity_poster_id` BIGINT UNSIGNED DEFAULT NULL AFTER `assoc_qrcode_resource_id`,
ADD KEY `idx_partner_account_activity_poster` (`activity_poster_id`);
ALTER TABLE `partner_account`
ADD CONSTRAINT `fk_partner_account_activity_poster`
FOREIGN KEY (`activity_poster_id`) REFERENCES `activity_poster`(`id`) ON DELETE SET NULL;
+24
View File
@@ -44,6 +44,7 @@ enum ResourceBizType {
SIGN_PHOTO
VIDEO
REDEEM_PENDING_PHOTO
ACTIVITY_POSTER
}
enum RedeemPendingStatus {
@@ -1204,6 +1205,7 @@ model PartnerAccount {
managedWarehouseId BigInt? @unique @map("managed_warehouse_id") @db.UnsignedBigInt
assocQrcodeId String? @unique @map("assoc_qrcode_id") @db.VarChar(64)
assocQrcodeResourceId BigInt? @map("assoc_qrcode_resource_id") @db.UnsignedBigInt
activityPosterId BigInt? @map("activity_poster_id") @db.UnsignedBigInt
/// 测试合伙人账号
isTest Boolean @default(false) @map("is_test")
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
@@ -1219,6 +1221,7 @@ model PartnerAccount {
assocUsers User[] @relation("UserPartnerAssoc")
userNotes PartnerUserNote[]
assocQrcodeResource CommonResource? @relation("PartnerAssocQrcode", fields: [assocQrcodeResourceId], references: [id], onDelete: SetNull)
activityPoster ActivityPoster? @relation(fields: [activityPosterId], references: [id], onDelete: SetNull)
@@index([cityId, scopeType])
@@index([cityId, isPrimary])
@@ -1226,6 +1229,7 @@ model PartnerAccount {
@@index([wxOpenId])
@@index([contactPhone])
@@index([isTest])
@@index([activityPosterId])
@@map("partner_account")
}
@@ -1246,6 +1250,26 @@ model PartnerUserNote {
@@map("partner_user_note")
}
/// HQ 活动图模板:底图 + 方形码栏(相对百分比)+ 文案
model ActivityPoster {
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
title String @db.VarChar(128)
copyText String @map("copy_text") @db.Text
imageUrl String @map("image_url") @db.VarChar(512)
qrXPct Decimal @map("qr_x_pct") @db.Decimal(5, 2)
qrYPct Decimal @map("qr_y_pct") @db.Decimal(5, 2)
qrSizePct Decimal @map("qr_size_pct") @db.Decimal(5, 2)
sortOrder Int @default(0) @map("sort_order")
status String @default("ACTIVE") @db.VarChar(16)
createdAt DateTime @default(now()) @map("created_at") @db.DateTime(3)
updatedAt DateTime @updatedAt @map("updated_at") @db.DateTime(3)
selectedByPartners PartnerAccount[]
@@index([status, sortOrder])
@@map("activity_poster")
}
model PartnerBill {
id BigInt @id @default(autoincrement()) @db.UnsignedBigInt
billNo String @unique @map("bill_no") @db.VarChar(32)
@@ -122,6 +122,10 @@ export const HqOperationAction = {
DEV_PLAN_DISPATCH_TEST: 'DEV_PLAN_DISPATCH_TEST',
SUPPORT_TICKET_REVIEW: 'SUPPORT_TICKET_REVIEW',
SUPPORT_TICKET_BATCH_REVIEW: 'SUPPORT_TICKET_BATCH_REVIEW',
ACTIVITY_POSTER_CREATE: 'ACTIVITY_POSTER_CREATE',
ACTIVITY_POSTER_UPDATE: 'ACTIVITY_POSTER_UPDATE',
ACTIVITY_POSTER_UPDATE_STATUS: 'ACTIVITY_POSTER_UPDATE_STATUS',
ACTIVITY_POSTER_DELETE: 'ACTIVITY_POSTER_DELETE',
} as const;
export type HqOperationActionCode = (typeof HqOperationAction)[keyof typeof HqOperationAction];
@@ -249,6 +253,10 @@ export const HQ_OPERATION_ACTION_LABELS: Record<string, string> = {
[HqOperationAction.DEV_PLAN_DISPATCH_TEST]: '测试任务派发助手',
[HqOperationAction.SUPPORT_TICKET_REVIEW]: '技术支持工单审批',
[HqOperationAction.SUPPORT_TICKET_BATCH_REVIEW]: '技术支持批量审批',
[HqOperationAction.ACTIVITY_POSTER_CREATE]: '新增活动图',
[HqOperationAction.ACTIVITY_POSTER_UPDATE]: '编辑活动图',
[HqOperationAction.ACTIVITY_POSTER_UPDATE_STATUS]: '活动图上下架',
[HqOperationAction.ACTIVITY_POSTER_DELETE]: '删除活动图',
STORE_PAYOUT: '门店打款确认',
};
@@ -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);
}
}
@@ -136,15 +136,51 @@ export class PartnerAssocService {
const userCount = await this.prisma.user.count({
where: { assocPartnerAccountId: primary.id },
});
const selectedPoster = primary.activityPosterId
? await this.prisma.activityPoster.findUnique({
where: { id: primary.activityPosterId },
select: { id: true, status: true },
})
: null;
const activityPosterId =
selectedPoster?.status === 'ACTIVE' ? selectedPoster.id.toString() : null;
return {
partnerId: primary.id.toString(),
qrcodeUrl: ensured.qrcodeUrl,
userCount,
companyName: primary.companyName,
name: primary.name,
activityPosterId,
};
}
async getSelectedActivityPosterId(partnerAccountId: bigint): Promise<string | null> {
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
if (!primary.activityPosterId) return null;
const poster = await this.prisma.activityPoster.findUnique({
where: { id: primary.activityPosterId },
select: { id: true, status: true },
});
return poster?.status === 'ACTIVE' ? poster.id.toString() : null;
}
async setSelectedActivityPoster(partnerAccountId: bigint, posterId: bigint | null) {
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
if (posterId) {
const poster = await this.prisma.activityPoster.findFirst({
where: { id: posterId, status: 'ACTIVE' },
select: { id: true },
});
if (!poster) throw new BadRequestException('活动图不存在或已下架');
}
await this.prisma.partnerAccount.update({
where: { id: primary.id },
data: { activityPosterId: posterId },
});
return { posterId: posterId?.toString() ?? null };
}
async getStats(partnerAccountId: bigint) {
const primary = await this.partnerCityService.resolvePrimaryAccount(partnerAccountId);
const { todayStart, monthStart } = dayBounds();