feat(M03-B): 完成装修广告与媒体管理
This commit is contained in:
@@ -17,6 +17,10 @@ import {
|
||||
registerStoreRoomRoutes,
|
||||
type StoreRoomRouteOptions
|
||||
} from './routes/store-room-management.js';
|
||||
import {
|
||||
registerContentRoutes,
|
||||
type ContentRouteOptions
|
||||
} from './routes/content-management.js';
|
||||
|
||||
export interface BuildAppOptions {
|
||||
config?: AppConfig;
|
||||
@@ -24,6 +28,7 @@ export interface BuildAppOptions {
|
||||
auth?: AuthRouteOptions;
|
||||
userManagement?: UserManagementRouteOptions;
|
||||
storeRoom?: StoreRoomRouteOptions;
|
||||
content?: ContentRouteOptions;
|
||||
}
|
||||
|
||||
declare module 'fastify' {
|
||||
@@ -78,6 +83,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
||||
if (options.storeRoom) {
|
||||
await registerStoreRoomRoutes(app, options.storeRoom);
|
||||
}
|
||||
if (options.content) {
|
||||
await registerContentRoutes(app, options.content);
|
||||
}
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
import type { PoolConnection, ResultSetHeader, RowDataPacket } from 'mysql2/promise';
|
||||
import type { ManagementActor } from '../auth/user-management-repository.js';
|
||||
import type { MySqlPool } from '../db/mysql.js';
|
||||
import type { StoredImage } from './media-storage.js';
|
||||
|
||||
export interface DecorationInput {
|
||||
storeId: string;
|
||||
templateCode: string;
|
||||
schemaVersion: number;
|
||||
content: {
|
||||
components: Array<{
|
||||
type: 'HERO' | 'NOTICE' | 'GALLERY' | 'CONTACT' | 'ROOM_LIST';
|
||||
props: Record<string, unknown>;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AdvertisementInput {
|
||||
scopeType: 'PLATFORM' | 'TENANT' | 'STORE';
|
||||
storeId?: string | null;
|
||||
title: string;
|
||||
imageAssetId: string;
|
||||
targetType: 'NONE' | 'PAGE' | 'URL';
|
||||
targetValue: string;
|
||||
startsAt?: Date | null;
|
||||
endsAt?: Date | null;
|
||||
status: 'DRAFT' | 'ACTIVE' | 'INACTIVE';
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
interface IdRow extends RowDataPacket { id: string }
|
||||
interface VersionRow extends RowDataPacket { nextVersion: number }
|
||||
interface ContentRow extends RowDataPacket {
|
||||
id: string; scopeType: string; storeId: string | null; title: string; imageUrl: string;
|
||||
targetType: string; targetValue: string; startsAt: Date | null; endsAt: Date | null;
|
||||
status: string; sortOrder: number;
|
||||
}
|
||||
|
||||
export class ContentError extends Error {
|
||||
constructor(public readonly code: string) { super(code); }
|
||||
}
|
||||
|
||||
export class ContentRepository {
|
||||
constructor(private readonly pool: MySqlPool) {}
|
||||
|
||||
async registerAsset(actor: ManagementActor, storeId: string | undefined, image: StoredImage) {
|
||||
if (storeId) this.assertStoreScope(actor, storeId);
|
||||
return this.transaction(async (connection) => {
|
||||
const [result] = await connection.execute<ResultSetHeader>(
|
||||
`INSERT INTO qipai_media_assets
|
||||
(tenant_id, store_id, storage_path, public_url, mime_type, byte_size,
|
||||
width, height, checksum_sha256, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)`,
|
||||
[actor.tenantId, storeId ?? null, image.storagePath, image.publicUrl, image.mimeType,
|
||||
image.byteSize, image.width, image.height, image.checksumSha256, actor.userId]
|
||||
);
|
||||
const assetId = String(result.insertId);
|
||||
await this.audit(connection, actor, 'MEDIA_ASSET_REGISTERED', 'MEDIA_ASSET', assetId);
|
||||
return { assetId, url: image.publicUrl };
|
||||
});
|
||||
}
|
||||
|
||||
async saveDecoration(actor: ManagementActor, input: DecorationInput) {
|
||||
this.assertStoreScope(actor, input.storeId);
|
||||
return this.transaction(async (connection) => {
|
||||
await this.lockStore(connection, actor.tenantId, input.storeId);
|
||||
const [versions] = await connection.execute<VersionRow[]>(
|
||||
`SELECT COALESCE(MAX(version), 0) + 1 AS nextVersion
|
||||
FROM qipai_store_decorations
|
||||
WHERE tenant_id = ? AND store_id = ? FOR UPDATE`,
|
||||
[actor.tenantId, input.storeId]
|
||||
);
|
||||
const version = Number(versions[0]?.nextVersion ?? 1);
|
||||
const [result] = await connection.execute<ResultSetHeader>(
|
||||
`INSERT INTO qipai_store_decorations
|
||||
(tenant_id, store_id, template_code, schema_version, content_json,
|
||||
status, version, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, 'DRAFT', ?, ?)`,
|
||||
[actor.tenantId, input.storeId, input.templateCode, input.schemaVersion,
|
||||
JSON.stringify(input.content), version, actor.userId]
|
||||
);
|
||||
await this.audit(connection, actor, 'DECORATION_DRAFT_CREATED', 'DECORATION', String(result.insertId));
|
||||
return { decorationId: String(result.insertId), version };
|
||||
});
|
||||
}
|
||||
|
||||
async publishDecoration(actor: ManagementActor, decorationId: string, storeId: string) {
|
||||
this.assertStoreScope(actor, storeId);
|
||||
return this.transaction(async (connection) => {
|
||||
const [rows] = await connection.execute<IdRow[]>(
|
||||
`SELECT id FROM qipai_store_decorations
|
||||
WHERE tenant_id = ? AND store_id = ? AND id = ? AND deleted_at IS NULL FOR UPDATE`,
|
||||
[actor.tenantId, storeId, decorationId]
|
||||
);
|
||||
if (!rows[0]) throw new ContentError('DECORATION_NOT_FOUND');
|
||||
await connection.execute(
|
||||
`UPDATE qipai_store_decorations SET status = 'ARCHIVED'
|
||||
WHERE tenant_id = ? AND store_id = ? AND status = 'PUBLISHED'`,
|
||||
[actor.tenantId, storeId]
|
||||
);
|
||||
await connection.execute(
|
||||
`UPDATE qipai_store_decorations SET status = 'PUBLISHED',
|
||||
published_at = UTC_TIMESTAMP(3)
|
||||
WHERE tenant_id = ? AND store_id = ? AND id = ?`,
|
||||
[actor.tenantId, storeId, decorationId]
|
||||
);
|
||||
await this.audit(connection, actor, 'DECORATION_PUBLISHED', 'DECORATION', decorationId);
|
||||
return { decorationId, published: true };
|
||||
});
|
||||
}
|
||||
|
||||
async listAdvertisements(actor: ManagementActor) {
|
||||
const scope = this.adScope(actor);
|
||||
const [rows] = await this.pool.execute<ContentRow[]>(
|
||||
`SELECT a.id, a.scope_type AS scopeType, a.store_id AS storeId, a.title,
|
||||
m.public_url AS imageUrl, a.target_type AS targetType,
|
||||
a.target_value AS targetValue, a.starts_at AS startsAt, a.ends_at AS endsAt,
|
||||
a.status, a.sort_order AS sortOrder
|
||||
FROM qipai_advertisements a
|
||||
INNER JOIN qipai_media_assets m ON m.id = a.image_asset_id AND m.tenant_id = a.tenant_id
|
||||
WHERE a.tenant_id = ? AND a.deleted_at IS NULL AND ${scope.sql}
|
||||
ORDER BY a.sort_order, a.id DESC`,
|
||||
[actor.tenantId, ...scope.params]
|
||||
);
|
||||
return rows.map((row) => ({ ...row, id: String(row.id), storeId: row.storeId && String(row.storeId) }));
|
||||
}
|
||||
|
||||
async saveAdvertisement(actor: ManagementActor, input: AdvertisementInput) {
|
||||
this.assertAdScope(actor, input);
|
||||
return this.transaction(async (connection) => {
|
||||
const [result] = await connection.execute<ResultSetHeader>(
|
||||
`INSERT INTO qipai_advertisements
|
||||
(tenant_id, scope_type, store_id, title, image_asset_id, target_type,
|
||||
target_value, starts_at, ends_at, status, sort_order, created_by)
|
||||
SELECT ?, ?, ?, ?, m.id, ?, ?, ?, ?, ?, ?, ?
|
||||
FROM qipai_media_assets m
|
||||
WHERE m.tenant_id = ? AND m.id = ? AND m.deleted_at IS NULL`,
|
||||
[actor.tenantId, input.scopeType, input.storeId ?? null, input.title,
|
||||
input.targetType, input.targetValue, input.startsAt ?? null, input.endsAt ?? null,
|
||||
input.status, input.sortOrder, actor.userId, actor.tenantId, input.imageAssetId]
|
||||
);
|
||||
if (result.affectedRows !== 1) throw new ContentError('IMAGE_ASSET_NOT_FOUND');
|
||||
const advertisementId = String(result.insertId);
|
||||
await this.audit(connection, actor, 'ADVERTISEMENT_CREATED', 'ADVERTISEMENT', advertisementId);
|
||||
return { advertisementId };
|
||||
});
|
||||
}
|
||||
|
||||
private assertAdScope(actor: ManagementActor, input: AdvertisementInput) {
|
||||
const tenantManager = actor.access.capabilities.includes('tenant.manage')
|
||||
|| actor.access.roles.includes('PLATFORM_ADMIN');
|
||||
if (input.scopeType === 'PLATFORM' && !actor.access.roles.includes('PLATFORM_ADMIN')) {
|
||||
throw new ContentError('PLATFORM_AD_FORBIDDEN');
|
||||
}
|
||||
if (input.scopeType === 'TENANT' && !tenantManager) throw new ContentError('TENANT_AD_FORBIDDEN');
|
||||
if (input.scopeType === 'STORE') {
|
||||
if (!input.storeId) throw new ContentError('STORE_REQUIRED');
|
||||
this.assertStoreScope(actor, input.storeId);
|
||||
}
|
||||
}
|
||||
|
||||
private assertStoreScope(actor: ManagementActor, storeId: string) {
|
||||
if (actor.access.capabilities.includes('tenant.manage')
|
||||
|| actor.access.roles.includes('PLATFORM_ADMIN')) return;
|
||||
if (!actor.access.capabilities.includes('store.operation.write')
|
||||
|| !actor.access.storeIds.includes(storeId)) {
|
||||
throw new ContentError('STORE_SCOPE_FORBIDDEN');
|
||||
}
|
||||
}
|
||||
|
||||
private adScope(actor: ManagementActor) {
|
||||
if (actor.access.capabilities.includes('tenant.manage')
|
||||
|| actor.access.roles.includes('PLATFORM_ADMIN')) return { sql: '1 = 1', params: [] as string[] };
|
||||
if (actor.access.storeIds.length === 0) return { sql: "a.scope_type = 'TENANT'", params: [] as string[] };
|
||||
return {
|
||||
sql: `(a.scope_type = 'TENANT' OR (a.scope_type = 'STORE'
|
||||
AND a.store_id IN (${actor.access.storeIds.map(() => '?').join(',')})))`,
|
||||
params: actor.access.storeIds
|
||||
};
|
||||
}
|
||||
|
||||
private async lockStore(connection: PoolConnection, tenantId: string, storeId: string) {
|
||||
const [rows] = await connection.execute<IdRow[]>(
|
||||
`SELECT id FROM qipai_stores
|
||||
WHERE tenant_id = ? AND id = ? AND deleted_at IS NULL FOR UPDATE`,
|
||||
[tenantId, storeId]
|
||||
);
|
||||
if (!rows[0]) throw new ContentError('STORE_NOT_FOUND');
|
||||
}
|
||||
|
||||
private async audit(
|
||||
connection: PoolConnection, actor: ManagementActor,
|
||||
action: string, resourceType: string, resourceId: string
|
||||
) {
|
||||
await connection.execute(
|
||||
`INSERT INTO qipai_audit_logs
|
||||
(tenant_id, actor_type, actor_id, action, resource_type, resource_id,
|
||||
trace_id, ip, user_agent, metadata)
|
||||
VALUES (?, 'USER', ?, ?, ?, ?, ?, ?, ?, JSON_OBJECT())`,
|
||||
[actor.tenantId, actor.userId, action, resourceType, resourceId,
|
||||
actor.traceId, actor.ip, actor.userAgent.slice(0, 255)]
|
||||
);
|
||||
}
|
||||
|
||||
private async transaction<T>(work: (connection: PoolConnection) => Promise<T>) {
|
||||
const connection = await this.pool.getConnection();
|
||||
try {
|
||||
await connection.beginTransaction();
|
||||
const result = await work(connection);
|
||||
await connection.commit();
|
||||
return result;
|
||||
} catch (error) {
|
||||
await connection.rollback();
|
||||
throw error;
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { extname, resolve, sep } from 'node:path';
|
||||
import sharp from 'sharp';
|
||||
|
||||
export interface StoredImage {
|
||||
storagePath: string;
|
||||
publicUrl: string;
|
||||
mimeType: 'image/webp';
|
||||
byteSize: number;
|
||||
width: number;
|
||||
height: number;
|
||||
checksumSha256: string;
|
||||
}
|
||||
|
||||
export class MediaValidationError extends Error {
|
||||
constructor(public readonly code: string) { super(code); }
|
||||
}
|
||||
|
||||
export class MediaStorage {
|
||||
constructor(
|
||||
private readonly root: string,
|
||||
private readonly publicBaseUrl = 'https://api.txyundm.cn/uploads'
|
||||
) {}
|
||||
|
||||
async storeImage(input: {
|
||||
tenantId: string;
|
||||
storeId?: string;
|
||||
originalName: string;
|
||||
contentType: string;
|
||||
body: Buffer;
|
||||
}): Promise<StoredImage> {
|
||||
if (input.body.length === 0 || input.body.length > 8 * 1024 * 1024) {
|
||||
throw new MediaValidationError('IMAGE_SIZE_INVALID');
|
||||
}
|
||||
if (!['image/jpeg', 'image/png', 'image/webp'].includes(input.contentType)) {
|
||||
throw new MediaValidationError('IMAGE_TYPE_INVALID');
|
||||
}
|
||||
if (!['.jpg', '.jpeg', '.png', '.webp'].includes(extname(input.originalName).toLowerCase())) {
|
||||
throw new MediaValidationError('IMAGE_EXTENSION_INVALID');
|
||||
}
|
||||
let result: Buffer;
|
||||
let metadata: sharp.Metadata;
|
||||
try {
|
||||
const source = sharp(input.body, { failOn: 'warning', limitInputPixels: 40_000_000 });
|
||||
metadata = await source.metadata();
|
||||
if (!metadata.width || !metadata.height) throw new Error('missing dimensions');
|
||||
result = await source
|
||||
.rotate()
|
||||
.resize({ width: 1920, height: 1920, fit: 'inside', withoutEnlargement: true })
|
||||
.webp({ quality: 82 })
|
||||
.toBuffer();
|
||||
} catch {
|
||||
throw new MediaValidationError('IMAGE_DECODE_FAILED');
|
||||
}
|
||||
const outputMetadata = await sharp(result).metadata();
|
||||
const relativeDirectory = ['tenants', input.tenantId, input.storeId ? `stores/${input.storeId}` : 'shared'];
|
||||
const directory = resolve(this.root, ...relativeDirectory);
|
||||
const safeRoot = resolve(this.root);
|
||||
if (directory !== safeRoot && !directory.startsWith(`${safeRoot}${sep}`)) {
|
||||
throw new MediaValidationError('IMAGE_PATH_INVALID');
|
||||
}
|
||||
await mkdir(directory, { recursive: true });
|
||||
const fileName = `${randomUUID()}.webp`;
|
||||
await writeFile(resolve(directory, fileName), result, { flag: 'wx' });
|
||||
const urlPath = [...relativeDirectory, fileName].join('/');
|
||||
return {
|
||||
storagePath: urlPath,
|
||||
publicUrl: `${this.publicBaseUrl}/${urlPath}`,
|
||||
mimeType: 'image/webp',
|
||||
byteSize: result.length,
|
||||
width: outputMetadata.width ?? metadata.width ?? 0,
|
||||
height: outputMetadata.height ?? metadata.height ?? 0,
|
||||
checksumSha256: createHash('sha256').update(result).digest('hex')
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,8 @@ const migrationFiles: Record<MigrationDirection, readonly string[]> = {
|
||||
'database/migrations/2026061804_m02b_wechat_auth.up.sql',
|
||||
'database/migrations/2026061805_m02c_rbac.up.sql',
|
||||
'database/migrations/2026061806_m02d_user_management.up.sql',
|
||||
'database/migrations/2026061807_m03a_store_room_domain.up.sql'
|
||||
'database/migrations/2026061807_m03a_store_room_domain.up.sql',
|
||||
'database/migrations/2026061808_m03b_decoration_ads_media.up.sql'
|
||||
],
|
||||
verify: [
|
||||
'database/migrations/2026061601_m01b_core_schema.verify.sql',
|
||||
@@ -36,9 +37,11 @@ const migrationFiles: Record<MigrationDirection, readonly string[]> = {
|
||||
'database/migrations/2026061804_m02b_wechat_auth.verify.sql',
|
||||
'database/migrations/2026061805_m02c_rbac.verify.sql',
|
||||
'database/migrations/2026061806_m02d_user_management.verify.sql',
|
||||
'database/migrations/2026061807_m03a_store_room_domain.verify.sql'
|
||||
'database/migrations/2026061807_m03a_store_room_domain.verify.sql',
|
||||
'database/migrations/2026061808_m03b_decoration_ads_media.verify.sql'
|
||||
],
|
||||
down: [
|
||||
'database/migrations/2026061808_m03b_decoration_ads_media.down.sql',
|
||||
'database/migrations/2026061807_m03a_store_room_domain.down.sql',
|
||||
'database/migrations/2026061806_m02d_user_management.down.sql',
|
||||
'database/migrations/2026061805_m02c_rbac.down.sql',
|
||||
@@ -168,7 +171,8 @@ export async function executeMigrationPlan(
|
||||
3, 7, 1,
|
||||
5, 3, 7, 1,
|
||||
1, 3, 1,
|
||||
3, 6, 13, 1
|
||||
3, 6, 13, 1,
|
||||
3, 3, 1
|
||||
][index] ?? 1;
|
||||
if (!Array.isArray(result) || result.length < minimumRows) {
|
||||
throw new Error(
|
||||
|
||||
@@ -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
|
||||
});
|
||||
}
|
||||
@@ -7,6 +7,9 @@ import { RbacRepository } from './auth/rbac-repository.js';
|
||||
import { parseWechatAppSecrets, WechatHttpClient } from './auth/wechat-client.js';
|
||||
import { UserManagementRepository } from './auth/user-management-repository.js';
|
||||
import { StoreRoomRepository } from './stores/store-room-repository.js';
|
||||
import { ContentRepository } from './content/content-repository.js';
|
||||
import { MediaStorage } from './content/media-storage.js';
|
||||
import { resolve } from 'node:path';
|
||||
|
||||
const config = loadConfig();
|
||||
const pool = createMySqlPool(config);
|
||||
@@ -34,6 +37,13 @@ const app = await buildApp({
|
||||
authRepository,
|
||||
accessControl,
|
||||
jwtSecret: config.auth.jwtSecret
|
||||
},
|
||||
content: {
|
||||
repository: new ContentRepository(pool),
|
||||
mediaStorage: new MediaStorage(resolve(process.cwd(), 'shared', 'uploads')),
|
||||
authRepository,
|
||||
accessControl,
|
||||
jwtSecret: config.auth.jwtSecret
|
||||
}
|
||||
});
|
||||
app.addHook('onClose', async () => {
|
||||
|
||||
Reference in New Issue
Block a user