feat(api): members and categories management
成员(/v1/albums/{albumId}/members):owner/管理员邀请已开通同事为协作者
(重复 409 MEMBER_CONFLICT、owner 目标 400、未开通/停用账号 400)、成员列表
((addedAt,id) DESC 键集分页)、移除协作者(幂等 204;成员行是唯一权限来源,
删除行即失去可见性 A02;owner 不可移除 403)。分类(/albums/{albumId}/categories
与 /categories/{categoryId}):创建/部分更新/删除,translations 全量替换,
相册详情按 sortOrder 升序带出;404 统一 ALBUM_NOT_FOUND(分类不存在与相册
不可见同码)。审计 album.member.add/remove、album.category.add/update/remove
(resourceId=albumId,metadata 记目标 id/字段)。共用错误/P2002 判定抽至
support.ts(修复 meta.target 为 DB 约束名时的误判)。
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -1,15 +1,20 @@
|
||||
// services/api/src/albums/albums.module.ts —— 相册模块(Task 14 起步,Task 15 补全)。
|
||||
// PermissionsService(A02 权限基石)+ AlbumsService/AlbumsController(创建/详情/
|
||||
// 列表;Task 16 增补 PATCH)。export PermissionsService 供 uploads/photos 等后续
|
||||
// 模块经模块间 DI 复用同一份判定逻辑;AlbumsService 暂无外部消费者不 export。
|
||||
// services/api/src/albums/albums.module.ts —— 相册模块(Task 14 起步,Task 15
|
||||
// 补全,Task 16 增补 PATCH,Task 17 增补成员/分类)。PermissionsService(A02
|
||||
// 权限基石)+ AlbumsService/MembersService/CategoriesService 与对应控制器。
|
||||
// export PermissionsService 供 uploads/photos 等后续模块经模块间 DI 复用同一
|
||||
// 份判定逻辑;AlbumsService 等暂无外部消费者不 export。
|
||||
import { Module } from '@nestjs/common';
|
||||
import { AlbumsController } from './albums.controller';
|
||||
import { AlbumsService } from './albums.service';
|
||||
import { CategoriesController } from './categories.controller';
|
||||
import { CategoriesService } from './categories.service';
|
||||
import { MembersController } from './members.controller';
|
||||
import { MembersService } from './members.service';
|
||||
import { PermissionsService } from './permissions.service';
|
||||
|
||||
@Module({
|
||||
controllers: [AlbumsController],
|
||||
providers: [PermissionsService, AlbumsService],
|
||||
controllers: [AlbumsController, MembersController, CategoriesController],
|
||||
providers: [PermissionsService, AlbumsService, MembersService, CategoriesService],
|
||||
exports: [PermissionsService],
|
||||
})
|
||||
export class AlbumsModule {}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// services/api/src/albums/albums.service.ts —— 相册创建/详情/列表核心逻辑(Task 15)。
|
||||
// 契约权威:packages/contracts/openapi.yaml tags [albums](createAlbum/getAlbum/
|
||||
// listAlbums;updateAlbum 属 Task 16)。要点:
|
||||
// services/api/src/albums/albums.service.ts —— 相册创建/详情/更新/列表核心逻辑
|
||||
// (Task 15;update 自 Task 16)。契约权威:packages/contracts/openapi.yaml
|
||||
// tags [albums](createAlbum/getAlbum/updateAlbum/listAlbums)。要点:
|
||||
// · 创建走单事务:albums + album_translations(批量)+ album_members(owner)
|
||||
// + audit_logs(album.create)——四表要么全成要么全无,杜绝「无主相册」
|
||||
// (权限全部源自成员行,Task 14 结论:漏写 owner 行会让创建者自己不可见)。
|
||||
@@ -29,6 +29,12 @@ import {
|
||||
} from '../shared/cursor';
|
||||
import type { AlbumCreateRequestDto, AlbumUpdateRequestDto } from './dto';
|
||||
import { PermissionsService } from './permissions.service';
|
||||
import {
|
||||
albumForbidden,
|
||||
albumNotFound,
|
||||
isUniqueViolationOn,
|
||||
validationFailed,
|
||||
} from './support';
|
||||
|
||||
export type AlbumTranslationResponse =
|
||||
components['schemas']['AlbumTranslation'];
|
||||
@@ -69,32 +75,6 @@ function generatePublicToken(): string {
|
||||
return token;
|
||||
}
|
||||
|
||||
function albumNotFound(): ApiException {
|
||||
return new ApiException(
|
||||
ErrorCodes.ALBUM_NOT_FOUND,
|
||||
'相册不存在或不可见',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
/** P2002 是否命中指定唯一索引(meta.target 形如 ['publicToken'])。 */
|
||||
function isUniqueViolationOn(err: unknown, field: string): boolean {
|
||||
if (typeof err !== 'object' || err === null) {
|
||||
return false;
|
||||
}
|
||||
const { code, meta } = err as { code?: unknown; meta?: { target?: unknown } };
|
||||
if (code !== 'P2002') {
|
||||
return false;
|
||||
}
|
||||
const target = meta?.target;
|
||||
const fields = Array.isArray(target)
|
||||
? target
|
||||
: typeof target === 'string'
|
||||
? [target]
|
||||
: [];
|
||||
return fields.includes(field);
|
||||
}
|
||||
|
||||
type AlbumRow = Prisma.albumsGetPayload<Prisma.albumsDefaultArgs>;
|
||||
type AlbumTranslationRow = Prisma.album_translationsGetPayload<
|
||||
Prisma.album_translationsDefaultArgs
|
||||
@@ -146,7 +126,8 @@ export class AlbumsService {
|
||||
|
||||
/**
|
||||
* 创建相册:事务内四写(albums/translations/members/audit),返回完整
|
||||
* Album 形状(categories 恒 []——分类自 Task 17 起才有写入入口)。
|
||||
* Album 形状(categories 恒 []——新建相册尚无分类,写入入口在
|
||||
* CategoriesService,Task 17)。
|
||||
*/
|
||||
async create(
|
||||
userId: string,
|
||||
@@ -156,11 +137,7 @@ export class AlbumsService {
|
||||
// ——那是 500 而非 400,必须在入事务前以校验错误拒绝。
|
||||
const locales = dto.translations.map((t) => t.locale);
|
||||
if (new Set(locales).size !== locales.length) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.VALIDATION_FAILED,
|
||||
'translations 存在重复 locale',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
throw validationFailed('translations 存在重复 locale');
|
||||
}
|
||||
|
||||
let albumId: string;
|
||||
@@ -274,11 +251,7 @@ export class AlbumsService {
|
||||
(key) => dto[key] !== undefined,
|
||||
) as string[];
|
||||
if (fields.length === 0) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.VALIDATION_FAILED,
|
||||
'请求体至少需要包含一个待更新字段',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
throw validationFailed('请求体至少需要包含一个待更新字段');
|
||||
}
|
||||
if (dto.translations !== undefined) {
|
||||
// 同 create:重复 locale 会在事务内 createMany 撞唯一索引变 500,先 400。
|
||||
@@ -296,11 +269,7 @@ export class AlbumsService {
|
||||
throw albumNotFound();
|
||||
}
|
||||
if (!(await this.permissions.canManageAlbum(user, albumId))) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.AUTH_FORBIDDEN,
|
||||
'仅创建者或管理员可修改相册',
|
||||
HttpStatus.FORBIDDEN,
|
||||
);
|
||||
throw albumForbidden('仅创建者或管理员可修改相册');
|
||||
}
|
||||
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
@@ -318,21 +287,15 @@ export class AlbumsService {
|
||||
? null
|
||||
: new Date(dto.endAt);
|
||||
if (endAt !== null && endAt.getTime() <= startAt.getTime()) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.VALIDATION_FAILED,
|
||||
'endAt 必须晚于 startAt',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
throw validationFailed('endAt 必须晚于 startAt');
|
||||
}
|
||||
|
||||
// 合并校验②:合并后的 defaultLocale 必须被合并后的翻译集覆盖。
|
||||
const defaultLocale = dto.defaultLocale ?? album.defaultLocale;
|
||||
if (dto.translations !== undefined) {
|
||||
if (!dto.translations.some((t) => t.locale === defaultLocale)) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.VALIDATION_FAILED,
|
||||
throw validationFailed(
|
||||
'translations 必须包含(更新后的)defaultLocale 对应语言的条目',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
} else if (dto.defaultLocale !== undefined) {
|
||||
@@ -342,11 +305,7 @@ export class AlbumsService {
|
||||
select: { locale: true },
|
||||
});
|
||||
if (!rows.some((r) => r.locale === defaultLocale)) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.VALIDATION_FAILED,
|
||||
'defaultLocale 必须有对应翻译条目',
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
throw validationFailed('defaultLocale 必须有对应翻译条目');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -474,8 +433,8 @@ export class AlbumsService {
|
||||
|
||||
/**
|
||||
* 组装完整 Album 形状:主行 + 翻译(locale 升序,确定性输出)+ 分类
|
||||
* (sortOrder 升序,Task 17 前无写入入口故实际为空数组——join 逻辑先就位,
|
||||
* 分类上线即生效)。相册域无 Prisma relation,全部二次查询应用层组装。
|
||||
* (sortOrder 升序;写入入口为 CategoriesService,Task 17 起)。相册域无
|
||||
* Prisma relation,全部二次查询应用层组装。
|
||||
*/
|
||||
private async loadAlbum(albumId: string): Promise<AlbumResponse | null> {
|
||||
const album = await this.prisma.albums.findUnique({
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// services/api/src/albums/categories.controller.ts —— 分类端点(Task 17)。
|
||||
// 方法名与契约 operationId 一一对应(createCategory/updateCategory/
|
||||
// deleteCategory)。契约把创建挂在 /albums/{albumId}/categories、更新/删除
|
||||
// 挂在 /categories/{categoryId}——单控制器 + 显式全路径(两个基地址)。
|
||||
// 控制器级 SessionGuard:三端点全需认证;权限与 HTTP 映射(404/403/400)
|
||||
// 由 CategoriesService 抛 ApiException。
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthenticatedRequest, SessionGuard } from '../auth/session.guard';
|
||||
import { userOf } from './albums.controller';
|
||||
import { CategoriesService, type CategoryResponse } from './categories.service';
|
||||
import {
|
||||
CategoryCreateRequestDto,
|
||||
CategoryUpdateRequestDto,
|
||||
} from './dto';
|
||||
|
||||
@Controller()
|
||||
@UseGuards(SessionGuard)
|
||||
export class CategoriesController {
|
||||
constructor(private readonly categoriesService: CategoriesService) {}
|
||||
|
||||
@Post('albums/:albumId/categories')
|
||||
createCategory(
|
||||
@Param('albumId') albumId: string,
|
||||
@Body() dto: CategoryCreateRequestDto,
|
||||
@Req() req: AuthenticatedRequest,
|
||||
): Promise<CategoryResponse> {
|
||||
return this.categoriesService.create(userOf(req), albumId, dto);
|
||||
}
|
||||
|
||||
@Patch('categories/:categoryId')
|
||||
updateCategory(
|
||||
@Param('categoryId') categoryId: string,
|
||||
@Body() dto: CategoryUpdateRequestDto,
|
||||
@Req() req: AuthenticatedRequest,
|
||||
): Promise<CategoryResponse> {
|
||||
return this.categoriesService.update(userOf(req), categoryId, dto);
|
||||
}
|
||||
|
||||
@Delete('categories/:categoryId')
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
deleteCategory(
|
||||
@Param('categoryId') categoryId: string,
|
||||
@Req() req: AuthenticatedRequest,
|
||||
): Promise<void> {
|
||||
return this.categoriesService.remove(userOf(req), categoryId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
// services/api/src/albums/categories.service.ts —— 相册分类管理(Task 17)。
|
||||
// 契约权威:openapi.yaml tags [categories](createCategory/updateCategory/
|
||||
// deleteCategory)。要点:
|
||||
// · /categories/{categoryId} 端点的 404 语义与契约一致:分类不存在或所属
|
||||
// 相册不可见统一 ALBUM_NOT_FOUND(先读分类行→404,再 canView→404、
|
||||
// canManage→403;非成员视角「分类不存在」与「不可见」同码防枚举)。
|
||||
// · translations 全量替换(deleteMany+createMany);重复 locale 入事务前
|
||||
// 400(同 albums 翻译处理:撞唯一索引是 500 不是 400)。
|
||||
// · 审计 resourceId=albumId(与 album.* 动作族统一,便于「某相册全部操作」
|
||||
// 检索),metadata.categoryId 指向具体分类;update 额外记 fields。
|
||||
// · 删除:分类+翻译行同事务删除。契约注「分类下仍有照片时是否允许删除由
|
||||
// 服务端策略决定」——P1a 照片写入路径(Task 18+)尚未给 photos.categoryId
|
||||
// 赋值,此处不做照片计数检查,Task 20 照片分类赋值时再补。
|
||||
import { HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { ErrorCodes } from '@photo/contracts';
|
||||
import { ApiException } from '../api-exception';
|
||||
import type { components } from '@photo/contracts';
|
||||
import type { Prisma } from '@photo/db-cn';
|
||||
import type { AuthUser } from '../auth/session.guard';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import type {
|
||||
CategoryCreateRequestDto,
|
||||
CategoryUpdateRequestDto,
|
||||
} from './dto';
|
||||
import { PermissionsService } from './permissions.service';
|
||||
import {
|
||||
albumForbidden,
|
||||
albumNotFound,
|
||||
validationFailed,
|
||||
} from './support';
|
||||
|
||||
export type CategoryResponse = components['schemas']['Category'];
|
||||
export type CategoryTranslationResponse =
|
||||
components['schemas']['CategoryTranslation'];
|
||||
|
||||
type CategoryRow = Prisma.categoriesGetPayload<Prisma.categoriesDefaultArgs>;
|
||||
type CategoryTranslationRow = Prisma.category_translationsGetPayload<
|
||||
Prisma.category_translationsDefaultArgs
|
||||
>;
|
||||
|
||||
/** 契约 CategoryUpdateRequest 属性序(审计 metadata.fields 序列,同 albums)。 */
|
||||
const CATEGORY_UPDATE_FIELD_ORDER = [
|
||||
'sortOrder',
|
||||
'translations',
|
||||
] as const satisfies readonly (keyof CategoryUpdateRequestDto)[];
|
||||
|
||||
/** translations 重复 locale → 400(入事务前,理由同 albums.service)。 */
|
||||
function assertNoDuplicateLocale(
|
||||
translations: Array<{ locale: string }>,
|
||||
): void {
|
||||
const locales = translations.map((t) => t.locale);
|
||||
if (new Set(locales).size !== locales.length) {
|
||||
throw validationFailed('translations 存在重复 locale');
|
||||
}
|
||||
}
|
||||
|
||||
function toCategoryResponse(
|
||||
category: CategoryRow,
|
||||
translations: CategoryTranslationRow[],
|
||||
): CategoryResponse {
|
||||
return {
|
||||
id: category.id,
|
||||
albumId: category.albumId,
|
||||
sortOrder: category.sortOrder,
|
||||
translations: translations.map((row) => ({
|
||||
// locale 取值来自入参枚举校验,收窄为契约 Locale(同 albums 翻译)。
|
||||
locale: row.locale as CategoryTranslationResponse['locale'],
|
||||
name: row.name,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class CategoriesService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly permissions: PermissionsService,
|
||||
) {}
|
||||
|
||||
/** 创建分类(契约 createCategory):201 返回 Category。 */
|
||||
async create(
|
||||
user: AuthUser,
|
||||
albumId: string,
|
||||
dto: CategoryCreateRequestDto,
|
||||
): Promise<CategoryResponse> {
|
||||
assertNoDuplicateLocale(dto.translations);
|
||||
await this.assertAlbumManaged(user, albumId);
|
||||
|
||||
const categoryId = await this.prisma.$transaction(async (tx) => {
|
||||
const category = await tx.categories.create({
|
||||
data: { albumId, sortOrder: dto.sortOrder ?? 0 },
|
||||
select: { id: true },
|
||||
});
|
||||
await tx.category_translations.createMany({
|
||||
data: dto.translations.map((t) => ({
|
||||
categoryId: category.id,
|
||||
locale: t.locale,
|
||||
name: t.name,
|
||||
})),
|
||||
});
|
||||
await tx.audit_logs.create({
|
||||
data: {
|
||||
actorId: user.id,
|
||||
action: 'album.category.add',
|
||||
resourceId: albumId,
|
||||
metadata: { categoryId: category.id },
|
||||
},
|
||||
});
|
||||
return category.id;
|
||||
});
|
||||
const category = await this.loadCategory(categoryId);
|
||||
if (category === null) {
|
||||
// 刚提交就读不到只可能是并发异常路径,按 5xx 兜底(同 albums.create)。
|
||||
throw new ApiException(
|
||||
ErrorCodes.INTERNAL_ERROR,
|
||||
'Internal server error',
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
);
|
||||
}
|
||||
return category;
|
||||
}
|
||||
|
||||
/** 更新分类(契约 updateCategory):部分更新,translations 全量替换。 */
|
||||
async update(
|
||||
user: AuthUser,
|
||||
categoryId: string,
|
||||
dto: CategoryUpdateRequestDto,
|
||||
): Promise<CategoryResponse> {
|
||||
// 契约 minProperties:1(判据同 albums.service.update:plainToInstance 后
|
||||
// 声明属性以 undefined 成键,以「任一字段已赋值」为准)。
|
||||
const fields = CATEGORY_UPDATE_FIELD_ORDER.filter(
|
||||
(key) => dto[key] !== undefined,
|
||||
);
|
||||
if (fields.length === 0) {
|
||||
throw validationFailed('请求体至少需要包含一个待更新字段');
|
||||
}
|
||||
if (dto.translations !== undefined) {
|
||||
assertNoDuplicateLocale(dto.translations);
|
||||
}
|
||||
|
||||
const existing = await this.assertCategoryManaged(user, categoryId);
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.categories.update({
|
||||
where: { id: categoryId },
|
||||
data: { sortOrder: dto.sortOrder },
|
||||
});
|
||||
if (dto.translations !== undefined) {
|
||||
await tx.category_translations.deleteMany({ where: { categoryId } });
|
||||
await tx.category_translations.createMany({
|
||||
data: dto.translations.map((t) => ({
|
||||
categoryId,
|
||||
locale: t.locale,
|
||||
name: t.name,
|
||||
})),
|
||||
});
|
||||
}
|
||||
await tx.audit_logs.create({
|
||||
data: {
|
||||
actorId: user.id,
|
||||
action: 'album.category.update',
|
||||
resourceId: existing.albumId,
|
||||
metadata: { categoryId, fields },
|
||||
},
|
||||
});
|
||||
});
|
||||
const category = await this.loadCategory(categoryId);
|
||||
if (category === null) {
|
||||
throw albumNotFound();
|
||||
}
|
||||
return category;
|
||||
}
|
||||
|
||||
/** 删除分类(契约 deleteCategory):204 无响应体。 */
|
||||
async remove(user: AuthUser, categoryId: string): Promise<void> {
|
||||
const existing = await this.assertCategoryManaged(user, categoryId);
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.category_translations.deleteMany({ where: { categoryId } });
|
||||
await tx.categories.delete({ where: { id: categoryId } });
|
||||
await tx.audit_logs.create({
|
||||
data: {
|
||||
actorId: user.id,
|
||||
action: 'album.category.remove',
|
||||
resourceId: existing.albumId,
|
||||
metadata: { categoryId },
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** /albums/{albumId}/categories 的 404/403 顺序映射 + admin 空相册兜底。 */
|
||||
private async assertAlbumManaged(
|
||||
user: AuthUser,
|
||||
albumId: string,
|
||||
): Promise<void> {
|
||||
if (!(await this.permissions.canViewAlbum(user, albumId))) {
|
||||
throw albumNotFound();
|
||||
}
|
||||
if (!(await this.permissions.canManageAlbum(user, albumId))) {
|
||||
throw albumForbidden('仅创建者或管理员可管理分类');
|
||||
}
|
||||
const album = await this.prisma.albums.findUnique({
|
||||
where: { id: albumId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (album === null) {
|
||||
// admin 视角 canView 恒真,空值兜底同码 404。
|
||||
throw albumNotFound();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* /categories/{categoryId} 的 404/403 顺序映射:分类行不存在 → 404(契约
|
||||
* 语义:分类不存在或所属相册不存在/不可见同码);行存在再按所属相册判
|
||||
* canView → 404 / canManage → 403。返回分类行(含 albumId 供审计)。
|
||||
*/
|
||||
private async assertCategoryManaged(
|
||||
user: AuthUser,
|
||||
categoryId: string,
|
||||
): Promise<CategoryRow> {
|
||||
const category = await this.prisma.categories.findUnique({
|
||||
where: { id: categoryId },
|
||||
});
|
||||
if (category === null) {
|
||||
throw albumNotFound();
|
||||
}
|
||||
if (!(await this.permissions.canViewAlbum(user, category.albumId))) {
|
||||
throw albumNotFound();
|
||||
}
|
||||
if (!(await this.permissions.canManageAlbum(user, category.albumId))) {
|
||||
throw albumForbidden('仅创建者或管理员可管理分类');
|
||||
}
|
||||
return category;
|
||||
}
|
||||
|
||||
/** 组装 Category 形状:主行 + 翻译(locale 升序,确定性输出)。 */
|
||||
private async loadCategory(categoryId: string): Promise<CategoryResponse | null> {
|
||||
const category = await this.prisma.categories.findUnique({
|
||||
where: { id: categoryId },
|
||||
});
|
||||
if (category === null) {
|
||||
return null;
|
||||
}
|
||||
const translations = await this.prisma.category_translations.findMany({
|
||||
where: { categoryId },
|
||||
orderBy: { locale: 'asc' },
|
||||
});
|
||||
return toCategoryResponse(category, translations);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
// services/api/src/albums/dto.ts —— 相册端点入参 DTO(Task 15;Task 16 增补更新版)。
|
||||
// 校验约束对齐契约 AlbumCreateRequest / AlbumUpdateRequest / AlbumTranslation:
|
||||
// services/api/src/albums/dto.ts —— 相册端点入参 DTO(Task 15;Task 16 增补更新版;
|
||||
// Task 17 增补成员/分类)。校验约束对齐契约
|
||||
// AlbumCreateRequest / AlbumUpdateRequest / MemberAddRequest /
|
||||
// CategoryCreateRequest / CategoryUpdateRequest / AlbumTranslation:
|
||||
// · translations 至少 1 条(minItems: 1),locale 限 P1a 双语枚举;
|
||||
// · defaultLocale 必须有对应翻译条目(跨字段校验,契约 required 语义);
|
||||
// · endAt 可空(契约 [string,'null']),给值时须晚于 startAt(跨字段校验);
|
||||
@@ -13,11 +15,14 @@ import {
|
||||
ArrayMinSize,
|
||||
IsBoolean,
|
||||
IsIn,
|
||||
IsInt,
|
||||
IsISO8601,
|
||||
IsNotEmpty,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
Max,
|
||||
Min,
|
||||
Validate,
|
||||
ValidateNested,
|
||||
ValidatorConstraint,
|
||||
@@ -222,3 +227,70 @@ export class AlbumUpdateRequestDto {
|
||||
@IsBoolean()
|
||||
originalDownloadEnabled?: boolean;
|
||||
}
|
||||
|
||||
// ── 成员(Task 17)──
|
||||
|
||||
/**
|
||||
* 契约 MemberAddRequest:userId 必填(已开通账号);role 缺省 collaborator,
|
||||
* 枚举仅 collaborator——owner 由创建流程产生,经本端点加 owner 属 P4a 管理员
|
||||
* 操作,role='owner' 在 DTO 层即 400。
|
||||
*/
|
||||
export class MemberAddRequestDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(64) // users.id VarChar(64)
|
||||
userId!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(['collaborator'])
|
||||
role?: 'collaborator';
|
||||
}
|
||||
|
||||
// ── 分类(Task 17)──
|
||||
|
||||
/** 契约 CategoryTranslation:name minLength 1;列宽 VarChar(128)。 */
|
||||
export class CategoryTranslationDto {
|
||||
@IsIn(ALBUM_LOCALES)
|
||||
locale!: AlbumLocale;
|
||||
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
@MaxLength(128)
|
||||
name!: string;
|
||||
}
|
||||
|
||||
/** sortOrder:契约 integer 无界;Int 列物理边界内收为 400(而非溢出 500)。 */
|
||||
const SORT_ORDER_MIN = -2_147_483_648;
|
||||
const SORT_ORDER_MAX = 2_147_483_647;
|
||||
|
||||
export class CategoryCreateRequestDto {
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(SORT_ORDER_MIN)
|
||||
@Max(SORT_ORDER_MAX)
|
||||
sortOrder?: number;
|
||||
|
||||
@ArrayMinSize(1)
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => CategoryTranslationDto)
|
||||
translations!: CategoryTranslationDto[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 契约 CategoryUpdateRequest:全字段可选 + minProperties:1。空体拒绝在服务层
|
||||
* (同 AlbumUpdateRequestDto:plainToInstance 后声明属性以 undefined 成键,
|
||||
* Object.keys 不可判空,以「任一字段已赋值」为判据)。
|
||||
*/
|
||||
export class CategoryUpdateRequestDto {
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(SORT_ORDER_MIN)
|
||||
@Max(SORT_ORDER_MAX)
|
||||
sortOrder?: number;
|
||||
|
||||
@IsOptional()
|
||||
@ArrayMinSize(1)
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => CategoryTranslationDto)
|
||||
translations?: CategoryTranslationDto[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// services/api/src/albums/members.controller.ts —— /albums/{albumId}/members
|
||||
// 端点(Task 17)。方法名与契约 operationId 一一对应(addAlbumMember/
|
||||
// listAlbumMembers/removeAlbumMember)。控制器级 SessionGuard:三端点全需
|
||||
// 认证。控制器只做认证用户透传 + 查询参数规整(复用 albums.controller 的
|
||||
// parseLimit/parseCursor,同一契约 bounds/游标语义);权限与 HTTP 映射由
|
||||
// MembersService 抛 ApiException(404 ALBUM_NOT_FOUND / 403 AUTH_FORBIDDEN /
|
||||
// 409 MEMBER_CONFLICT)。
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { AuthenticatedRequest, SessionGuard } from '../auth/session.guard';
|
||||
import { parseCursor, parseLimit, userOf } from './albums.controller';
|
||||
import { MemberAddRequestDto } from './dto';
|
||||
import {
|
||||
type MemberListResponse,
|
||||
type MemberResponse,
|
||||
MembersService,
|
||||
} from './members.service';
|
||||
|
||||
@Controller('albums/:albumId/members')
|
||||
@UseGuards(SessionGuard)
|
||||
export class MembersController {
|
||||
constructor(private readonly membersService: MembersService) {}
|
||||
|
||||
@Post()
|
||||
addAlbumMember(
|
||||
@Param('albumId') albumId: string,
|
||||
@Body() dto: MemberAddRequestDto,
|
||||
@Req() req: AuthenticatedRequest,
|
||||
): Promise<MemberResponse> {
|
||||
return this.membersService.add(userOf(req), albumId, dto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
listAlbumMembers(
|
||||
@Param('albumId') albumId: string,
|
||||
@Query('cursor') cursor: string | undefined,
|
||||
@Query('limit') limit: string | undefined,
|
||||
@Req() req: AuthenticatedRequest,
|
||||
): Promise<MemberListResponse> {
|
||||
return this.membersService.list(
|
||||
userOf(req),
|
||||
albumId,
|
||||
parseCursor(cursor),
|
||||
parseLimit(limit),
|
||||
);
|
||||
}
|
||||
|
||||
@Delete(':userId')
|
||||
@HttpCode(HttpStatus.NO_CONTENT)
|
||||
removeAlbumMember(
|
||||
@Param('albumId') albumId: string,
|
||||
@Param('userId') userId: string,
|
||||
@Req() req: AuthenticatedRequest,
|
||||
): Promise<void> {
|
||||
return this.membersService.remove(userOf(req), albumId, userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
// services/api/src/albums/members.service.ts —— 相册成员管理(Task 17)。
|
||||
// 契约权威:openapi.yaml tags [members](addAlbumMember/listAlbumMembers/
|
||||
// removeAlbumMember)。要点:
|
||||
// · 权限顺序与 albums 一致防枚举:canViewAlbum=false → 404;canManageAlbum
|
||||
// =false → 403(协作者可见不可管);admin 视角再由空行兜底 404。
|
||||
// · 成员行(album_members)是唯一权限来源(Task 14 结论):移除=删行,
|
||||
// 被移除者下一次请求即刻失去可见性(A02,PermissionsService 无缓存)。
|
||||
// · owner 行不可经本端点产生/删除:邀请 owner 目标 → 400(仅 collaborator
|
||||
// 可加,owner 转移属 P4a 管理员操作);移除 owner → 403。
|
||||
// · 被邀请账号必须已开通(credentialStatus=active 且 sourceStatus≠disabled):
|
||||
// 邀请属管理动作,明示目标账号有效性不构成成员枚举泄露。
|
||||
// · 移除幂等:目标成员行不存在仍 204(契约语义);仅真实删除落审计
|
||||
// (幂等重删不重复记 album.member.remove)。
|
||||
// · 列表:(addedAt,id) DESC 键集游标(shared/cursor,与相册列表同构);
|
||||
// users 无 relation(扁平外键),二次查询应用层组装 Member。
|
||||
import { HttpStatus, Injectable } from '@nestjs/common';
|
||||
import { ErrorCodes } from '@photo/contracts';
|
||||
import type { components } from '@photo/contracts';
|
||||
import type { Prisma } from '@photo/db-cn';
|
||||
import { ApiException } from '../api-exception';
|
||||
import type { AuthUser } from '../auth/session.guard';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import {
|
||||
decodeKeysetCursor,
|
||||
encodeKeysetCursor,
|
||||
keysetWhereDesc,
|
||||
} from '../shared/cursor';
|
||||
import type { MemberAddRequestDto } from './dto';
|
||||
import { PermissionsService } from './permissions.service';
|
||||
import {
|
||||
albumForbidden,
|
||||
albumNotFound,
|
||||
isUniqueViolationOn,
|
||||
validationFailed,
|
||||
} from './support';
|
||||
|
||||
export type MemberResponse = components['schemas']['Member'];
|
||||
export type MemberListResponse = components['schemas']['MemberList'];
|
||||
|
||||
@Injectable()
|
||||
export class MembersService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly permissions: PermissionsService,
|
||||
) {}
|
||||
|
||||
/** 添加协作者(契约 addAlbumMember):201 返回 Member。 */
|
||||
async add(
|
||||
user: AuthUser,
|
||||
albumId: string,
|
||||
dto: MemberAddRequestDto,
|
||||
): Promise<MemberResponse> {
|
||||
const { ownerId } = await this.assertManageable(user, albumId);
|
||||
|
||||
// 目标账号须存在且已开通(pending 凭据/已停用均不可加)。
|
||||
const target = await this.prisma.users.findUnique({
|
||||
where: { id: dto.userId },
|
||||
select: {
|
||||
account: true,
|
||||
displayName: true,
|
||||
credentialStatus: true,
|
||||
sourceStatus: true,
|
||||
},
|
||||
});
|
||||
if (
|
||||
target === null ||
|
||||
target.credentialStatus !== 'active' ||
|
||||
target.sourceStatus === 'disabled'
|
||||
) {
|
||||
throw validationFailed('被邀请的用户不存在或不可用(须为已开通账号)');
|
||||
}
|
||||
// owner 不能经本端点被(重)添加:防重复 owner 行与角色歧义。
|
||||
if (dto.userId === ownerId) {
|
||||
throw validationFailed('owner 由创建流程产生,不能经由本端点添加');
|
||||
}
|
||||
|
||||
const role = dto.role ?? 'collaborator';
|
||||
try {
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.album_members.create({
|
||||
data: { albumId, userId: dto.userId, role, status: 'active' },
|
||||
});
|
||||
await tx.audit_logs.create({
|
||||
data: {
|
||||
actorId: user.id,
|
||||
action: 'album.member.add',
|
||||
resourceId: albumId,
|
||||
metadata: { userId: dto.userId, role },
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (err) {
|
||||
// 并发窗口内重复邀请:唯一索引 @@unique([albumId,userId]) 兜底成契约 409。
|
||||
if (isUniqueViolationOn(err, 'albumId_userId')) {
|
||||
throw new ApiException(
|
||||
ErrorCodes.MEMBER_CONFLICT,
|
||||
'该用户已是相册成员',
|
||||
HttpStatus.CONFLICT,
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
return {
|
||||
userId: dto.userId,
|
||||
account: target.account,
|
||||
displayName: target.displayName,
|
||||
role,
|
||||
status: 'active',
|
||||
};
|
||||
}
|
||||
|
||||
/** 成员列表(契约 listAlbumMembers):任何成员/admin 可见;(addedAt,id) DESC。 */
|
||||
async list(
|
||||
user: AuthUser,
|
||||
albumId: string,
|
||||
cursor: string | undefined,
|
||||
limit: number,
|
||||
): Promise<MemberListResponse> {
|
||||
if (!(await this.permissions.canViewAlbum(user, albumId))) {
|
||||
throw albumNotFound();
|
||||
}
|
||||
// admin 对不存在的 id 权限恒真(非 admin 的可见成员行本身蕴含相册存在),
|
||||
// 空相册兜底同码 404——契约「相册不存在,或当前用户不可见」。
|
||||
const albumExists = await this.prisma.albums.findUnique({
|
||||
where: { id: albumId },
|
||||
select: { id: true },
|
||||
});
|
||||
if (albumExists === null) {
|
||||
throw albumNotFound();
|
||||
}
|
||||
let decoded: ReturnType<typeof decodeKeysetCursor> = null;
|
||||
if (cursor !== undefined && cursor !== '') {
|
||||
decoded = decodeKeysetCursor(cursor);
|
||||
if (decoded === null) {
|
||||
throw validationFailed('cursor 不合法');
|
||||
}
|
||||
}
|
||||
|
||||
const where: Prisma.album_membersWhereInput = { albumId };
|
||||
if (decoded !== null) {
|
||||
Object.assign(where, keysetWhereDesc('addedAt', 'id', decoded));
|
||||
}
|
||||
const rows = await this.prisma.album_members.findMany({
|
||||
where,
|
||||
orderBy: [{ addedAt: 'desc' }, { id: 'desc' }],
|
||||
take: limit + 1, // 多取一条探测 hasMore(同相册列表,免 count 查询)
|
||||
});
|
||||
const hasMore = rows.length > limit;
|
||||
const page = hasMore ? rows.slice(0, limit) : rows;
|
||||
|
||||
const users = await this.prisma.users.findMany({
|
||||
where: { id: { in: page.map((m) => m.userId) } },
|
||||
select: { id: true, account: true, displayName: true },
|
||||
});
|
||||
const byId = new Map(users.map((u) => [u.id, u]));
|
||||
|
||||
const items = page.flatMap((row) => {
|
||||
const u = byId.get(row.userId);
|
||||
// 用户行缺失(P1a 无用户删除,仅可能来自手工改库):跳过而非报错。
|
||||
return u === undefined
|
||||
? []
|
||||
: [
|
||||
{
|
||||
userId: row.userId,
|
||||
account: u.account,
|
||||
displayName: u.displayName,
|
||||
role: row.role as MemberResponse['role'],
|
||||
status: row.status as MemberResponse['status'],
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
const last = page.at(-1);
|
||||
const nextCursor =
|
||||
hasMore && last !== undefined
|
||||
? encodeKeysetCursor({
|
||||
sort: last.addedAt.toISOString(),
|
||||
id: last.id,
|
||||
})
|
||||
: null;
|
||||
return { items, nextCursor, hasMore: nextCursor !== null };
|
||||
}
|
||||
|
||||
/** 移除成员(契约 removeAlbumMember):幂等 204;owner 不可移除(403)。 */
|
||||
async remove(
|
||||
user: AuthUser,
|
||||
albumId: string,
|
||||
targetUserId: string,
|
||||
): Promise<void> {
|
||||
const { ownerId } = await this.assertManageable(user, albumId);
|
||||
if (targetUserId === ownerId) {
|
||||
throw albumForbidden('不能移除相册创建者(owner 转移属管理员操作)');
|
||||
}
|
||||
// Task 14:成员行是唯一权限来源,移除=删行(无软删除状态)。
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
const removed = await tx.album_members.deleteMany({
|
||||
where: { albumId, userId: targetUserId },
|
||||
});
|
||||
if (removed.count > 0) {
|
||||
// 幂等重删(count=0)不重复落审计。
|
||||
await tx.audit_logs.create({
|
||||
data: {
|
||||
actorId: user.id,
|
||||
action: 'album.member.remove',
|
||||
resourceId: albumId,
|
||||
metadata: { userId: targetUserId },
|
||||
},
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 404/403 顺序映射 + admin 空相册兜底(增删均为管理动作,共用入口)。 */
|
||||
private async assertManageable(
|
||||
user: AuthUser,
|
||||
albumId: string,
|
||||
): Promise<{ ownerId: string }> {
|
||||
if (!(await this.permissions.canViewAlbum(user, albumId))) {
|
||||
throw albumNotFound();
|
||||
}
|
||||
if (!(await this.permissions.canManageAlbum(user, albumId))) {
|
||||
throw albumForbidden('仅创建者或管理员可管理成员');
|
||||
}
|
||||
const album = await this.prisma.albums.findUnique({
|
||||
where: { id: albumId },
|
||||
select: { ownerId: true },
|
||||
});
|
||||
if (album === null) {
|
||||
// admin 对不存在的 id 权限恒真,由空值兜底同码 404。
|
||||
throw albumNotFound();
|
||||
}
|
||||
return album;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// services/api/src/albums/support.ts —— 相册域服务共用小工具(Task 15 起自
|
||||
// albums.service.ts 抽出,Task 17 起 members/categories 服务同用)。
|
||||
import { HttpStatus } from '@nestjs/common';
|
||||
import { ErrorCodes } from '@photo/contracts';
|
||||
import { ApiException } from '../api-exception';
|
||||
|
||||
/** 统一 404:不可见(含不存在)同码防 id 枚举(契约 albums/categories 404 语义)。 */
|
||||
export function albumNotFound(): ApiException {
|
||||
return new ApiException(
|
||||
ErrorCodes.ALBUM_NOT_FOUND,
|
||||
'相册不存在或不可见',
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
/** 统一 403:可见但无管理权限(协作者视角)。 */
|
||||
export function albumForbidden(message = '仅创建者或管理员可操作'): ApiException {
|
||||
return new ApiException(ErrorCodes.AUTH_FORBIDDEN, message, HttpStatus.FORBIDDEN);
|
||||
}
|
||||
|
||||
/** 统一 400(契约 VALIDATION_FAILED)。 */
|
||||
export function validationFailed(message: string): ApiException {
|
||||
return new ApiException(
|
||||
ErrorCodes.VALIDATION_FAILED,
|
||||
message,
|
||||
HttpStatus.BAD_REQUEST,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* P2002 是否命中指定唯一索引。uniqueName 用 Prisma 唯一选择器名(单列
|
||||
* 'publicToken' / 复合 'albumId_userId')。meta.target 两种形态都兼容:
|
||||
* 字段数组(部分引擎/版本)或 DB 约束名字符串(MySQL 实测形如
|
||||
* 'albums_publicToken_key' / 'album_members_albumId_userId_key'——
|
||||
* 表名前缀 + 选择器名 + _key 后缀,两种后缀都匹配)。
|
||||
*/
|
||||
export function isUniqueViolationOn(err: unknown, uniqueName: string): boolean {
|
||||
if (typeof err !== 'object' || err === null) {
|
||||
return false;
|
||||
}
|
||||
const { code, meta } = err as { code?: unknown; meta?: { target?: unknown } };
|
||||
if (code !== 'P2002') {
|
||||
return false;
|
||||
}
|
||||
const target = meta?.target;
|
||||
if (Array.isArray(target)) {
|
||||
return target.map(String).includes(uniqueName);
|
||||
}
|
||||
if (typeof target === 'string') {
|
||||
return (
|
||||
target === uniqueName ||
|
||||
target.endsWith(`${uniqueName}_key`) ||
|
||||
target.endsWith(`_${uniqueName}_key`)
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
Reference in New Issue
Block a user