feat(admin): 添加空间删除记录查询
continuous-integration/drone/push Build is passing Details

This commit is contained in:
dongjf 2026-11-29 19:52:21 +08:00
parent 33b2e9e2ba
commit 2fc6359914
13 changed files with 147 additions and 16 deletions

View File

@ -13,3 +13,5 @@ docker build -t item-atlas-admin:dev .
本机预览使用同源 `/auth` 和独立 realm。部署、测试账号与排错步骤见 [管理后台本机预览](../../deploy/admin-preview/README.md)。登录过期或接口拒绝管理员权限时,页面会清空已读取的空间数据。
列表使用 `GET /api/admin/households?q=&limit=25&offset=0`,按名称及 ID 排序。名称按字面包含匹配,查询长度最多 100,页大小为 1 至 100。响应中的 `hasMore` 决定是否提供下一页。查询、详情和删除沿用 `atlas-admin` 客户端与 `atlas-space-admin` 角色鉴权。部署后台镜像前先部署包含列表接口的物品服务,然后在内部入口用管理员与普通账号分别检查权限。
「删除记录」显示管理员删除空间的时间、空间 ID 和操作人 ID。列表从 `GET /api/admin/space-deletions?limit=25` 读取,可以按 `householdId` 精确查。下一页传入响应中的 `nextBefore`,排序以删除时间和记录 ID 降序为准。读取同样需要管理员权限,响应禁止缓存。操作人与空间 ID 来自删除事务落库的审计记录。记录的查询不需要关联已删除的空间。

View File

