Merge pull request #92 from shumaiOne/feat/recently-deleted-empty-trash

feat(trash): add recently-deleted banner and empty trash option for admin
This commit is contained in:
Yiling-J
2026-06-11 16:58:30 +08:00
committed by GitHub
6 changed files with 348 additions and 19 deletions
+19
View File
@@ -177,4 +177,23 @@ describe('project api', () => {
creatorId: 'user1',
})
})
it('POST /projects/:projectId/empty-trash', async () => {
vi.mocked(assetService.emptyTrash).mockResolvedValue(undefined)
const res = await app.request('/projects/p1/empty-trash', {
method: 'POST',
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual({ success: true })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.Project,
id: 'p1',
})
expect(assetService.emptyTrash).toHaveBeenCalledWith('p1')
})
})
+15
View File
@@ -80,6 +80,21 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(resp)
},
)
.post('/projects/:projectId/empty-trash', async (c) => {
const projectId = c.req.param('projectId')
const user = c.get('user')
await authzService.hasPermission({
user,
permission: Permission.Admin,
type: ResourceType.Project,
id: projectId,
})
await assetService.emptyTrash(projectId)
return c.json({ success: true })
})
.get('/teams/:teamId/projects', zValidator('query', listProjectsRequestSchema), async (c) => {
const teamId = c.req.param('teamId')
const user = c.get('user')
+209
View File
@@ -1883,4 +1883,213 @@ describe('AssetService — natural sort by name', () => {
expect(result).toHaveLength(1)
})
})
describe('emptyTrash', () => {
it('should permanently delete trashed assets of the target project only', async () => {
const { s3Service } = await import('../s3/s3')
const team = await prisma.team.create({ data: { name: 'Empty Trash Team' } })
const project1 = await prisma.project.create({
data: { name: 'Project 1', teamId: team.id },
})
const project2 = await prisma.project.create({
data: { name: 'Project 2', teamId: team.id },
})
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-${Date.now()}@example.com` },
})
// 1. Create a trashed folder with a child file in Project 1
const folderA = await prisma.asset.create({
data: {
name: 'Folder A',
type: AssetType.folder,
status: 'trashed',
isDeleted: true,
project: { connect: { id: project1.id } },
creator: { connect: { id: user.id } },
deletedAt: new Date(),
},
})
const fileA1 = await prisma.asset.create({
data: {
name: 'File A1',
type: AssetType.file,
status: 'uploaded',
isDeleted: true,
project: { connect: { id: project1.id } },
parent: { connect: { id: folderA.id } },
creator: { connect: { id: user.id } },
storageKey: {
create: {
key: 'files/project1-trashed/raw',
createdAt: new Date(Date.now() - 25 * 60 * 60 * 1000),
},
},
},
})
// 2. Create an active file in Project 1
const fileActive = await prisma.asset.create({
data: {
name: 'File Active',
type: AssetType.file,
status: 'uploaded',
isDeleted: false,
project: { connect: { id: project1.id } },
creator: { connect: { id: user.id } },
storageKey: {
create: {
key: 'files/project1-active/raw',
createdAt: new Date(Date.now() - 25 * 60 * 60 * 1000),
},
},
},
})
// 3. Create a trashed file in Project 2
const fileOtherTrashed = await prisma.asset.create({
data: {
name: 'File Other Trashed',
type: AssetType.file,
status: 'trashed',
isDeleted: true,
project: { connect: { id: project2.id } },
creator: { connect: { id: user.id } },
deletedAt: new Date(),
storageKey: {
create: {
key: 'files/project2-trashed/raw',
createdAt: new Date(Date.now() - 25 * 60 * 60 * 1000),
},
},
},
})
// Act
await assetService.emptyTrash(project1.id)
// Assert: Project 1 trashed assets are deleted from DB
expect(await prisma.asset.findUnique({ where: { id: folderA.id } })).toBeNull()
expect(await prisma.asset.findUnique({ where: { id: fileA1.id } })).toBeNull()
// Assert: Project 1 active assets are NOT deleted
expect(await prisma.asset.findUnique({ where: { id: fileActive.id } })).not.toBeNull()
// Assert: Project 2 trashed assets are NOT deleted
expect(await prisma.asset.findUnique({ where: { id: fileOtherTrashed.id } })).not.toBeNull()
// Assert: S3 deletion was called for Project 1's trashed file
expect(s3Service.deletePrefix).toHaveBeenCalledWith(
expect.any(String),
'files/project1-trashed/',
)
// Assert: S3 deletion was NOT called for Project 1's active file or Project 2's trashed file
expect(s3Service.deletePrefix).not.toHaveBeenCalledWith(
expect.any(String),
'files/project1-active/',
)
expect(s3Service.deletePrefix).not.toHaveBeenCalledWith(
expect.any(String),
'files/project2-trashed/',
)
})
it('should do nothing and not throw when there are no trashed assets', async () => {
const team = await prisma.team.create({ data: { name: 'Empty Test Team' } })
const project = await prisma.project.create({
data: { name: 'Empty Test Project', teamId: team.id },
})
await expect(assetService.emptyTrash(project.id)).resolves.not.toThrow()
})
})
describe('expireTrashedAssets', () => {
it('should only purge root assets that have been in the trash for > 30 days and their descendants', async () => {
const team = await prisma.team.create({ data: { name: 'GC Team' } })
const project = await prisma.project.create({
data: { name: 'GC Project', teamId: team.id },
})
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-${Date.now()}@example.com` },
})
const fortyDaysAgo = new Date(Date.now() - 40 * 24 * 60 * 60 * 1000)
const twentyDaysAgo = new Date(Date.now() - 20 * 24 * 60 * 60 * 1000)
// 1. Root expired folder (> 30 days)
const folderExpired = await prisma.asset.create({
data: {
name: 'Expired Folder',
type: AssetType.folder,
status: 'trashed',
isDeleted: true,
project: { connect: { id: project.id } },
creator: { connect: { id: user.id } },
deletedAt: fortyDaysAgo,
},
})
// Child of expired folder
const childOfExpired = await prisma.asset.create({
data: {
name: 'Child of Expired',
type: AssetType.file,
status: 'uploaded',
isDeleted: true,
project: { connect: { id: project.id } },
parent: { connect: { id: folderExpired.id } },
creator: { connect: { id: user.id } },
},
})
// 2. Root active folder (<= 30 days)
const folderActive = await prisma.asset.create({
data: {
name: 'Active Folder',
type: AssetType.folder,
status: 'trashed',
isDeleted: true,
project: { connect: { id: project.id } },
creator: { connect: { id: user.id } },
deletedAt: twentyDaysAgo,
},
})
// Child of active folder
const childOfActive = await prisma.asset.create({
data: {
name: 'Child of Active',
type: AssetType.file,
status: 'uploaded',
isDeleted: true,
project: { connect: { id: project.id } },
parent: { connect: { id: folderActive.id } },
creator: { connect: { id: user.id } },
},
})
// Act
await (
assetService as unknown as { expireTrashedAssets: () => Promise<void> }
).expireTrashedAssets()
// Assert
const expiredDb = await prisma.asset.findUnique({ where: { id: folderExpired.id } })
const childExpiredDb = await prisma.asset.findUnique({ where: { id: childOfExpired.id } })
const activeDb = await prisma.asset.findUnique({ where: { id: folderActive.id } })
const childActiveDb = await prisma.asset.findUnique({ where: { id: childOfActive.id } })
// The expired folder and its child should be marked as pending_purge
expect(expiredDb?.status).toBe('pending_purge')
expect(childExpiredDb?.status).toBe('pending_purge')
// The active folder and its child should remain 'trashed' and 'uploaded' respectively
expect(activeDb?.status).toBe('trashed')
expect(childActiveDb?.status).toBe('uploaded')
})
})
})
+34 -15
View File
@@ -1033,6 +1033,38 @@ export class AssetService {
}
}
private async cascadeStatusToPendingPurge(rootIds: string[]): Promise<void> {
if (rootIds.length === 0) return
await this.prismaClient.$executeRaw`
WITH RECURSIVE descendant AS (
SELECT id FROM assets WHERE id = ANY(${rootIds})
UNION ALL
SELECT a.id FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
)
UPDATE assets SET status = 'pending_purge', updated_at = NOW()
WHERE id IN (SELECT id FROM descendant);
`
}
async emptyTrash(projectId: string): Promise<void> {
const trashedRoots = await this.prismaClient.asset.findMany({
where: {
projectId,
status: 'trashed',
isDeleted: true,
},
select: { id: true },
})
const rootIds = trashedRoots.map((r) => r.id)
await this.cascadeStatusToPendingPurge(rootIds)
await this.purgePendingAssets()
await this.purgeUnreferencedStorageKeys()
}
private cleanupJobsRunning = false
async startCleanupJob() {
@@ -1080,21 +1112,8 @@ export class AssetService {
take: 100,
})
for (const root of expiredRoots) {
await this.prismaClient.$transaction(async (tx) => {
// Use recursive CTE to find all descendants and mark them all as pending_purge
await tx.$executeRaw`
WITH RECURSIVE descendant AS (
SELECT id FROM assets WHERE id = ${root.id}
UNION ALL
SELECT a.id FROM assets a
INNER JOIN descendant d ON a.parent_id = d.id
)
UPDATE assets SET status = 'pending_purge', updated_at = NOW()
WHERE id IN (SELECT id FROM descendant);
`
})
}
const rootIds = expiredRoots.map((r) => r.id)
await this.cascadeStatusToPendingPurge(rootIds)
}
/**
@@ -349,6 +349,28 @@ export function FileBrowser({
selectedIds,
})
const [isEmptyTrashDialogOpen, setIsEmptyTrashDialogOpen] = useState(false)
const { mutate: emptyTrash, isPending: isEmptyingTrash } = useMutation({
mutationFn: async () => {
const res = await client.api.projects[':projectId']['empty-trash'].$post({
param: { projectId },
})
if (!res.ok) throw new Error('Failed to empty trash')
return await res.json()
},
onSuccess: () => {
toast.success('Trash emptied successfully')
queryClient.invalidateQueries({
queryKey: ['projects', projectId, 'recently-deleted'],
})
onClearSelection()
setIsEmptyTrashDialogOpen(false)
},
onError: (err) => {
toast.error(`Error emptying trash: ${err.message}`)
},
})
const $confirmUpload = client.api.teams[':teamId'].upload.tasks[':taskId'].$patch
const { mutateAsync: confirmUpload } = useMutation<
InferResponseType<typeof $confirmUpload>,
@@ -431,7 +453,7 @@ export function FileBrowser({
const newVersionInputRef = useRef<HTMLInputElement>(null)
const [targetVersionFileId, setTargetVersionFileId] = useState<string | null>(null)
const fileContextMenu = useRef(false)
const { canEdit } = usePermissions()
const { canEdit, canAdmin } = usePermissions()
const scrollContainerRef = useRef<HTMLDivElement>(null)
@@ -806,6 +828,27 @@ export function FileBrowser({
rootFolderId={rootFolderId}
/>
)}
{isRecentlyDeleted && (
<div className="flex items-center justify-between px-4 py-2.5 bg-muted/20 border-b border-border text-sm shrink-0 animate-in fade-in slide-in-from-top-2 duration-300">
<div className="flex items-center gap-2 text-muted-foreground">
<AlertTriangle className="h-4 w-4 text-amber-500 shrink-0" />
<span>Items are automatically deleted after 30 days.</span>
</div>
{canAdmin && (
<Button
variant="destructive"
size="sm"
disabled={
isEmptyingTrash || (folders.length === 0 && displayedFiles.length === 0)
}
onClick={() => setIsEmptyTrashDialogOpen(true)}
className="h-8 px-3 text-xs font-medium bg-destructive/10 text-destructive border border-destructive/20 hover:bg-destructive hover:text-destructive-foreground transition-all duration-200"
>
Delete Now
</Button>
)}
</div>
)}
<div
ref={scrollContainerRef}
className="flex-1 overflow-y-auto min-h-0 relative flex flex-col"
@@ -1021,6 +1064,30 @@ export function FileBrowser({
</AlertDialogContent>
</AlertDialog>
<AlertDialog open={isEmptyTrashDialogOpen} onOpenChange={setIsEmptyTrashDialogOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Empty Trash?</AlertDialogTitle>
<AlertDialogDescription>
All items in the recently deleted folder will be permanently removed both from the
database and from storage. This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
emptyTrash()
}}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
disabled={isEmptyingTrash}
>
{isEmptyingTrash ? 'Deleting...' : 'Delete Now'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<Dialog open={isDownloadDialogOpen} onOpenChange={setIsDownloadDialogOpen}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
@@ -301,10 +301,10 @@ export default function FileSystemManager({
}, [selectedIds, files])
const handleItemDoubleClick = (item: AssetInfo) => {
if (isRecentlyDeleted) {
return
}
if (item.type === 'folder') {
if (isRecentlyDeleted) {
return
}
setFilterConditions([])
navigate({
to: '/projects/$projectId/folders/$folderId',