feat(M03-B): 完成装修广告与媒体管理

This commit is contained in:
Codex
2026-06-18 15:06:16 +08:00
parent 7e9b53487b
commit f74624296d
19 changed files with 1241 additions and 13 deletions
+220
View File
@@ -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();
}
}
}
+77
View File
@@ -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')
};
}
}