feat(M03-B): 完成装修广告与媒体管理
This commit is contained in:
@@ -0,0 +1,161 @@
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import type { AuthRepository } from '../auth/auth-repository.js';
|
||||
import { authenticateAccessToken } from '../auth/authenticate.js';
|
||||
import type { AccessProfile } from '../auth/rbac-repository.js';
|
||||
import type { ManagementActor } from '../auth/user-management-repository.js';
|
||||
import { ContentError, type ContentRepository } from '../content/content-repository.js';
|
||||
import { MediaStorage, MediaValidationError } from '../content/media-storage.js';
|
||||
|
||||
const idSchema = z.object({ id: z.string().regex(/^[1-9]\d{0,19}$/) });
|
||||
const storeQuerySchema = z.object({ storeId: z.string().regex(/^[1-9]\d{0,19}$/) });
|
||||
const componentSchema = z.object({
|
||||
type: z.enum(['HERO', 'NOTICE', 'GALLERY', 'CONTACT', 'ROOM_LIST']),
|
||||
props: z.record(z.unknown())
|
||||
});
|
||||
const decorationSchema = z.object({
|
||||
storeId: z.string().regex(/^[1-9]\d{0,19}$/),
|
||||
templateCode: z.string().trim().min(1).max(64),
|
||||
schemaVersion: z.number().int().min(1).max(100),
|
||||
content: z.object({ components: z.array(componentSchema).max(50) })
|
||||
});
|
||||
const adSchema = z.object({
|
||||
scopeType: z.enum(['PLATFORM', 'TENANT', 'STORE']),
|
||||
storeId: z.string().regex(/^[1-9]\d{0,19}$/).nullable().optional(),
|
||||
title: z.string().trim().min(1).max(128),
|
||||
imageAssetId: z.string().regex(/^[1-9]\d{0,19}$/),
|
||||
targetType: z.enum(['NONE', 'PAGE', 'URL']).default('NONE'),
|
||||
targetValue: z.string().trim().max(512).default(''),
|
||||
startsAt: z.coerce.date().nullable().optional(),
|
||||
endsAt: z.coerce.date().nullable().optional(),
|
||||
status: z.enum(['DRAFT', 'ACTIVE', 'INACTIVE']).default('DRAFT'),
|
||||
sortOrder: z.number().int().min(-100000).max(100000).default(0)
|
||||
}).refine((value) => !value.startsAt || !value.endsAt || value.endsAt > value.startsAt);
|
||||
|
||||
export interface ContentRouteOptions {
|
||||
repository: Pick<ContentRepository,
|
||||
'registerAsset' | 'saveDecoration' | 'publishDecoration'
|
||||
| 'listAdvertisements' | 'saveAdvertisement'>;
|
||||
mediaStorage: MediaStorage;
|
||||
authRepository: Pick<AuthRepository, 'validateSession'>;
|
||||
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
|
||||
jwtSecret: string;
|
||||
}
|
||||
|
||||
export async function registerContentRoutes(app: FastifyInstance, options: ContentRouteOptions) {
|
||||
if (!app.hasContentTypeParser('application/octet-stream')) {
|
||||
app.addContentTypeParser(
|
||||
'application/octet-stream',
|
||||
{ parseAs: 'buffer', bodyLimit: 8 * 1024 * 1024 },
|
||||
(_request, body, done) => done(null, body)
|
||||
);
|
||||
}
|
||||
app.post('/admin-api/media/images', async (request, reply) => {
|
||||
const actor = await requireContentManager(request, reply, options);
|
||||
if (!actor) return;
|
||||
const storeIdResult = z.string().regex(/^[1-9]\d{0,19}$/).optional()
|
||||
.safeParse(singleHeader(request.headers['x-store-id']));
|
||||
const originalName = singleHeader(request.headers['x-file-name']);
|
||||
if (!storeIdResult.success || !originalName || !Buffer.isBuffer(request.body)) {
|
||||
return invalid(reply, request.traceId);
|
||||
}
|
||||
const storeId = storeIdResult.data;
|
||||
return handle(reply, request.traceId, async () => {
|
||||
const image = await options.mediaStorage.storeImage({
|
||||
tenantId: actor.tenantId, storeId, originalName,
|
||||
contentType: singleHeader(request.headers['x-image-content-type']) ?? '',
|
||||
body: request.body as Buffer
|
||||
});
|
||||
return reply.status(201).send({
|
||||
code: 0, data: await options.repository.registerAsset(actor, storeId, image),
|
||||
traceId: request.traceId
|
||||
});
|
||||
});
|
||||
});
|
||||
app.post('/admin-api/decorations', async (request, reply) => {
|
||||
const actor = await requireContentManager(request, reply, options);
|
||||
const body = decorationSchema.safeParse(request.body);
|
||||
if (!actor || !body.success) return actor ? invalid(reply, request.traceId) : undefined;
|
||||
return handle(reply, request.traceId, async () => reply.status(201).send({
|
||||
code: 0, data: await options.repository.saveDecoration(actor, body.data),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
app.post('/admin-api/decorations/:id/publish', async (request, reply) => {
|
||||
const actor = await requireContentManager(request, reply, options);
|
||||
const params = idSchema.safeParse(request.params);
|
||||
const query = storeQuerySchema.safeParse(request.query);
|
||||
if (!actor || !params.success || !query.success) {
|
||||
return actor ? invalid(reply, request.traceId) : undefined;
|
||||
}
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.publishDecoration(actor, params.data.id, query.data.storeId),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
app.get('/admin-api/advertisements', async (request, reply) => {
|
||||
const actor = await requireContentManager(request, reply, options);
|
||||
if (!actor) return;
|
||||
return { code: 0, data: await options.repository.listAdvertisements(actor),
|
||||
traceId: request.traceId };
|
||||
});
|
||||
app.post('/admin-api/advertisements', async (request, reply) => {
|
||||
const actor = await requireContentManager(request, reply, options);
|
||||
const body = adSchema.safeParse(request.body);
|
||||
if (!actor || !body.success) return actor ? invalid(reply, request.traceId) : undefined;
|
||||
return handle(reply, request.traceId, async () => reply.status(201).send({
|
||||
code: 0, data: await options.repository.saveAdvertisement(actor, body.data),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function requireContentManager(
|
||||
request: FastifyRequest, reply: FastifyReply, options: ContentRouteOptions
|
||||
): Promise<ManagementActor | null> {
|
||||
const auth = await authenticateAccessToken(
|
||||
request.headers.authorization, options.authRepository, options.jwtSecret
|
||||
);
|
||||
if (!auth) {
|
||||
reply.status(401).send({ code: 'AUTH_SESSION_INVALID', message: 'Authentication required.',
|
||||
traceId: request.traceId });
|
||||
return null;
|
||||
}
|
||||
const access = await options.accessControl.getAccessProfile(
|
||||
auth.session.tenantId, auth.session.user.id
|
||||
);
|
||||
if (!access.capabilities.some((item) =>
|
||||
item === 'store.operation.write' || item === 'tenant.manage'
|
||||
) && !access.roles.includes('PLATFORM_ADMIN')) {
|
||||
reply.status(403).send({ code: 'CONTENT_MANAGEMENT_FORBIDDEN',
|
||||
message: 'Content management permission is required.', traceId: request.traceId });
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
tenantId: auth.session.tenantId, userId: auth.session.user.id, access,
|
||||
traceId: request.traceId, ip: request.ip, userAgent: request.headers['user-agent'] ?? ''
|
||||
};
|
||||
}
|
||||
|
||||
async function handle(reply: FastifyReply, traceId: string, work: () => Promise<unknown>) {
|
||||
try {
|
||||
return await work();
|
||||
} catch (error) {
|
||||
if (!(error instanceof ContentError) && !(error instanceof MediaValidationError)) throw error;
|
||||
const forbidden = error.code.endsWith('_FORBIDDEN');
|
||||
return reply.status(forbidden ? 403 : 400).send({
|
||||
code: error.code, message: 'The content request is invalid or not allowed.', traceId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function singleHeader(value: string | string[] | undefined) {
|
||||
return Array.isArray(value) ? value[0] : value;
|
||||
}
|
||||
|
||||
function invalid(reply: FastifyReply, traceId: string) {
|
||||
return reply.status(400).send({
|
||||
code: 'INVALID_CONTENT_REQUEST', message: 'The content request is invalid.', traceId
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user