@ -6,8 +6,13 @@ import zhCn from 'element-plus/es/locale/lang/zh-cn'
interface SpaceSummary { id: string; name: string }
interface Space extends SpaceSummary { items: number; photos: number }
interface SpacePage { spaces: SpaceSummary[]; hasMore: boolean }
interface SpaceDeletion { id: string; householdId: string; operatorId: string; deletedAt: string }
interface DeletionPage { records: SpaceDeletion[]; nextBefore: string | null }
type AdminView = 'spaces' | 'audit'
const pageSize = 25
const spacesApi = '/api/admin/households'
const auditApi = '/api/admin/space-deletions'
const identityUrl = import.meta.env.VITE_OIDC_URL || 'https://api-atlas.tutudog.com/auth'
const keycloak = new Keycloak({
@ -19,6 +24,7 @@ const logout = () => keycloak.logout({ redirectUri: window.location.origin + '/'
const initialized = ref(false)
const authenticated = ref(false)
const authorized = ref(false)
const view = ref<AdminView>('spaces')
const input = ref('')
const activeQuery = ref('')
const pageOffset = ref(0)
@ -29,8 +35,13 @@ const error = ref('')
const success = ref('')
const confirming = ref(false)
const confirmation = ref('')
const auditInput = ref('')
const auditHousehold = ref('')
const auditPage = ref<DeletionPage>()
const auditCursors = ref<(string | null)[]>([null])
const isId = (value: string) => /^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i.test(value)
const pageNumber = computed(() => pageOffset.value / pageSize + 1)
const auditDate = new Intl.DateTimeFormat('zh-CN', { dateStyle: 'medium', timeStyle: 'medium' })
onMounted(async () => {
try {
@ -49,6 +60,7 @@ function clearManagementData() {
authorized.value = false
page.value = undefined
space.value = undefined
auditPage.value = undefined
confirming.value = false
confirmation.value = success.value = ''
}
@ -59,11 +71,11 @@ function requireLogin(): never {
throw new Error('登录已失效,请重新登录。')
}
async function request(path = '', method = 'GET') {
async function request(path: string, method = 'GET') {
try { await keycloak.updateToken(30) }
catch { requireLogin() }
if (!keycloak.token) requireLogin()
const response = await fetch(`/api/admin/households${path}`, {
const response = await fetch(path, {
method, cache: 'no-store', headers: { Authorization: `Bearer ${keycloak.token}` },
})
if (!response.ok) {
@ -72,15 +84,55 @@ async function request(path = '', method = 'GET') {
clearManagementData()
throw new Error('当前账号没有空间管理权限。')
}
if (response.status === 404) throw new Error('找不到这个空间。')
if (response.status === 404 && path.startsWith(spacesApi + '/')) throw new Error('找不到这个空间。')
throw new Error('操作失败,请稍后重试。')
}
return response
}
function selectView(next: AdminView) {
if (busy.value || view.value === next) return
view.value = next
success.value = error.value = ''
if (next === 'audit') void loadAudit([null], auditHousehold.value)
}
function searchAudit() {
const household = auditInput.value.trim()
if (household && !isId(household)) {
error.value = '请输入完整的空间 ID。'
return
}
return loadAudit([null], household)
}
async function loadAudit(cursors: (string | null)[], household = auditHousehold.value) {
if (busy.value) return
busy.value = true
error.value = ''
const params = new URLSearchParams({ limit: String(pageSize) })
const before = cursors.at(-1)
if (household) params.set('householdId', household)
if (before) params.set('before', before)
try {
auditPage.value = await (await request(`${auditApi}?${params}`)).json()
auditCursors.value = cursors
auditHousehold.value = household
} catch (failure) {
error.value = failure instanceof Error ? failure.message : '操作记录加载失败。'
} finally {
busy.value = false
}
}
function nextAuditPage() {
const next = auditPage.value?.nextBefore
if (next) void loadAudit([...auditCursors.value, next])
}
async function readPage(offset: number, query: string) {
const params = new URLSearchParams({ q: query, limit: String(pageSize), offset: String(offset) })
const result: SpacePage = await (await request(`?${params}`)).json()
const result: SpacePage = await (await request(`${spacesApi}?${params}`)).json()
page.value = result
pageOffset.value = offset
activeQuery.value = query
@ -110,7 +162,7 @@ async function openSpace(id: string) {
busy.value = true
space.value = undefined
success.value = error.value = ''
try { space.value = await (await request(`/${id}`)).json() }
try { space.value = await (await request(`${spacesApi}/${id}`)).json() }
catch (failure) { error.value = failure instanceof Error ? failure.message : '查询失败。' }
finally { busy.value = false }
}
@ -120,7 +172,7 @@ async function deleteSpace() {
busy.value = true
error.value = ''
try {
await request(`/${space.value.id}`, 'DELETE')
await request(`${spacesApi}/${space.value.id}`, 'DELETE')
success.value = '空间已删除,原图和缩略图已进入清理队列。'
space.value = undefined
confirming.value = false
@ -145,7 +197,7 @@ async function deleteSpace() {
<el-config-provider :locale="zhCn">
<main>
<header>
<h1>见物 <small>空间管理</small></h1>
<h1>见物 <small>管理后台</small></h1>
<el-button v-if="authenticated" text @click="logout">退出登录</el-button>
<el-button v-else-if="initialized" text @click="keycloak.login()">重新登录</el-button>
</header>
@ -153,6 +205,12 @@ async function deleteSpace() {
<el-alert v-if="success" :title="success" type="success" show-icon :closable="false" />
<p v-if="!initialized">正在验证登录</p>
<template v-if="authorized">
<nav class="views" aria-label="后台功能">
<el-button :type="view === 'spaces' ? 'primary' : 'default'" :aria-pressed="view === 'spaces'" :disabled="busy" @click="selectView('spaces')">空间管理</el-button>
<el-button :type="view === 'audit' ? 'primary' : 'default'" :aria-pressed="view === 'audit'" :disabled="busy" @click="selectView('audit')">删除记录</el-button>
</nav>
</template>
<template v-if="authorized && view === 'spaces'">
<form @submit.prevent="findSpace">
<label for="space-search">查找空间</label>
<div class="lookup">
@ -196,6 +254,29 @@ async function deleteSpace() {
</template>
</el-dialog>
</template>
<section v-if="authorized && view === 'audit'" v-loading="busy" aria-label="空间删除记录">
<form @submit.prevent="searchAudit">
<label for="audit-search">按空间 ID 查询</label>
<div class="lookup">
<el-input id="audit-search" v-model="auditInput" placeholder="留空查看全部记录" maxlength="36" clearable :disabled="busy" />
<el-button native-type="submit" type="primary" :disabled="busy">查询</el-button>
</div>
</form>
<template v-if="auditPage">
<el-table :data="auditPage.records" row-key="id" empty-text="没有匹配的删除记录">
<el-table-column label="删除时间" min-width="165">
<template #default="{ row }">{{ auditDate.format(new Date(row.deletedAt)) }}</template>
</el-table-column>
<el-table-column prop="householdId" label="空间 ID" min-width="278" />
<el-table-column prop="operatorId" label="操作人 ID" min-width="278" />
</el-table>
<nav class="pages" aria-label="删除记录翻页">
<el-button :disabled="busy || auditCursors.length === 1" @click="loadAudit(auditCursors.slice(0, -1))">上一页</el-button>
<span>第 {{ auditCursors.length }} 页</span>
<el-button :disabled="busy || !auditPage.nextBefore" @click="nextAuditPage">下一页</el-button>
</nav>
</template>
</section>
</main>
</el-config-provider>
</template>
@ -210,6 +291,7 @@ h2 { margin-top: 0; }
form, .el-alert { margin-bottom: 18px; }
label { display: block; margin-bottom: 8px; }
.lookup { display: flex; gap: 10px; }
.views { margin-bottom: 22px; }
.space-list { min-height: 120px; margin-top: 18px; }
.pages { display: flex; align-items: center; justify-content: flex-end; gap: 12px; margin: 16px 0; }
</style>

View File

@ -63,6 +63,15 @@ class HouseholdController {
return ResponseEntity.accepted().build();
}
@GetMapping("/api/admin/space-deletions")
ResponseEntity<SpaceDeletionPage> spaceDeletions(
@RequestParam(required = false) UUID householdId,
@RequestParam(required = false) @Min(1) Long before,
@RequestParam(defaultValue = "25") @Min(1) @Max(100) int limit) {
return ResponseEntity.ok().cacheControl(CacheControl.noStore())
.body(service.spaceDeletions(householdId, before, limit));
}
@GetMapping(FAMILY + "/members")
List<Member> members(@PathVariable UUID household, Principal user) {
return service.members(household, user.getName());

View File

@ -13,6 +13,8 @@ final class HouseholdDtos {
record ManagedSpaceSummary(UUID id, String name) {}
record ManagedSpacePage(List<ManagedSpaceSummary> spaces, boolean hasMore) {}
record ManagedSpace(UUID id, String name, long items, long photos) {}
record SpaceDeletion(String id, UUID householdId, String operatorId, OffsetDateTime deletedAt) {}
record SpaceDeletionPage(List<SpaceDeletion> records, String nextBefore) {}
record HouseholdInput(@NotBlank @Size(max = 100) String name, @Size(max = 80) String displayName) {}
enum MemberRole { EDITOR, VIEWER }
record RoleInput(@NotNull MemberRole role) {}

View File

@ -71,6 +71,25 @@ class HouseholdService {
.param("household", household).param("actor", actor).update();
}
SpaceDeletionPage spaceDeletions(UUID household, Long before, int limit) {
var sql = new StringBuilder("SELECT id, household_id, subject, deleted_at FROM space_admin_action WHERE 1=1");
if (household != null) {
sql.append(" AND household_id=:household");
}
if (before != null) {
sql.append(" AND (deleted_at, id) < (SELECT deleted_at, id FROM space_admin_action WHERE id=:before)");
}
sql.append(" ORDER BY deleted_at DESC, id DESC LIMIT :limit");
var query = db.sql(sql.toString()).param("limit", limit + 1);
if (household != null) { query.param("household", household); }
if (before != null) { query.param("before", before); }
List<SpaceDeletion> records = query.query((rs, row) -> new SpaceDeletion(
Long.toString(rs.getLong("id")), rs.getObject("household_id", UUID.class),
rs.getString("subject"), rs.getObject("deleted_at", OffsetDateTime.class))).list();
if (records.size() <= limit) { return new SpaceDeletionPage(records, null); }
return new SpaceDeletionPage(records.subList(0, limit), records.get(limit - 1).id());
}
private void deleteSpaceData(UUID household) {
// Deleting the photo rows also enqueues both objects for removal in this transaction.
for (String table : List.of("item_photo", "item_alias", "item_move", "item_relation", "item_preference",

View File

@ -0,0 +1,2 @@
CREATE INDEX space_admin_action_recent ON space_admin_action(deleted_at DESC, id DESC);
CREATE INDEX space_admin_action_by_household ON space_admin_action(household_id, deleted_at DESC, id DESC);

View File

@ -163,6 +163,8 @@ def main():
room, room_photo = verify_location_photos(house, space, jpeg)
call("GET", "/api/admin/households", user=None, status=401)
call("GET", "/api/admin/households", status=403)
call("GET", "/api/admin/space-deletions", user=None, status=401)
call("GET", "/api/admin/space-deletions", status=403)
call("DELETE", space, user="viewer", status=403)
call("DELETE", f"/api/admin/households/{house}", status=403)
call("DELETE", space, status=202)
@ -178,6 +180,7 @@ def main():
api = f"/api/households/{another}"
admin = f"/api/admin/households/{another}"
search = "/api/admin/households?" + urlencode({"q": unique_name, "limit": 1})
audit = "/api/admin/space-deletions?" + urlencode({"householdId": another, "limit": 1})
assert call("GET", search, user="admin") == {
"spaces": [{"id": another, "name": unique_name}], "hasMore": False,
}
@ -188,9 +191,15 @@ def main():
attached = json.loads(upload(f"{api}/items/{second['id']}/photos", jpeg))["id"]
place_photo = json.loads(upload(f"{api}/locations/{place}/photos", jpeg))["id"]
assert call("GET", admin, user="admin")["photos"] == 2
assert call("GET", audit, user="admin") == {"records": [], "nextBefore": None}
call("DELETE", admin, user="admin", status=202)
assert call("GET", search, user="admin")["spaces"] == []
call("GET", api, status=404)
call("DELETE", admin, user="admin", status=404)
history = call("GET", audit, user="admin")
record, = history["records"]
assert record["householdId"] == another and record["operatorId"] and record["deletedAt"]
assert isinstance(record["id"], str) and history["nextBefore"] is None
await_absence(another, second["id"], attached)
await_absence(another, place, place_photo, "locations")
print("PASS dedicated OIDC admin client, role, audited deletion and both OSS objects")

View File

@ -1,6 +1,6 @@
# 管理后台本机预览
在 kind 中创建独立的 `item-atlas-admin-preview` 命名空间。管理员和普通账号由独立的 Keycloak realm 管理。网关和物品服务使用同一次后端候选发布的镜像。PostgreSQL 在一个独立的持久卷上,为登录和物品服务分别创建数据库和用户。
在 kind 中创建独立的 `item-atlas-admin-preview` 命名空间。管理员和普通账号由独立的 Keycloak realm 管理。网关复用后端候选发布的镜像,物品服务和后台用同一份源码构建预览镜像。PostgreSQL 在一个独立的持久卷上,为登录和物品服务分别创建数据库和用户。
```mermaid
flowchart LR
@ -17,7 +17,7 @@ flowchart LR
## 启动
在能访问 kind 的终端执行,确认当前上下文、节点镜像架构和存储类位置。已有的候选后端镜像可以直接用。新节点需按 [候选交付流程](../../docs/deployment/backend-release.md) 拉取清单中的两个后端镜像。Docker 和 kubectl 如果同在虚拟机里,以下构建与部署命令也在虚拟机中执行。
在能访问 kind 的终端执行,确认当前上下文、节点镜像架构和存储类位置。新节点需按 [候选交付流程](../../docs/deployment/backend-release.md) 拉取清单中的网关镜像。Docker 和 kubectl 如果同在虚拟机里,镜像构建与部署命令也在虚拟机中执行。
```sh
kind_cluster=atlas-dev
@ -25,10 +25,13 @@ context="kind-$kind_cluster"
namespace=item-atlas-admin-preview
secret_dir=/path/on/ssd/item-atlas-admin-preview
mvn -B -ntp -f backend/pom.xml -pl inventory-service -am package
docker build -t item-atlas-inventory-service:admin-preview-0.1.2 backend/inventory-service
docker build --build-arg VITE_OIDC_URL=/auth \
--build-arg VITE_OIDC_REALM=item-atlas-admin-preview \
-t item-atlas-admin:admin-preview-0.1.1 apps/admin
kind load docker-image --name "$kind_cluster" item-atlas-admin:admin-preview-0.1.1
-t item-atlas-admin:admin-preview-0.1.2 apps/admin
kind load docker-image --name "$kind_cluster" \
item-atlas-inventory-service:admin-preview-0.1.2 item-atlas-admin:admin-preview-0.1.2
python3 deploy/admin-preview/prepare-secrets.py "$secret_dir"
kubectl --context "$context" create namespace "$namespace"
@ -49,7 +52,7 @@ kubectl --context "$context" -n "$namespace" port-forward --address 127.0.0.1 sv
## 验收和排错
打开 [管理后台](http://127.0.0.1:18482/)。管理员可以分页查空间、按名称或完整 ID 定位、查看物品和照片数量。普通账号登录后会看到权限提示。删除请使用专用测试空间,提交后检查数据库中的 `space_admin_action`。照片记录被删除时,数据库触发器会在同一个事务登记 `media_cleanup`。本预览用于核对队列写入,真实对象清理由 [对象存储冒烟脚本](../../backend/tests/media_smoke.py) 在带存储的环境验收。
打开 [管理后台](http://127.0.0.1:18482/)。管理员可以分页查空间、按名称或完整 ID 定位、查看物品和照片数量。普通账号登录后会看到权限提示。删除请使用专用测试空间,提交后打开「删除记录」,按空间 ID 核对操作人和时间。对应数据保存在 `space_admin_action`。照片记录被删除时,数据库触发器会在同一个事务登记 `media_cleanup`。本预览用于核对队列写入,真实对象清理由 [对象存储冒烟脚本](../../backend/tests/media_smoke.py) 在带存储的环境验收。
页面打不开先查 `/healthz` 和端口转发。浏览器返回登录页时看 Keycloak 回调地址和 Nginx `/auth` 路由。管理 API 返回 `401` 时核对 issuer、JWKS 和有效期,返回 `403` 时核对客户端和管理员角色。物品服务启动时 Flyway 会等待数据库,持续失败时查看 PVC、PostgreSQL 日志及 Flyway 日志。后台 Nginx 的访问日志保留路径、状态码与响应耗时,省略包含授权码的查询参数。

View File

@ -23,7 +23,8 @@ spec:
automountServiceAccountToken: false
containers:
- name: inventory
image: git.tutudog.com/dongjf/item-atlas-inventory-service:5299e526f4aee1e619a66f3d57e464b05be7ef92
image: item-atlas-inventory-service:admin-preview-0.1.2
imagePullPolicy: Never
envFrom:
- secretRef: {name: atlas-admin-inventory}
env:

View File

@ -42,7 +42,7 @@ spec:
automountServiceAccountToken: false
containers:
- name: nginx
image: item-atlas-admin:admin-preview-0.1.1
image: item-atlas-admin:admin-preview-0.1.2
imagePullPolicy: Never
env:
- {name: ATLAS_GATEWAY_URL, value: 'http://atlas-admin-gateway:8080'}

View File

@ -6,7 +6,7 @@
| --- | --- | --- |
| H5 | uni-app(Vue 3、TypeScript、Vite),使用 DCloud 的 CLI 模板 | [移动网页](../../apps/h5/README.md)面向手机找物、照片裁剪和快速录入。构建 H5 静态文件,由独立 Nginx 镜像托管。 |
| PC 网页 | Vue 3、TypeScript、Vite、Vue Router | [桌面工作台](../../apps/pc/README.md)支持搜索、物品录入、移位和两级平面图。独立 Nginx 镜像。 |
| 管理后台 | Vue 3、TypeScript、Vite、Element Plus | [管理后台](../../apps/admin/README.md)支持按名称或 ID 查空间、分页浏览、删除及图片清理。独立 Nginx 镜像。其他管理模块有多页路由需求时接入 Vue Router。 |
| 管理后台 | Vue 3、TypeScript、Vite、Element Plus | [管理后台](../../apps/admin/README.md)支持查找和删除空间,以及按空间 ID 查看管理员删除记录。独立 Nginx 镜像。其他管理模块有多页路由需求时接入 Vue Router。 |
| iOS | Swift、SwiftUI,最低 iOS 17 | [iOS 应用](../../apps/ios/README.md)接入账号、空间、物品、草稿和相册上传。拍照和录音按后续原生端验收范围补齐。 |
| Android | Kotlin、Jetpack Compose | [Android 应用](../../apps/android/README.md)使用 Gradle,最低 Android 8.0。首版接入原生会话、空间、找物、录入和移位。 |

View File

@ -35,7 +35,7 @@ Spring Boot 负责服务本身,Spring Cloud 主要用 Gateway。正式部署
| 收藏和评分 | 按用户和物品唯一保存,用户可以改分、取消收藏或清除短评。 |
| 草稿 | 保存输入、候选项和确认状态。同一草稿版本只接受一份确认任务。 |
业务路径放在 `/api/households/{householdId}` 下。`/items`、`/locations`、`/items/{id}/moves` 和 `/items/{id}/preference` 走物品服务。`/drafts`、`/drafts/{id}/confirm` 和 `/operations/{id}` 走录入服务。社区走 `/api/community/posts`,公开标题和正文来自独立社区表。模型状态走 `/api/model-providers`,后台管理预留独立的 `/api/admin` 前缀。内部投递路径只允许服务访问。
业务路径放在 `/api/households/{householdId}` 下。`/items`、`/locations`、`/items/{id}/moves` 和 `/items/{id}/preference` 走物品服务。`/drafts`、`/drafts/{id}/confirm` 和 `/operations/{id}` 走录入服务。社区走 `/api/community/posts`,公开标题和正文来自独立社区表。模型状态走 `/api/model-providers`。后台从 `/api/admin` 管理空间和查询删除记录,由物品服务核对管理员角色。内部投递路径只允许服务访问。
## 草稿确认与分布式一致性

View File

@ -28,6 +28,8 @@ Git 发布标签使用 `vMAJOR.MINOR.PATCH`。示例 `v0.1.0-rc.6` 中,`v` 是
常规开发把功能分支推到 Gitea,合并到 `main` 后,准备一批候选时再给已确认的提交打标签。Drone 的标签事件按 `refs/tags/...` 匹配。 [Drone 触发条件](https://docs.drone.io/pipeline/triggers/)
`backend-ci` 同时运行一份。冒烟脚本会在同一 runner 上启动三个短生命周期 Java 服务,使用小堆和 Serial GC,给 PostgreSQL 与其他进程留内存。脚本失败时会输出各服务日志。部署使用的容器保留各环境自己的 JVM 配置。 [Drone 并发配置](https://docs.drone.io/yaml/docker/#the-concurrency-object) · [JDK 21 JVM 参数](https://docs.oracle.com/en/java/javase/21/docs/specs/man/java.html)
## 在哪里点部署
在 Drone 打开成功的**标签构建**,例如 [#23](https://drone.tutudog.com/dongjf/item-atlas/23),在构建操作菜单选择 **Promote**,目标填 `staging`。Drone 会另开一个构建号,打开那次运行即可看到 `deploy-staging → helm-upgrade`。工作 Mac 的 ARM64 runner 调用 Helm,Kubernetes 根据结果更新 Pod。集群控制台用于检查镜像、事件和就绪结果。 [Drone Promotion](https://docs.drone.io/promote/)