mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-22 02:58:03 +00:00
feat(trash): add recently-deleted banner and empty trash option for admin
- Added emptyTrash method in AssetService to purge trashed assets from DB and S3 - Added POST /projects/:projectId/empty-trash endpoint in project API - Implemented unit and integration tests for service and API - Prevented double click redirect in recently deleted folder - Added top banner with Delete Now option in recently-deleted folder with confirmation dialog
This commit is contained in:
@@ -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')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -1883,4 +1883,118 @@ 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/',
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1033,6 +1033,36 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
async emptyTrash(projectId: string): Promise<void> {
|
||||
const trashedRoots = await this.prismaClient.asset.findMany({
|
||||
where: {
|
||||
projectId,
|
||||
status: 'trashed',
|
||||
isDeleted: true,
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
|
||||
for (const root of trashedRoots) {
|
||||
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);
|
||||
`
|
||||
})
|
||||
}
|
||||
|
||||
await this.purgePendingAssets()
|
||||
await this.purgeUnreferencedStorageKeys()
|
||||
}
|
||||
|
||||
private cleanupJobsRunning = false
|
||||
|
||||
async startCleanupJob() {
|
||||
|
||||
@@ -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,25 @@ 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}
|
||||
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 +1062,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',
|
||||
|
||||
Reference in New Issue
Block a user