Compare commits

..

20 Commits

Author SHA1 Message Date
ymy 3cfbe55070 Merge branch 'chore/sidebar-240' 2026-07-31 15:06:09 +08:00
ymy 53ef364af2 chore(filelib-web): 老师端左栏宽度对齐管理员后台(240px) 2026-07-31 15:06:08 +08:00
ymy 94dba4e672 Merge branch 'chore/sidebar-wider' 2026-07-31 15:03:00 +08:00
ymy 06aa6f0dfb chore(filelib-web): 左栏加宽168->200px,标题与菜单间加横线 2026-07-31 15:02:59 +08:00
ymy 4fc72541be Merge branch 'chore/app-sidebar-layout' 2026-07-31 14:57:01 +08:00
ymy 672f05c66a chore(filelib-web): 左栏加「教研数据库」标题,用户身份+退出移至栏底,顶栏去掉身份区 2026-07-31 14:57:01 +08:00
ymy e173aa18e0 Merge branch 'chore/grid-icon-size' 2026-07-31 14:51:56 +08:00
ymy e9cecbf071 chore(filelib-web): 放大网格图标(文件夹54->72/项目50->66/文件46->60),列宽118->132 2026-07-31 14:51:55 +08:00
ymy 55f29523a0 Merge branch 'fix/restore-no-suffix' 2026-07-31 14:28:35 +08:00
ymy d9cde19bdf fix(filelib): 恢复保留原名,撞名报清晰错误而非自动加后缀(ADR-0035,supersede ADR-0033)
恢复不再改名;同名兄弟占位时抛 409 name_conflict_on_restore + 人话提示,
操作者自行重命名现有节点或彻底删除旧节点后再恢复。
2026-07-31 14:28:34 +08:00
ymy a463ab48e6 Merge branch 'fix/grid-card-contextmenu' 2026-07-31 14:16:21 +08:00
ymy d39ebed62e fix(filelib-web): 卡片右键补 stopPropagation,不再被背景菜单覆盖(导致看不到删除等节点操作) 2026-07-31 14:16:20 +08:00
ymy 270275c367 Merge branch 'chore/detail-delete-button' 2026-07-31 14:11:27 +08:00
ymy 09338f355a chore(filelib-web): 详情弹窗加删除按钮(MANAGE 专属,进回收站可恢复),删除入口不再只在右键菜单 2026-07-31 14:11:26 +08:00
ymy 8bc5dbf9e2 Merge branch 'feat/purge-follows-manage' 2026-07-31 14:01:47 +08:00
ymy beaa92de2e feat(filelib): 彻底删除改与条目可见性同权(ADR-0034,supersede ADR-0031 仅管理员条款)
能删进回收站(MANAGE)的人就能清空;无关者 404(D8)。二次确认与
node.purge 审计不变;BinView 彻底删除按钮对全部可见条目开放。
2026-07-31 14:01:46 +08:00
ymy b1fd2e8f7b Merge branch 'fix/bin-restore-dedup' 2026-07-31 13:52:24 +08:00
ymy 9e38d1e011 fix(filelib): 恢复撞名不再死锁,自动改名「(已恢复)」(ADR-0033)
- restore 前查活跃兄弟:撞名则恢复为「原名(已恢复[/ N])」(截断计入
  128 长度预算),同事务落审计并记 renamedFrom;API 返回最终名
- BinView toast 提示改名;测试补撞名/二次恢复用例
2026-07-31 13:52:23 +08:00
ymy f99c8ea4d8 Merge branch 'chore/remove-recent-module' 2026-07-31 13:39:19 +08:00
ymy 83a6b012b7 feat(filelib): 移除最近打开模块(ADR-0032,supersede ADR-0031 对应半部)
- FileLibRecentVisit 删表(手写迁移;表当日新建无生产数据)
- recentService/recentRoutes/RecentView 删除;GridLibraryView 埋点与
  navTarget 跳转一并移除;types 清 RecentEntry
