feat(api): management photo list and account lookup

P1b Task 4: listAlbumPhotos (GET /albums/{albumId}/photos, tag
[photos]) + lookupUsersByAccount (GET /admin/users, tag [admin]).

- management list: all visibility states visible (unpublished/
  published/hidden/deleted) for owner/admin; collaborator 403,
  outsider/ghost album 404 (canView -> canManage ordering, same
  anti-enumeration as members). Items = PhotoRecord + uploader
  {userId, account, displayName} (flat-FK second query, redacted).
  Keyset (uploadedAt,id) DESC via shared/cursor; visibility filter
  validated against PhotoVisibility enum (400 otherwise), categoryId
  must belong to the album (ghost/cross-album same-code 400).
  pending_upload rows (uploadedAt NULL) excluded: the sort key is
  both the contract-required field and the keyset predicate - NULL
  can neither be shaped as PhotoRecord nor compared; in-flight
  uploads are covered by the uploads history endpoint.
- account lookup (new src/admin module): prefix search over active
  users only (credentialStatus=active, sourceStatus!=disabled,
  !localLocked - same eligibility as SessionGuard/members.add),
  account ASC, no cursor (small cap). $queryRaw LIKE prefix% with
  explicit ESCAPE '!': !/%/_/\ escaped to literal matching (Prisma
  startsWith escaping is not contractual); utf8mb4_0900_bin makes
  the prefix match case-sensitive ('AL' misses 'alice'), documented
  in contract + tests. Access policy per contract: any authenticated
  staff (deviation from plan's admin/owner), unauthenticated 401.
- e2e: photos-admin (6) + users-lookup (6) cases; api e2e 136 -> 148.

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
浅念
2026-09-18 08:54:44 +08:00
parent 361a72f300
commit 8ba98ace63
10 changed files with 1124 additions and 12 deletions
+135 -3
View File
@@ -1,6 +1,7 @@
// services/api/src/photos/photos.service.ts —— 照片可见性生命周期(Task 24:
// updatePhoto 隐藏/恢复发布、deletePhoto 软删除)。契约权威:openapi.yaml tags
// [photos]。状态机(visibility,docs §5.5「对外可见性」):
// updatePhoto 隐藏/恢复发布、deletePhoto 软删除)+ 管理照片列表(P1b Task 4:
// listAlbumPhotos,全状态可见 + uploader 脱敏内嵌 + (uploadedAt,id) 键集游标)。
// 契约权威:openapi.yaml tags [photos]。状态机(visibility,docs §5.5「对外可见性」):
// unpublished ──(worker 发布事务, Task 21)──▶ published
// published ◀──────(manager)──────▶ hidden 双向,管理者可来回
// unpublished/published/hidden ──(manager)──▶ deleted 单向终态(软删除)
@@ -26,8 +27,18 @@ import type { Prisma } from '@photo/db-cn';
import { ApiException } from '../api-exception';
import type { AuthUser } from '../auth/session.guard';
import { PermissionsService } from '../albums/permissions.service';
import {
albumForbidden,
albumNotFound,
validationFailed,
} from '../albums/support';
import { PrismaService } from '../prisma/prisma.service';
import type { PhotoVisibilityTarget } from './dto';
import {
decodeKeysetCursor,
encodeKeysetCursor,
keysetWhereDesc,
} from '../shared/cursor';
import type { PhotoVisibility, PhotoVisibilityTarget } from './dto';
import {
photoForbidden,
photoNotFound,
@@ -35,6 +46,7 @@ import {
} from './support';
export type PhotoRecord = components['schemas']['PhotoRecord'];
export type AdminPhotoListResponse = components['schemas']['AdminPhotoList'];
type PhotoRow = Prisma.photosGetPayload<Prisma.photosDefaultArgs>;
type PhotoVariantRow = Prisma.photo_variantsGetPayload<
@@ -68,6 +80,126 @@ export class PhotosService {
private readonly permissions: PermissionsService,
) {}
/**
* 管理照片列表(P1b Task 4,契约 listAlbumPhotos):区别于公开列表——全部
* 可见性状态可见(unpublished/published/hidden/deleted),条目内嵌 uploader
* 脱敏信息(account/displayName,无凭据字段)。权限顺序防枚举(同 members):
* canViewAlbum=false → 404 ALBUM_NOT_FOUND;可见但 canManageAlbum=false
* (协作者)→ 403 AUTH_FORBIDDEN;admin 对幽灵 id 权限恒真,空相册兜底 404。
* 排序 (uploadedAt,id) DESC 键集游标(shared/cursor)。
*
* 未完成上传(pending_upload、uploadedAt NULL)不入列表:uploadedAt 既是契约
* 必返字段又是键集排序键——NULL 行既无法以契约形状返回(toPhotoRecord 的
* new Date(0) 兜底会伪造 1970 时间轴),也无法参与键集谓词(SQL 对 NULL 的
* 比较恒 UNKNOWN,跨页会被静默跳过)。进行中的会话由 uploads 历史端点表达。
*/
async listAlbumPhotos(
user: AuthUser,
albumId: string,
query: {
visibility?: PhotoVisibility;
categoryId?: string;
cursor?: string;
limit: number;
},
): Promise<AdminPhotoListResponse> {
if (!(await this.permissions.canViewAlbum(user, albumId))) {
throw albumNotFound();
}
if (!(await this.permissions.canManageAlbum(user, albumId))) {
throw albumForbidden('仅创建者或管理员可访问管理列表');
}
// admin 对不存在 id 的 canView/canManage 恒真(非 admin 的可见成员行本身
// 蕴含相册存在),空相册兜底同码 404——契约「相册不存在,或当前用户不可见」。
const albumExists = await this.prisma.albums.findUnique({
where: { id: albumId },
select: { id: true },
});
if (albumExists === null) {
throw albumNotFound();
}
// categoryId:须为本相册分类;幽灵/跨册同码 400(同公开列表语义,不区分
// 两种失败,防探测)。
if (query.categoryId !== undefined) {
const category = await this.prisma.categories.findUnique({
where: { id: query.categoryId },
select: { albumId: true },
});
if (category === null || category.albumId !== albumId) {
throw validationFailed('categoryId 不属于该相册');
}
}
let decoded: ReturnType<typeof decodeKeysetCursor> = null;
if (query.cursor !== undefined && query.cursor !== '') {
decoded = decodeKeysetCursor(query.cursor);
if (decoded === null) {
throw validationFailed('cursor 不合法');
}
}
const where: Prisma.photosWhereInput = {
albumId,
uploadedAt: { not: null },
...(query.visibility !== undefined
? { visibility: query.visibility }
: {}),
...(query.categoryId !== undefined
? { categoryId: query.categoryId }
: {}),
};
if (decoded !== null) {
Object.assign(where, keysetWhereDesc('uploadedAt', 'id', decoded));
}
const rows = await this.prisma.photos.findMany({
where,
orderBy: [{ uploadedAt: 'desc' }, { id: 'desc' }],
take: query.limit + 1, // 多取一条探测 hasMore(同相册/成员列表)
});
const hasMore = rows.length > query.limit;
const page = hasMore ? rows.slice(0, query.limit) : rows;
// users 无 relation(扁平外键):二次查询应用层组装 uploader 脱敏信息。
const users =
page.length === 0
? []
: await this.prisma.users.findMany({
where: { id: { in: page.map((p) => p.uploaderId) } },
select: { id: true, account: true, displayName: true },
});
const userById = new Map(users.map((u) => [u.id, u]));
const items = page.flatMap((row) => {
const uploader = userById.get(row.uploaderId);
// 用户行缺失(P1a 无用户删除,仅可能来自手工改库):跳过而非 5xx(同
// 成员列表先例,单条脏数据不拖垮整页)。
return uploader === undefined
? []
: [
{
...toPhotoRecord(row),
uploader: {
userId: uploader.id,
account: uploader.account,
displayName: uploader.displayName,
},
},
];
});
const last = page.at(-1);
const nextCursor =
hasMore && last !== undefined
? encodeKeysetCursor({
// where 已排除 NULL:断言收窄供类型系统(键集取页末行 DB 位置)。
sort: (last.uploadedAt ?? new Date(0)).toISOString(),
id: last.id,
})
: null;
return { items, nextCursor, hasMore: nextCursor !== null };
}
/**
* 调整可见性(契约 updatePhoto):hidden↔published 间切换。权限 → 状态机 →
* 条件更新事务(entityVersion+1 + outbox + audit)→ 回读回显。