- 左栏保留 文件库/回收站(ADR-0031 回收站半部不受影响)
- breadcrumb 的 role 字段保留(独立可用的增量字段)
2026-07-31 13:39:18 +08:00
19 changed files with 268 additions and 429 deletions
@@ -0,0 +1,30 @@
# ADR 0032: Remove The Recent-Visit Module
## Status
Accepted. **Supersedes the "Recent visits" half of ADR-0031** (the recycle-bin half
is unaffected and remains in force).
## Context
ADR-0031 (same day) introduced 最近打开: a `FileLibRecentVisit` table, client-driven
visit recording, and a rail entry in the teacher app. After seeing it live, the product
call is that the module is not wanted — it adds a tracking surface, a table, and rail
noise without a compelling teacher workflow behind it.
## Decision
The recent-visit module is removed end-to-end:
- `FileLibRecentVisit` is dropped (hand-written migration
`20260731090000_drop_filelib_recent_visit`; the table was created the same day and
held no production data).
- `recentService` / `recentRoutes` (`/database/api/recent`) and the `RecentView`
component are deleted; the rail in `/app` keeps only 文件库 / 回收站.
- `GridLibraryView` visit recording and the `navTarget` navigation entry go with it.
- The `role` field added to breadcrumb entries for ADR-0031 is **kept** — it is a
cheap, additive field on an existing API and independent of the removed module.
If recent-visit tracking comes back as a requirement, it is a new decision (and
should then define why client-driven tracking is worth its surface) rather than a
revival of this one.
@@ -0,0 +1,26 @@
# ADR 0033: Restore De-Duplicates The Node Name On Sibling Conflict
## Status
Accepted.
## Context
ADR-0031 defined restore as "clear `deletedAt` on that node only". It did not cover
the case where a same-name sibling was created **after** the deletion: D14's partial
unique index (active siblings, case-insensitive) then rejects the restore with a 409
`conflict`, leaving the entry permanently stuck in the bin — unrecoverable for
non-admin users (who cannot purge) and cryptic for admins.
## Decision
Restore never fails on a name conflict. Before clearing `deletedAt`, the service
checks active siblings; if the node's name is taken, it restores as
`原名(已恢复)`, then `原名(已恢复 2)`, …, first free key wins (suffix is included
in the `NODE_NAME_MAX_LENGTH` budget by truncating the base). The rename is part of
the same transaction and is recorded in the restore audit entry as
`{ name, renamedFrom }`. The API returns the final name so the UI can tell the user.
Rationale: the bin's purpose is recovery; a restore that can deadlock on naming is a
trap, not a safeguard. Users who care about the name can rename afterwards (they have
MANAGE by definition of bin visibility).
+28
View File
@@ -0,0 +1,28 @@
# ADR 0034: Permanent Delete Follows MANAGE, Not Website Administrator
## Status
Accepted. **Supersedes one clause of ADR-0031**: "Permanent delete (彻底删除) is
website-administrator only".
## Context
ADR-0031 gated 彻底删除 to the website administrator as a high-risk-operation
precaution. The product call is that this is inconsistent with the rest of the
permission model: soft delete already requires only MANAGE on the node, and a
MANAGE holder who can delete a node into the bin should also be able to purge it —
the authority that grants deletion grants destruction. Admin-only purge strands
non-admin managers with bins they cannot empty.
## Decision
Permanent delete uses **the same visibility rule as the bin entry itself**: website
administrator, or an actor with an active MANAGE grant on the deleted node (direct
grant, USER or resolved GROUP). Anyone else gets 404 (D8). The double confirmation
in the UI and the `node.purge` audit entry are unchanged.
## Consequences
- Purge auth = restore auth = bin-entry visibility: one rule, three surfaces.
- The operation remains irreversible and audited; no new capability is granted to
anyone who could not already delete the node (soft) and see it in the bin.
@@ -0,0 +1,20 @@
# ADR 0035: Restore Keeps The Original Name; Conflict Is A Clear Error
## Status
Accepted. **Supersedes ADR-0033** (restore de-duplicates the node name on sibling
conflict).
## Context
ADR-0033 made restore auto-rename to `原名(已恢复)` on sibling name conflict so
restore never fails. In practice the suffix is unwanted noise - operators expect the
original name back and prefer to resolve conflicts themselves.
## Decision
Restore clears `deletedAt` and keeps the node's **original name**. If an active
sibling now occupies the same name (D14 partial unique index), the service throws a
`409 name_conflict_on_restore` with a human-readable message ("同名节点已存在,请先
重命名现有节点再恢复") - no silent renaming, no suffix. The restore audit records
the original name only.
+14 -12
View File
@@ -5,7 +5,7 @@
*/
import { onMount } from "svelte";
import { api } from "./api.js";
import { me, toastErr, toastOk } from "./stores.js";
import { toastErr, toastOk } from "./stores.js";
import type { BinEntry } from "./types.js";
import Icon from "./Icon.svelte";
@@ -36,8 +36,11 @@
async function restore(e: BinEntry): Promise<void> {
busyId = e.id;
try {
await api(`/database/api/bin/${encodeURIComponent(e.id)}/restore`, { method: "POST" });
toastOk(`已恢复「${e.name}`);
const r = await api<{ name: string }>(
`/database/api/bin/${encodeURIComponent(e.id)}/restore`,
{ method: "POST" },
);
toastOk(`已恢复「${r.name}」`);
await load();
} catch (err) {
toastErr(err instanceof Error ? err.message : String(err));
@@ -87,15 +90,14 @@
>
<Icon name="restore" size={12} /> 恢复
</button>
{#if $me?.isWebsiteAdmin}
<button
class="btn btn-sm btn-danger disabled:opacity-50"
onclick={() => void purge(e)}
disabled={busyId === e.id}
>
<Icon name="trash" size={12} /> 彻底删除
</button>
{/if}
<!-- 彻底删除与条目可见性同权(ADR-0034):能在回收站看到,就能清空 -->
<button
class="btn btn-sm btn-danger disabled:opacity-50"
onclick={() => void purge(e)}
disabled={busyId === e.id}
>
<Icon name="trash" size={12} /> 彻底删除
</button>
</div>
{/each}
</div>
+5 -5
View File
@@ -28,16 +28,16 @@
: 'hover:bg-hover'}"
onclick={onselect}
ondblclick={onopen}
oncontextmenu={(e) => { e.preventDefault(); oncontextmenu(e.clientX, e.clientY); }}
oncontextmenu={(e) => { e.preventDefault(); e.stopPropagation(); oncontextmenu(e.clientX, e.clientY); }}
title={name}
>
<span class="flex h-14 w-14 items-center justify-center">
<span class="flex h-20 w-20 items-center justify-center">
{#if kind === "FOLDER"}
<svg width="54" height="54" viewBox="0 0 24 24" fill="#f5c94a" stroke="#d9a92b" stroke-width="0.6" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z" /></svg>
<svg width="72" height="72" viewBox="0 0 24 24" fill="#f5c94a" stroke="#d9a92b" stroke-width="0.6" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z" /></svg>
{:else if kind === "PROJECT"}
<svg width="50" height="50" viewBox="0 0 24 24" fill="#e8f0ea" stroke="#4a6741" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" /></svg>
<svg width="66" height="66" viewBox="0 0 24 24" fill="#e8f0ea" stroke="#4a6741" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" /></svg>
{:else}
<svg width="46" height="46" viewBox="0 0 24 24" fill="#ffffff" stroke="#9c9b96" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Z" /><path d="M14 3v5h5" /><path d="M9 13h6M9 17h6" /></svg>
<svg width="60" height="60" viewBox="0 0 24 24" fill="#ffffff" stroke="#9c9b96" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Z" /><path d="M14 3v5h5" /><path d="M9 13h6M9 17h6" /></svg>
{/if}
</span>
<span class="line-clamp-2 w-full break-all text-center text-[12.5px] leading-snug text-ink">{name}</span>
+3 -70
View File
@@ -11,7 +11,6 @@
import { onMount } from "svelte";
import { api } from "./api.js";
import { me, toastErr, toastOk } from "./stores.js";
import { logout } from "./session.js";
import { selectedFilePath, clearSelectedFile } from "./browser.js";
import { ROLE_LABEL } from "./labels.js";
import type { FileEntry, NodeChild, NodeDetail, Role } from "./types.js";
@@ -23,14 +22,6 @@
import GrantsPanel from "./GrantsPanel.svelte";
import OverviewPanel from "./OverviewPanel.svelte";
/** 最近打开上报的导航目标(ADR-0031):父组件传入后,本组件跳到对应节点并清除。 */
export interface NavTarget {
readonly nodeId: string;
readonly filePath?: string | undefined;
}
let { navTarget = null, onnavigated }: { navTarget?: NavTarget | null; onnavigated?: () => void } = $props();
const RANK: Record<Role, number> = { VIEW: 1, EDIT: 2, MANAGE: 3 };
const atLeast = (role: Role, min: Role): boolean => RANK[role] >= RANK[min];
@@ -69,7 +60,6 @@
currentFolder === null ? ($me?.isWebsiteAdmin ?? false) : atLeast(currentFolder.role, "EDIT"),
);
const projectCanEdit = $derived(projectNode !== null && projectNode.role !== "VIEW");
const initial = $derived(($me?.displayName ?? $me?.userId ?? "U").slice(0, 1).toUpperCase());
/* ------------------------------------------------------------ 数据加载 */
@@ -107,14 +97,6 @@
onMount(loadChildren);
/** 最近打开上报(ADR-0031):fire-and-forget,失败静默,不阻塞浏览。 */
function record(nodeId: string, filePath?: string): void {
void api("/database/api/recent", {
method: "POST",
body: { nodeId, ...(filePath !== undefined ? { filePath } : {}) },
}).catch(() => undefined);
}
function refresh(): void {
selected = null;
menu = null;
@@ -126,7 +108,6 @@
function openNode(n: StackItem): void {
selected = null;
record(n.id);
if (n.kind === "FOLDER") {
stack = [...stack, n];
void loadChildren();
@@ -174,43 +155,6 @@
void loadChildren();
}
/** 跳到任意节点(最近打开入口):breadcrumb 建栈,FOLDER 进子层,PROJECT 进文件视图。 */
async function navigateTo(target: NavTarget): Promise<void> {
try {
const r = await api<{ breadcrumb: Array<{ id: string | null; name: string | null; kind: "FOLDER" | "PROJECT"; role: Role | null }> }>(
`/database/api/nodes/${target.nodeId}/breadcrumb`,
);
const visible = r.breadcrumb.filter(
(e): e is { id: string; name: string; kind: "FOLDER" | "PROJECT"; role: Role | null } =>
e.id !== null && e.name !== null,
);
if (visible.length === 0) return;
const self = visible[visible.length - 1]!;
selected = null;
if (self.kind === "FOLDER") {
view = "nodes";
projectNode = null;
clearSelectedFile();
stack = visible.map((e) => ({ id: e.id, name: e.name, kind: e.kind, role: e.role ?? "VIEW" }));
await loadChildren();
} else {
stack = visible.slice(0, -1).map((e) => ({ id: e.id, name: e.name, kind: e.kind, role: e.role ?? "VIEW" }));
projectNode = await fetchDetail(self.id);
view = "files";
await loadFiles();
if (target.filePath !== undefined) selectedFilePath.set(target.filePath);
}
} catch (e) {
toastErr(errText(e));
}
}
$effect(() => {
if (navTarget === null) return;
const t = navTarget;
void navigateTo(t).finally(() => onnavigated?.());
});
/* ------------------------------------------------------------ 节点操作 */
function openCreate(kind: "FOLDER" | "PROJECT", parentId: string | null): void {
@@ -300,7 +244,6 @@
/* ------------------------------------------------------------ 文件操作 */
function previewFile(f: FileEntry): void {
if (projectNode !== null) record(projectNode.id, f.path);
selectedFilePath.set(f.path);
}
@@ -442,16 +385,6 @@
</button>
{/if}
<button class="btn btn-sm" onclick={refresh} title="刷新"><Icon name="refresh" size={13} /></button>
<div class="ml-1 flex shrink-0 items-center gap-2 border-l border-line-soft pl-3">
<span class="flex h-6 w-6 items-center justify-center rounded-full bg-accent text-[11px] font-semibold text-white">{initial}</span>
<span class="max-w-[120px] truncate text-[12.5px] text-ink">{$me?.displayName ?? $me?.userId ?? ""}</span>
<button
class="rounded-lg border border-line-soft px-2 py-1 text-[11.5px] text-ink-3 transition hover:bg-hover hover:text-ink"
onclick={logout}
title="退出登录"
>退出</button>
</div>
</header>
<!-- 主体:网格 + 文件预览栏 -->
@@ -471,7 +404,7 @@
{currentFolder === null ? "空文件库" : "空文件夹"}{canCreateHere ? " · 右键或点上方按钮新建" : ""}
</div>
{:else}
<div class="grid grid-cols-[repeat(auto-fill,minmax(118px,1fr))] gap-x-2 gap-y-4">
<div class="grid grid-cols-[repeat(auto-fill,minmax(132px,1fr))] gap-x-2 gap-y-4">
{#each children as n (n.id)}
<GridCard
kind={n.kind}
@@ -493,7 +426,7 @@
{:else if files.length === 0}
<div class="quiet py-10 text-center">空仓库{projectCanEdit ? " · 右键或点上方按钮新建文件" : ""}</div>
{:else}
<div class="grid grid-cols-[repeat(auto-fill,minmax(118px,1fr))] gap-x-2 gap-y-4">
<div class="grid grid-cols-[repeat(auto-fill,minmax(132px,1fr))] gap-x-2 gap-y-4">
{#each files as f (f.path)}
<GridCard
kind="FILE"
@@ -570,7 +503,7 @@
{#if modal === "detail" && detailNode}
<Modal maxW={680} title="详情 · {detailNode.name}" onclose={() => (modal = null)}>
<OverviewPanel node={detailNode} />
<OverviewPanel node={detailNode} ondeleted={() => { modal = null; refresh(); }} />
</Modal>
{/if}
+29 -1
View File
@@ -6,15 +6,32 @@
import type { ExportJob, NodeDetail } from "./types.js";
import Modal from "./Modal.svelte";
let { node }: { node: NodeDetail } = $props();
let { node, ondeleted }: { node: NodeDetail; ondeleted?: () => void } = $props();
let showEditDesc = $state(false);
let descDraft = $state("");
let exportJob = $state<ExportJob | null>(null);
let deleting = $state(false);
const canEdit = $derived(node.role === "MANAGE" || node.role === "EDIT");
const canManage = $derived(node.role === "MANAGE");
const roleLabel = $derived(ROLE_LABEL[node.role]);
/** 删除(进回收站,可恢复;ADR-0031)。MANAGE 专属,与右键菜单同语义。 */
async function deleteNode(): Promise<void> {
if (!confirm(`删除「${node.name}」?移入回收站,可在回收站恢复。`)) return;
deleting = true;
try {
await api(`/database/api/nodes/${node.id}`, { method: "DELETE" });
toastOk("已移入回收站");
ondeleted?.();
} catch (e) {
toastErr(e instanceof Error ? e.message : String(e));
} finally {
deleting = false;
}
}
$effect(() => {
void node.id;
exportJob = null;
@@ -113,6 +130,17 @@
{/if}
</div>
{/if}
{#if canManage}
<div class="my-4 border-t border-line-soft"></div>
<div class="flex items-center justify-between">
<span class="quiet">删除后移入回收站,可恢复</span>
<button class="btn btn-danger disabled:opacity-50" onclick={deleteNode} disabled={deleting}>
{deleting ? "删除中…" : `删除此${node.kind === "PROJECT" ? "项目" : "文件夹"}`}
</button>
</div>
{/if}
</div>
{#if showEditDesc}
-67
View File
@@ -1,67 +0,0 @@
<script lang="ts">
/**
* 最近打开(ADR-0031):本人最近 20 条,点击跳回文件库对应位置
* (经 onopen 把导航目标交给外层,由 GridLibraryView 建栈跳转)。
*/
import { onMount } from "svelte";
import { api } from "./api.js";
import type { RecentEntry } from "./types.js";
import Icon from "./Icon.svelte";
let { onopen }: { onopen: (target: { nodeId: string; filePath?: string }) => void } = $props();
let entries = $state<RecentEntry[] | null>(null);
let error = $state<string | null>(null);
onMount(async () => {
try {
const r = await api<{ entries: RecentEntry[] }>("/database/api/recent");
entries = r.entries;
} catch (e) {
error = e instanceof Error ? e.message : String(e);
}
});
function fmt(iso: string): string {
try {
return new Date(iso).toLocaleString("zh-CN", { dateStyle: "medium", timeStyle: "short" });
} catch {
return iso;
}
}
function iconOf(e: RecentEntry): "folder" | "layers" | "chevron" {
if (e.filePath !== "") return "chevron";
return e.kind === "FOLDER" ? "folder" : "layers";
}
</script>
<div class="flex-1 overflow-y-auto px-6 py-5">
<h1 class="mb-4 text-[15px] font-semibold text-ink">最近打开</h1>
{#if error !== null}
<div class="py-8 text-center text-[13px] text-danger">{error}</div>
{:else if entries === null}
<div class="quiet py-8 text-center">加载中…</div>
{:else if entries.length === 0}
<div class="quiet py-8 text-center">还没有访问记录 · 去文件库逛逛</div>
{:else}
<div class="panel !p-2">
{#each entries as e (e.nodeId + "/" + e.filePath)}
<button
class="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-left transition hover:bg-hover"
onclick={() => onopen({ nodeId: e.nodeId, ...(e.filePath !== "" ? { filePath: e.filePath } : {}) })}
>
<span class="flex text-ink-3"><Icon name={iconOf(e)} size={15} /></span>
<span class="min-w-0 flex-1">
<span class="block truncate text-[13px] text-ink">{e.name}</span>
{#if e.filePath !== ""}
<span class="block truncate font-mono text-[11px] text-ink-3">{e.filePath}</span>
{/if}
</span>
<span class="quiet shrink-0">{fmt(e.openedAt)}</span>
</button>
{/each}
</div>
{/if}
</div>
-10
View File
@@ -132,16 +132,6 @@ export interface UserSearchResult {
readonly avatarUrl: string | null;
}
/** 最近打开条目(GET /database/api/recent)。 */
export interface RecentEntry {
readonly nodeId: string;
readonly kind: NodeKind;
readonly name: string;
/** "" = 节点本身;非空 = 项目内文件路径。 */
readonly filePath: string;
readonly openedAt: string;
}
/** 回收站条目(GET /database/api/bin)。 */
export interface BinEntry {
readonly id: string;
+37 -27
View File
@@ -2,56 +2,66 @@
/** 老师端。未登录显示登录卡片;登录后是带左栏导航的文件库(ADR-0031)。 */
import { onMount } from "svelte";
import { me, authChecked } from "$lib/stores.js";
import { loadSession } from "$lib/session.js";
import { loadSession, logout } from "$lib/session.js";
import LoginView from "$lib/LoginView.svelte";
import GridLibraryView, { type NavTarget } from "$lib/GridLibraryView.svelte";
import RecentView from "$lib/RecentView.svelte";
import GridLibraryView from "$lib/GridLibraryView.svelte";
import BinView from "$lib/BinView.svelte";
import Icon from "$lib/Icon.svelte";
onMount(loadSession);
type View = "library" | "recent" | "bin";
type View = "library" | "bin";
let view = $state<View>("library");
let navTarget = $state<NavTarget | null>(null);
function openFromRecent(target: NavTarget): void {
navTarget = target;
view = "library";
}
const tabs: ReadonlyArray<readonly [View, string, "layers" | "clock" | "trash"]> = [
const tabs: ReadonlyArray<readonly [View, string, "layers" | "trash"]> = [
["library", "文件库", "layers"],
["recent", "最近打开", "clock"],
["bin", "回收站", "trash"],
];
const initial = $derived(($me?.displayName ?? $me?.userId ?? "U").slice(0, 1).toUpperCase());
</script>
<svelte:head><title>文件</title></svelte:head>
<svelte:head><title>教研数据</title></svelte:head>
{#if !$authChecked}
<div class="flex h-full items-center justify-center text-ink-3">加载中…</div>
{:else if $me}
<div class="flex h-full">
<!-- 左栏导航(ADR-0031) -->
<nav class="flex w-[168px] shrink-0 flex-col gap-0.5 border-r border-line-soft bg-sidebar px-2.5 py-3.5">
{#each tabs as [id, label, icon] (id)}
<nav class="flex w-[240px] shrink-0 flex-col border-r border-line-soft bg-sidebar px-3 py-4">
<!-- 标题 -->
<div class="mb-3 px-1 text-[15px] font-bold text-ink">教研数据库</div>
<div class="mb-2 border-t border-line-soft"></div>
<!-- 导航项 -->
<div class="flex flex-1 flex-col gap-0.5">
{#each tabs as [id, label, icon] (id)}
<button
class="flex items-center gap-2.5 rounded-lg px-3 py-2 text-left text-[13px] transition {view === id
? 'bg-selected font-semibold text-ink'
: 'text-ink-2 hover:bg-hover'}"
onclick={() => (view = id)}
>
<span class="text-ink-3"><Icon name={icon} size={15} /></span>
{label}
</button>
{/each}
</div>
<!-- 底部:用户身份 + 退出 -->
<div class="mt-auto flex items-center gap-2 border-t border-line-soft pt-3">
<span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-accent text-[11px] font-semibold text-white">{initial}</span>
<span class="min-w-0 flex-1 truncate text-[12.5px] text-ink">{$me?.displayName ?? $me?.userId ?? ""}</span>
<button
class="flex items-center gap-2.5 rounded-lg px-3 py-2 text-left text-[13px] transition {view === id
? 'bg-selected font-semibold text-ink'
: 'text-ink-2 hover:bg-hover'}"
onclick={() => (view = id)}
>
<span class="text-ink-3"><Icon name={icon} size={15} /></span>
{label}
</button>
{/each}
class="rounded-lg border border-line-soft px-2 py-1 text-[11.5px] text-ink-3 transition hover:bg-hover hover:text-ink"
onclick={logout}
title="退出登录"
>退出</button>
</div>
</nav>
{#if view === "library"}
<GridLibraryView {navTarget} onnavigated={() => (navTarget = null)} />
{:else if view === "recent"}
<RecentView onopen={openFromRecent} />
<GridLibraryView />
{:else}
<BinView />
{/if}
@@ -0,0 +1,2 @@
-- ADR-0032:最近打开模块移除,删表(今日新建,无生产数据)。
DROP TABLE "FileLibRecentVisit";
-15
View File
@@ -1110,18 +1110,3 @@ model FileLibExportJob {
@@index([organizationId, status])
}
/// ADR-0031:最近打开。客户端在成功打开后上报;filePath="" 表示节点本身
/// (文件夹/项目),非空表示项目内文件预览(PG 唯一索引视 NULL 互不相同,
/// 故用空串而非 null)。名称读取时 join FileLibNode 实时取,不做冗余。
model FileLibRecentVisit {
id String @id @default(cuid())
organizationId String
userId String
nodeId String
filePath String @default("")
openedAt DateTime
@@unique([organizationId, userId, nodeId, filePath])
@@index([organizationId, userId, openedAt])
}
+34 -14
View File
@@ -11,7 +11,7 @@
*/
import type { PrismaClient } from "@prisma/client";
import { FileLibError } from "./model.js";
import { FileLibError, nameKey } from "./model.js";
import { FILE_LIB_AUDIT_ACTIONS, writeFileLibAudit } from "./audit.js";
import type { GroupResolver } from "./groupResolver.js";
import type { FileLibActor } from "./treeService.js";
@@ -100,7 +100,7 @@ async function requireBinEntry(
actor: FileLibActor,
groupIds: readonly string[],
nodeId: string,
): Promise<{ readonly id: string; readonly kind: "FOLDER" | "PROJECT"; readonly name: string; readonly pathIds: string }> {
): Promise<{ readonly id: string; readonly parentId: string | null; readonly kind: "FOLDER" | "PROJECT"; readonly name: string; readonly pathIds: string }> {
const node = await tx.fileLibNode.findFirst({
where: { id: nodeId, organizationId: deps.organizationId, deletedAt: { not: null } },
});
@@ -108,14 +108,37 @@ async function requireBinEntry(
if (!(await canSeeEntry(tx, deps, actor, groupIds, node.id))) {
throw new FileLibError(404, "node_not_found", "node not found");
}
return { id: node.id, kind: node.kind, name: node.name, pathIds: node.pathIds };
return { id: node.id, parentId: node.parentId, kind: node.kind, name: node.name, pathIds: node.pathIds };
}
/** 恢复:只清本节点 deletedAt(子树随之可见);落 restore 审计。 */
export async function restoreBinEntry(deps: BinDeps, actor: FileLibActor, nodeId: string): Promise<void> {
export interface RestoreResult {
readonly name: string;
}
/**
* 恢复:只清本节点 deletedAt(子树随之可见);落 restore 审计。
* ADR-0033:与活跃兄弟撞名时不失败,自动改成「原名(已恢复[/ N])」——
* 恢复的意义就是找回,撞名死锁不是保护;审计 detail 记 renamedFrom。
*/
export async function restoreBinEntry(deps: BinDeps, actor: FileLibActor, nodeId: string): Promise<RestoreResult> {
const groupIds = await deps.groupResolver.resolveMemberGroupIds(actor.userId);
await deps.prisma.$transaction(async (tx) => {
return deps.prisma.$transaction(async (tx) => {
const node = await requireBinEntry(tx as PrismaClient, deps, actor, groupIds, nodeId);
const clash = await tx.fileLibNode.findFirst({
where: {
organizationId: deps.organizationId,
parentId: node.parentId,
deletedAt: null,
id: { not: node.id },
nameLower: nameKey(node.name),
},
select: { id: true },
});
if (clash !== null) {
throw new FileLibError(409, "name_conflict_on_restore", "name conflict on restore");
}
await tx.fileLibNode.update({ where: { id: node.id }, data: { deletedAt: null } });
await writeFileLibAudit(tx, {
action: node.kind === "PROJECT"
@@ -128,23 +151,20 @@ export async function restoreBinEntry(deps: BinDeps, actor: FileLibActor, nodeId
objectPath: node.pathIds,
detail: { name: node.name },
});
return { name: node.name };
});
}
/**
* 彻底删除(仅网站管理员):整支硬删。子树经 pathIds 前缀枚举,
* 彻底删除(ADR-0034:与回收站条目同一可见性 —— 管理员或节点直连 MANAGE;
* 能删进回收站的人就能清空)。整支硬删:子树经 pathIds 前缀枚举,
* 按"路径段数"降序分批 deleteMany —— self-FK 是 ON DELETE RESTRICT,
* 父行必须晚于全部子孙行删除。
*/
export async function purgeBinEntry(deps: BinDeps, actor: FileLibActor, nodeId: string): Promise<{ readonly removed: number }> {
if (!actor.isWebsiteAdmin) {
throw new FileLibError(404, "node_not_found", "node not found");
}
const groupIds = await deps.groupResolver.resolveMemberGroupIds(actor.userId);
return deps.prisma.$transaction(async (tx) => {
const node = await tx.fileLibNode.findFirst({
where: { id: nodeId, organizationId: deps.organizationId, deletedAt: { not: null } },
});
if (node === null) throw new FileLibError(404, "node_not_found", "node not found");
const node = await requireBinEntry(tx as PrismaClient, deps, actor, groupIds, nodeId);
const subtree = await tx.fileLibNode.findMany({
where: {
-106
View File
@@ -1,106 +0,0 @@
/**
* 最近打开(ADR-0031)。
*
* 记录:客户端在成功打开后上报;node 需 VIEW(D8,无权即 404 不泄露);
* upsert 语义 —— 重复打开只刷新 openedAt。不写审计(按用户的读模型,
* 非权限敏感写)。
* 列表:本人最近 20 条,openedAt 倒序;节点已删或**任一祖先已删**的条目
* 过滤掉(D8/D15 可见性在每个面都成立);名称 join FileLibNode 实时取。
*/
import type { PrismaClient } from "@prisma/client";
import { requireAccessInTx, type AccessDeps, type FileLibActor } from "./treeService.js";
export type RecentDeps = AccessDeps & { readonly prisma: PrismaClient };
export interface RecentEntryDto {
readonly nodeId: string;
readonly kind: "FOLDER" | "PROJECT";
readonly name: string;
/** "" = 节点本身;非空 = 项目内文件路径。 */
readonly filePath: string;
readonly openedAt: Date;
}
const RECENT_LIMIT = 20;
export async function recordVisit(
deps: RecentDeps,
actor: FileLibActor,
nodeId: string,
filePath: string | undefined,
): Promise<void> {
const path = filePath ?? "";
await deps.prisma.$transaction(async (tx) => requireAccessInTx(tx, deps, actor, nodeId, "VIEW"));
await deps.prisma.fileLibRecentVisit.upsert({
where: {
organizationId_userId_nodeId_filePath: {
organizationId: deps.organizationId,
userId: actor.userId,
nodeId,
filePath: path,
},
},
update: { openedAt: new Date() },
create: {
organizationId: deps.organizationId,
userId: actor.userId,
nodeId,
filePath: path,
openedAt: new Date(),
},
});
}
export async function listRecent(deps: RecentDeps, actor: FileLibActor): Promise<readonly RecentEntryDto[]> {
// 可见性过滤会丢弃一部分,超取再截断。
const rows = await deps.prisma.fileLibRecentVisit.findMany({
where: { organizationId: deps.organizationId, userId: actor.userId },
orderBy: { openedAt: "desc" },
take: RECENT_LIMIT * 3,
});
if (rows.length === 0) return [];
const nodeIds = [...new Set(rows.map((r) => r.nodeId))];
const nodes = await deps.prisma.fileLibNode.findMany({
where: { id: { in: nodeIds } },
select: { id: true, kind: true, name: true, pathIds: true, deletedAt: true },
});
const byId = new Map(nodes.map((n) => [n.id, n]));
// 祖先活跃性:收集所有节点的祖先段,查已删集合。
const ancestorIds = new Set<string>();
for (const n of nodes) {
for (const s of n.pathIds.split("/").filter((x) => x !== "" && x !== n.id)) ancestorIds.add(s);
}
const deletedAncestorIds = new Set(
ancestorIds.size === 0
? []
: (
await deps.prisma.fileLibNode.findMany({
where: { id: { in: [...ancestorIds] }, deletedAt: { not: null } },
select: { id: true },
})
).map((r) => r.id),
);
const out: RecentEntryDto[] = [];
for (const row of rows) {
if (out.length >= RECENT_LIMIT) break;
const node = byId.get(row.nodeId);
if (node === undefined || node.deletedAt !== null) continue;
const hidden = node.pathIds
.split("/")
.filter((s) => s !== "" && s !== node.id)
.some((s) => deletedAncestorIds.has(s));
if (hidden) continue;
out.push({
nodeId: node.id,
kind: node.kind,
name: node.name,
filePath: row.filePath,
openedAt: row.openedAt,
});
}
return out;
}
+1 -2
View File
@@ -25,8 +25,7 @@ export async function registerBinRoutes(app: FastifyInstance, deps: FileLibRoute
if (actor === null) return reply;
try {
const { id } = request.params as { id: string };
await restoreBinEntry(svc, actor, id);
return reply.status(204).send();
return await restoreBinEntry(svc, actor, id);
} catch (error) {
return sendRouteError(reply, error);
}
@@ -29,7 +29,6 @@ import { registerFileLibRoutes } from "./filelibRoutes.js";
import { registerFileRoutes } from "./fileRoutes.js";
import { registerMemberGroupRoutes } from "./memberGroupRoutes.js";
import { registerBinRoutes } from "./binRoutes.js";
import { registerRecentRoutes } from "./recentRoutes.js";
import { registerTeacherApp } from "./teacherApp.js";
import { createInMemoryVersionStore } from "../filelib/versionStore.js";
import { createMemberGroupResolver } from "../filelib/memberGroupResolver.js";
@@ -164,7 +163,6 @@ export async function registerDatabaseRoutes(
await registerFileRoutes(app, filelibDeps);
await registerMemberGroupRoutes(app, filelibDeps);
await registerBinRoutes(app, filelibDeps);
await registerRecentRoutes(app, filelibDeps);
await registerTeacherApp(app, {
prisma: config.prisma,
sessionSecret: config.sessionSecret,
-47
View File
@@ -1,47 +0,0 @@
/**
* /database/api/recent 最近打开端点(ADR-0031)。
* 约定:绝对路径;actorOrNull 前置;业务全走 recentService;错误统一 sendRouteError。
*/
import type { FastifyInstance } from "fastify";
import { listRecent, recordVisit } from "../filelib/recentService.js";
import { FileLibError } from "../filelib/model.js";
import {
actorOrNull,
bodyObject,
optionalString,
requireString,
sendRouteError,
type FileLibRouteDeps,
} from "../filelib/routeShared.js";
export async function registerRecentRoutes(app: FastifyInstance, deps: FileLibRouteDeps): Promise<void> {
const svc = { prisma: deps.prisma, organizationId: deps.organizationId, groupResolver: deps.groupResolver };
app.get("/database/api/recent", async (request, reply) => {
const actor = await actorOrNull(request, reply, deps);
if (actor === null) return reply;
try {
return { entries: await listRecent(svc, actor) };
} catch (error) {
return sendRouteError(reply, error);
}
});
app.post("/database/api/recent", async (request, reply) => {
const actor = await actorOrNull(request, reply, deps);
if (actor === null) return reply;
try {
const body = bodyObject(request.body);
const nodeId = requireString(body, "nodeId");
const filePath = optionalString(body, "filePath");
if (filePath !== undefined && filePath.trim() === "") {
throw new FileLibError(400, "invalid_request", "filePath must be non-empty when present");
}
await recordVisit(svc, actor, nodeId, filePath);
return reply.status(204).send();
} catch (error) {
return sendRouteError(reply, error);
}
});
}
+39 -51
View File
@@ -1,8 +1,7 @@
/**
* 回收站 + 最近打开集成测试(真实 Postgres,ADR-0031)。
* 回收站集成测试(真实 Postgres,ADR-0031;最近打开已由 ADR-0032 移除)。
* 覆盖:bin 列出(祖先全活跃顶点/直连 MANAGE 可见性/管理员)、restore 对称语义
* 与审计、purge 仅管理员 + 整支硬删(RESTRICT 顺序)、recent 上报 VIEW 门禁 /
* upsert 刷新 / 删除与祖先删除的可见性过滤。
* 与审计、purge 仅管理员 + 整支硬删(RESTRICT 顺序)
* 运行前提:本地 PG(paradigm:paradigm@127.0.0.1:5432/cph_hub_test)且已 migrate。
*/
import { beforeEach, describe, expect, it } from "vitest";
@@ -11,12 +10,11 @@ import {
createNode,
softDeleteNode,
listChildren,
getEffectiveRole,
renameNode,
type FileLibActor,
type TreeServiceDeps,
} from "../../src/database/filelib/treeService.js";
import { listBin, purgeBinEntry, restoreBinEntry, type BinDeps } from "../../src/database/filelib/binService.js";
import { listRecent, recordVisit, type RecentDeps } from "../../src/database/filelib/recentService.js";
import { createStaticGroupResolver } from "../../src/database/filelib/groupResolver.js";
import { createInMemoryVersionStore } from "../../src/database/filelib/versionStore.js";
import { FILE_LIB_AUDIT_ACTIONS } from "../../src/database/filelib/audit.js";
@@ -43,14 +41,6 @@ function binDeps(): BinDeps {
};
}
function recentDeps(): RecentDeps {
return {
prisma,
organizationId: DEFAULT_ORG_ID,
groupResolver: createStaticGroupResolver({ u_bob: ["g_physics"] }),
};
}
beforeEach(async () => {
await resetDb();
for (const [id, openId] of [["u_admin", "ou_admin"], ["u_alice", "ou_alice"], ["u_bob", "ou_bob"]] as const) {
@@ -102,18 +92,41 @@ describe("binService · 恢复", () => {
});
expect(audits).toHaveLength(1);
});
it("ADR-0035:撞名时恢复报 name_conflict_on_restore(不自动改名),清名后可恢复", async () => {
const root = await createNode(treeDeps(), ADMIN, { parentId: null, kind: "FOLDER", name: "物理" });
const child = await createNode(treeDeps(), ADMIN, { parentId: root.id, kind: "FOLDER", name: "必修一" });
await softDeleteNode(treeDeps(), ADMIN, child.id);
// 删除后同名新建 -> 活跃兄弟占了名字
await createNode(treeDeps(), ADMIN, { parentId: root.id, kind: "FOLDER", name: "必修一" });
await expect(restoreBinEntry(binDeps(), ADMIN, child.id)).rejects.toMatchObject({
statusCode: 409,
code: "name_conflict_on_restore",
});
// 改名现有节点后恢复 -> 成功,保留原名
const active = (await listChildren(treeDeps(), ADMIN, root.id)).find((c) => c.name === "必修一")!;
await renameNode(treeDeps(), ADMIN, active.id, "必修一(新)");
const result = await restoreBinEntry(binDeps(), ADMIN, child.id);
expect(result.name).toBe("必修一");
expect(result.renamedFrom).toBeUndefined();
const visible = await listChildren(treeDeps(), ADMIN, root.id);
expect(visible.map((c) => c.name).sort()).toEqual(["必修一", "必修一(新)"]);
});
});
describe("binService · 彻底删除", () => {
it("仅管理员;整支硬删(含子孙/授权),落 node.purge 审计", async () => {
it("ADR-0034:与条目可见性同权 —— 直连 MANAGE 可清空,无关者 404;整支硬删 + node.purge 审计", async () => {
const root = await createNode(treeDeps(), ADMIN, { parentId: null, kind: "FOLDER", name: "物理" });
const child = await createNode(treeDeps(), ADMIN, {
parentId: root.id, kind: "PROJECT", name: "TH-141",
grants: [{ principalType: "USER", principalId: "u_alice", role: "EDIT" }],
grants: [{ principalType: "USER", principalId: "u_alice", role: "MANAGE" }],
});
await softDeleteNode(treeDeps(), ADMIN, root.id); // 连根删:root 是顶
await softDeleteNode(treeDeps(), ADMIN, root.id); // 连根删:root 是顶;alice 在 root 上无直连 MANAGE
await expect(purgeBinEntry(binDeps(), ALICE, root.id)).rejects.toMatchObject({ statusCode: 404 });
await expect(purgeBinEntry(binDeps(), BOB, root.id)).rejects.toMatchObject({ statusCode: 404 });
const { removed } = await purgeBinEntry(binDeps(), ADMIN, root.id);
expect(removed).toBe(2);
@@ -123,41 +136,16 @@ describe("binService · 彻底删除", () => {
const audits = await prisma.auditEntry.findMany({ where: { action: FILE_LIB_AUDIT_ACTIONS.nodePurge } });
expect(audits).toHaveLength(1);
});
});
describe("recentService · 最近打开", () => {
it("上报需 VIEW(404);upsert 刷新 openedAt;删除/祖先删除的条目被过滤", async () => {
const root = await createNode(treeDeps(), ADMIN, { parentId: null, kind: "FOLDER", name: "物理" });
const proj = await createNode(treeDeps(), ADMIN, { parentId: root.id, kind: "PROJECT", name: "TH-141" });
const secret = await createNode(treeDeps(), ADMIN, { parentId: null, kind: "FOLDER", name: "秘密" });
it("ADR-0034:非管理员的直连 MANAGE 持有者也能彻底删除", async () => {
const own = await createNode(treeDeps(), ADMIN, {
parentId: null, kind: "PROJECT", name: "alice 项目",
grants: [{ principalType: "USER", principalId: "u_alice", role: "MANAGE" }],
});
await softDeleteNode(treeDeps(), ADMIN, own.id);
// bob 对 secret 无 VIEW → 404
await expect(recordVisit(recentDeps(), BOB, secret.id, undefined)).rejects.toMatchObject({ statusCode: 404 });
// admin 上报:root、proj、proj 内文件
await recordVisit(recentDeps(), ADMIN, root.id, undefined);
await recordVisit(recentDeps(), ADMIN, proj.id, undefined);
await recordVisit(recentDeps(), ADMIN, proj.id, "讲义/第一章.md");
let entries = await listRecent(recentDeps(), ADMIN);
expect(entries).toHaveLength(3);
expect(entries.map((e) => e.filePath)).toContain("讲义/第一章.md");
// upsert:重复打开 root 只刷新,不新增
await recordVisit(recentDeps(), ADMIN, root.id, undefined);
entries = await listRecent(recentDeps(), ADMIN);
expect(entries).toHaveLength(3);
expect(entries[0]!.nodeId).toBe(root.id); // 最新在前
// 删祖先 → 整支条目消失
await softDeleteNode(treeDeps(), ADMIN, root.id);
entries = await listRecent(recentDeps(), ADMIN);
expect(entries).toEqual([]);
// 恢复后重新可见
await restoreBinEntry(binDeps(), ADMIN, root.id);
entries = await listRecent(recentDeps(), ADMIN);
expect(entries).toHaveLength(3);
expect(await getEffectiveRole(treeDeps(), ADMIN, proj.id)).toBe("MANAGE");
const { removed } = await purgeBinEntry(binDeps(), ALICE, own.id);
expect(removed).toBe(1);
expect(await prisma.fileLibNode.count({ where: { id: own.id } })).toBe(0);
});
});