mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 00:29:50 +00:00
Merge pull request #70 from shumaiOne/feat/member-management
feat(members): implement member management and handle permission errors
This commit is contained in:
@@ -44,6 +44,9 @@ if (process.env.WORKFLOW_EXECUTOR === 'temporal') {
|
||||
const server = Bun.serve({
|
||||
port: 3000,
|
||||
fetch: app.fetch,
|
||||
maxRequestBodySize: process.env.MAX_REQUEST_BODY_SIZE
|
||||
? parseInt(process.env.MAX_REQUEST_BODY_SIZE)
|
||||
: 1024 * 1024 * 1024 * 10, // Default 10GB
|
||||
routes: {
|
||||
// Serve index.html for root
|
||||
'/': index,
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
updateProjectRequestSchema,
|
||||
listProjectsRequestSchema,
|
||||
recentlyDeletedRequestSchema,
|
||||
updateProjectMemberRoleRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { listMembersQuerySchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
@@ -244,5 +245,46 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
return c.body(null, 204)
|
||||
})
|
||||
.patch(
|
||||
'/projects/:projectId/members/:userId',
|
||||
zValidator('json', updateProjectMemberRoleRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const projectId = c.req.param('projectId')
|
||||
const userId = c.req.param('userId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
await projectService.updateMemberRole({
|
||||
projectId,
|
||||
userId,
|
||||
role: req.role,
|
||||
})
|
||||
|
||||
return c.json({ success: true })
|
||||
},
|
||||
)
|
||||
.delete('/projects/:projectId/members/:userId', async (c) => {
|
||||
const user = c.get('user')
|
||||
const projectId = c.req.param('projectId')
|
||||
const userId = c.req.param('userId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Project,
|
||||
id: projectId,
|
||||
})
|
||||
|
||||
await projectService.removeMember(projectId, userId)
|
||||
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
export default route
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
listMembersQuerySchema,
|
||||
updateSandboxSettingsRequestSchema,
|
||||
updateMeRequestSchema,
|
||||
updateTeamMemberRoleRequestSchema,
|
||||
} from '@shumai/dtos'
|
||||
import { updateUserMetadataRequestSchema } from '@shumai/dtos'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
@@ -112,6 +113,47 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
return c.json(members)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/members/:userId',
|
||||
zValidator('json', updateTeamMemberRoleRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const userId = c.req.param('userId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
await teamService.updateMemberRole({
|
||||
teamId,
|
||||
userId,
|
||||
role: req.role,
|
||||
})
|
||||
|
||||
return c.json({ success: true })
|
||||
},
|
||||
)
|
||||
.delete('/teams/:teamId/members/:userId', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const userId = c.req.param('userId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
await teamService.removeMember(teamId, userId)
|
||||
|
||||
return c.json({ success: true })
|
||||
})
|
||||
.get('/teams/:teamId/settings', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import type { Prisma } from '@shumai/db'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
export enum Permission {
|
||||
@@ -32,7 +34,7 @@ export interface AuthzRequest {
|
||||
|
||||
export class AuthzService {
|
||||
async hasPermission(req: AuthzRequest): Promise<void> {
|
||||
if (!req.user) throw new Error('User is required')
|
||||
if (!req.user) throw new HTTPException(401, { message: 'User is required' })
|
||||
|
||||
const { teamId, projectId } = await this.resolveContext(req.type, req.id)
|
||||
|
||||
@@ -46,7 +48,7 @@ export class AuthzService {
|
||||
},
|
||||
})
|
||||
|
||||
if (!member) throw new Error('User is not a member of the team')
|
||||
if (!member) throw new HTTPException(403, { message: 'User is not a member of the team' })
|
||||
|
||||
// 2. Check Scope
|
||||
if (member.scope === 'team') {
|
||||
@@ -62,7 +64,7 @@ export class AuthzService {
|
||||
if (req.permission === Permission.Read) {
|
||||
return
|
||||
}
|
||||
throw new Error('User has only project scope')
|
||||
throw new HTTPException(403, { message: 'User has only project scope' })
|
||||
}
|
||||
|
||||
// Check Project Membership
|
||||
@@ -75,7 +77,7 @@ export class AuthzService {
|
||||
},
|
||||
})
|
||||
|
||||
if (!pm) throw new Error(`User is not a member of project ${projectId}`)
|
||||
if (!pm) throw new HTTPException(403, { message: `User is not a member of project ${projectId}` })
|
||||
|
||||
return this.checkRole(pm.role, req.permission)
|
||||
}
|
||||
@@ -93,7 +95,7 @@ export class AuthzService {
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!proj) throw new Error('Project not found')
|
||||
if (!proj) throw new HTTPException(404, { message: 'Project not found' })
|
||||
return { teamId: proj.teamId, projectId: id }
|
||||
}
|
||||
|
||||
@@ -106,7 +108,7 @@ export class AuthzService {
|
||||
project: { select: { id: true, teamId: true } },
|
||||
},
|
||||
})
|
||||
if (!asset) throw new Error('Asset not found')
|
||||
if (!asset) throw new HTTPException(404, { message: 'Asset not found' })
|
||||
if (asset.project) {
|
||||
return { teamId: asset.project.teamId, projectId: asset.project.id }
|
||||
}
|
||||
@@ -120,7 +122,7 @@ export class AuthzService {
|
||||
// For now, let's try to get context from parent.
|
||||
return this.resolveContext(ResourceType.Asset, asset.parentId)
|
||||
}
|
||||
throw new Error('Could not resolve context for asset')
|
||||
throw new HTTPException(403, { message: 'Could not resolve context for asset' })
|
||||
}
|
||||
|
||||
case ResourceType.Collection: {
|
||||
@@ -128,7 +130,7 @@ export class AuthzService {
|
||||
where: { id },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!coll) throw new Error('Collection not found')
|
||||
if (!coll) throw new HTTPException(404, { message: 'Collection not found' })
|
||||
return { teamId: coll.project.teamId, projectId: coll.projectId }
|
||||
}
|
||||
|
||||
@@ -137,7 +139,7 @@ export class AuthzService {
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!agent) throw new Error('Agent not found')
|
||||
if (!agent) throw new HTTPException(404, { message: 'Agent not found' })
|
||||
return { teamId: agent.teamId }
|
||||
}
|
||||
|
||||
@@ -146,7 +148,7 @@ export class AuthzService {
|
||||
where: { id },
|
||||
include: { agent: true },
|
||||
})
|
||||
if (!session) throw new Error('Agent session not found')
|
||||
if (!session) throw new HTTPException(404, { message: 'Agent session not found' })
|
||||
return { teamId: session.agent.teamId }
|
||||
}
|
||||
|
||||
@@ -155,7 +157,7 @@ export class AuthzService {
|
||||
where: { id },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!share) throw new Error('Share not found')
|
||||
if (!share) throw new HTTPException(404, { message: 'Share not found' })
|
||||
return { teamId: share.project.teamId, projectId: share.projectId }
|
||||
}
|
||||
|
||||
@@ -164,7 +166,7 @@ export class AuthzService {
|
||||
where: { key: id },
|
||||
select: { teamId: true, projectId: true },
|
||||
})
|
||||
if (!field) throw new Error('Metadata field not found')
|
||||
if (!field) throw new HTTPException(404, { message: 'Metadata field not found' })
|
||||
if (field.projectId) {
|
||||
const proj = await prisma.project.findUnique({
|
||||
where: { id: field.projectId },
|
||||
@@ -172,7 +174,7 @@ export class AuthzService {
|
||||
})
|
||||
return { teamId: proj!.teamId, projectId: field.projectId }
|
||||
}
|
||||
if (!field.teamId) throw new Error('Metadata field has no context')
|
||||
if (!field.teamId) throw new HTTPException(403, { message: 'Metadata field has no context' })
|
||||
return { teamId: field.teamId }
|
||||
}
|
||||
|
||||
@@ -181,7 +183,7 @@ export class AuthzService {
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!skill) throw new Error('Skill not found')
|
||||
if (!skill) throw new HTTPException(404, { message: 'Skill not found' })
|
||||
return { teamId: skill.teamId }
|
||||
}
|
||||
|
||||
@@ -190,7 +192,7 @@ export class AuthzService {
|
||||
where: { id },
|
||||
select: { teamId: true },
|
||||
})
|
||||
if (!provider) throw new Error('Provider not found')
|
||||
if (!provider) throw new HTTPException(404, { message: 'Provider not found' })
|
||||
return { teamId: provider.teamId }
|
||||
}
|
||||
|
||||
@@ -199,7 +201,7 @@ export class AuthzService {
|
||||
where: { id },
|
||||
select: { teamId: true, projectId: true },
|
||||
})
|
||||
if (!invite) throw new Error('Invite not found')
|
||||
if (!invite) throw new HTTPException(404, { message: 'Invite not found' })
|
||||
return { teamId: invite.teamId, projectId: invite.projectId ?? undefined }
|
||||
}
|
||||
|
||||
@@ -208,13 +210,13 @@ export class AuthzService {
|
||||
where: { id },
|
||||
include: { asset: { include: { project: true } } },
|
||||
})
|
||||
if (!comment) throw new Error('Comment not found')
|
||||
if (!comment.asset.project) throw new Error('Comment asset has no project')
|
||||
if (!comment) throw new HTTPException(404, { message: 'Comment not found' })
|
||||
if (!comment.asset.project) throw new HTTPException(403, { message: 'Comment asset has no project' })
|
||||
return { teamId: comment.asset.project.teamId, projectId: comment.asset.projectId! }
|
||||
}
|
||||
|
||||
default:
|
||||
throw new Error(`Unsupported resource type: ${type}`)
|
||||
throw new HTTPException(403, { message: `Unsupported resource type: ${type}` })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,7 +231,7 @@ export class AuthzService {
|
||||
if (role === 'owner') return
|
||||
break
|
||||
}
|
||||
throw new Error('Permission denied')
|
||||
throw new HTTPException(403, { message: 'Permission denied' })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
ServiceListProjectsRequest,
|
||||
ServiceAddProjectMemberRequest,
|
||||
ServiceListProjectMembersRequest,
|
||||
ServiceUpdateProjectMemberRoleRequest,
|
||||
ProjectInfo,
|
||||
ProjectUserInfo,
|
||||
} from '@shumai/dtos'
|
||||
@@ -303,6 +304,43 @@ export class ProjectService {
|
||||
return project.teamId
|
||||
}
|
||||
|
||||
async updateMemberRole(req: ServiceUpdateProjectMemberRoleRequest): Promise<void> {
|
||||
const member = await prisma.projectMember.findFirst({
|
||||
where: {
|
||||
projectId: req.projectId,
|
||||
teamMember: {
|
||||
userId: req.userId,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!member) throw new Error('Member not found')
|
||||
if (member.role === 'owner') throw new Error('Cannot change the role of an owner')
|
||||
|
||||
await prisma.projectMember.update({
|
||||
where: { id: member.id },
|
||||
data: { role: req.role },
|
||||
})
|
||||
}
|
||||
|
||||
async removeMember(projectId: string, userId: string): Promise<void> {
|
||||
const member = await prisma.projectMember.findFirst({
|
||||
where: {
|
||||
projectId: projectId,
|
||||
teamMember: {
|
||||
userId: userId,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!member) throw new Error('Member not found')
|
||||
if (member.role === 'owner') throw new Error('Cannot remove an owner')
|
||||
|
||||
await prisma.projectMember.delete({
|
||||
where: { id: member.id },
|
||||
})
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
private async toProjectInfo(p: any): Promise<ProjectInfo> {
|
||||
const pi: ProjectInfo = {
|
||||
|
||||
@@ -17,9 +17,7 @@ export class SearchService {
|
||||
|
||||
async search(folderId: string, req: SearchRequest): Promise<PaginatedData<AssetInfo[]>> {
|
||||
const targetFolderIds =
|
||||
req.recursively === false
|
||||
? [folderId]
|
||||
: await this.assetSvc.getDescendantFolderIds(folderId)
|
||||
req.recursively === false ? [folderId] : await this.assetSvc.getDescendantFolderIds(folderId)
|
||||
|
||||
const targetTypes =
|
||||
req.assetType === 'folder' ? [AssetType.folder] : [AssetType.file, AssetType.version_stack]
|
||||
|
||||
@@ -4,12 +4,14 @@ import { PaginatedData, paginateQuery } from '@shumai/core/src/pagination'
|
||||
import { ProviderService, providerService } from '@shumai/core/src/provider/provider'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import {
|
||||
ServiceCreateTeamRequest,
|
||||
ServiceGetUserTeamsRequest,
|
||||
ServiceJoinTeamRequest,
|
||||
ServiceGetMeRequest,
|
||||
ServiceGetTeamMembersRequest,
|
||||
ServiceUpdateTeamMemberRoleRequest,
|
||||
TeamInfo,
|
||||
GetMeResponse,
|
||||
UserInfo,
|
||||
@@ -140,7 +142,7 @@ export class TeamService {
|
||||
include: { user: true },
|
||||
})
|
||||
|
||||
if (!member) throw new Error('user is not a team member')
|
||||
if (!member) throw new HTTPException(403, { message: 'user is not a team member' })
|
||||
|
||||
const unreadNotificationCount = await notificationService.getUnreadCount(
|
||||
req.teamId,
|
||||
@@ -207,12 +209,50 @@ export class TeamService {
|
||||
)
|
||||
}
|
||||
|
||||
async updateMemberRole(req: ServiceUpdateTeamMemberRoleRequest): Promise<void> {
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId: req.teamId,
|
||||
userId: req.userId,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!member) throw new HTTPException(404, { message: 'Member not found' })
|
||||
if (member.role === 'owner')
|
||||
throw new HTTPException(403, { message: 'Cannot change the role of an owner' })
|
||||
|
||||
await prisma.teamMember.update({
|
||||
where: { id: member.id },
|
||||
data: { role: req.role },
|
||||
})
|
||||
}
|
||||
|
||||
async removeMember(teamId: string, userId: string): Promise<void> {
|
||||
const member = await prisma.teamMember.findUnique({
|
||||
where: {
|
||||
teamIdUserId: {
|
||||
teamId: teamId,
|
||||
userId: userId,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!member) throw new HTTPException(404, { message: 'Member not found' })
|
||||
if (member.role === 'owner') throw new HTTPException(403, { message: 'Cannot remove an owner' })
|
||||
|
||||
await prisma.teamMember.delete({
|
||||
where: { id: member.id },
|
||||
})
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
async getSettings(teamId: string): Promise<any> {
|
||||
const team = await prisma.team.findUnique({
|
||||
where: { id: teamId },
|
||||
})
|
||||
if (!team) throw new Error('team not found')
|
||||
if (!team) throw new HTTPException(404, { message: 'team not found' })
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const settings = (team.settings || {}) as any
|
||||
|
||||
@@ -227,7 +267,7 @@ export class TeamService {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
async updateSettings(teamId: string, key: string, value: any): Promise<any> {
|
||||
const team = await prisma.team.findUnique({ where: { id: teamId } })
|
||||
if (!team) throw new Error('team not found')
|
||||
if (!team) throw new HTTPException(404, { message: 'team not found' })
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const settings = (team.settings || {}) as any
|
||||
|
||||
@@ -65,6 +65,11 @@ export const recentlyDeletedRequestSchema = z
|
||||
})
|
||||
.merge(paginationParamsSchema)
|
||||
|
||||
export const updateProjectMemberRoleRequestSchema = z.object({
|
||||
role: z.enum(['editor', 'reviewer']),
|
||||
})
|
||||
export type UpdateProjectMemberRoleRequest = z.infer<typeof updateProjectMemberRoleRequestSchema>
|
||||
|
||||
// Service Layer Interfaces
|
||||
export interface ServiceCreateProjectRequest {
|
||||
teamId: string
|
||||
@@ -98,3 +103,9 @@ export interface ServiceListProjectMembersRequest {
|
||||
projectId: string
|
||||
includeAgents?: boolean
|
||||
}
|
||||
|
||||
export interface ServiceUpdateProjectMemberRoleRequest {
|
||||
projectId: string
|
||||
userId: string
|
||||
role: 'editor' | 'reviewer'
|
||||
}
|
||||
|
||||
@@ -84,6 +84,11 @@ export type SandboxSettings = z.infer<typeof sandboxSettingsSchema>
|
||||
export const updateSandboxSettingsRequestSchema = sandboxSettingsSchema
|
||||
export type UpdateSandboxSettingsRequest = z.infer<typeof updateSandboxSettingsRequestSchema>
|
||||
|
||||
export const updateTeamMemberRoleRequestSchema = z.object({
|
||||
role: z.enum(['editor', 'reviewer']),
|
||||
})
|
||||
export type UpdateTeamMemberRoleRequest = z.infer<typeof updateTeamMemberRoleRequestSchema>
|
||||
|
||||
// Service Layer Interfaces
|
||||
export interface ServiceCreateTeamRequest {
|
||||
name: string
|
||||
@@ -109,3 +114,9 @@ export interface ServiceGetTeamMembersRequest {
|
||||
teamId: string
|
||||
includeAgents?: boolean
|
||||
}
|
||||
|
||||
export interface ServiceUpdateTeamMemberRoleRequest {
|
||||
teamId: string
|
||||
userId: string
|
||||
role: 'editor' | 'reviewer'
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { hc } from 'hono/client'
|
||||
import type { AppType } from '@shumai/api'
|
||||
import { useAuthStore } from '@/ui/stores/auth'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
const customFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const response = await fetch(input, init)
|
||||
@@ -18,6 +19,12 @@ const customFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
}
|
||||
}
|
||||
|
||||
if (response.status === 403) {
|
||||
toast.error('You do not have permission. Please contact the team admin.', {
|
||||
id: 'forbidden-error',
|
||||
})
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
|
||||
@@ -361,26 +361,36 @@ export function FileBrowser({
|
||||
const isCurrentFolderUpload = variables.json.parentId === assetId
|
||||
|
||||
if (isCurrentFolderUpload) {
|
||||
const newLocalFiles: AssetInfo[] = filesToUpload.map((f) => {
|
||||
const urlInfo = (
|
||||
data.presignedUrls as { id?: string; url?: string; fileId?: string }[] | undefined
|
||||
)?.find((p) => p.id === f.id)
|
||||
const hasUrl = !!urlInfo && !!urlInfo.url
|
||||
return {
|
||||
id: urlInfo?.fileId || f.id,
|
||||
name: f.file.name,
|
||||
sizeByte: f.file.size,
|
||||
fileCount: 0,
|
||||
type: 'file',
|
||||
status: hasUrl ? 'uploading' : 'error',
|
||||
mediaType: f.file.type || null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
})
|
||||
const newLocalFiles: AssetInfo[] = filesToUpload
|
||||
.filter((f) => {
|
||||
const path = (f.file.webkitRelativePath || f.file.name).split('/')
|
||||
return path.length === 1
|
||||
})
|
||||
.map((f) => {
|
||||
const urlInfo = (
|
||||
data.presignedUrls as { id?: string; url?: string; fileId?: string }[] | undefined
|
||||
)?.find((p) => p.id === f.id)
|
||||
const hasUrl = !!urlInfo && !!urlInfo.url
|
||||
return {
|
||||
id: urlInfo?.fileId || f.id,
|
||||
name: f.file.name,
|
||||
sizeByte: f.file.size,
|
||||
fileCount: 0,
|
||||
type: 'file',
|
||||
status: hasUrl ? 'uploading' : 'error',
|
||||
mediaType: f.file.type || null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
})
|
||||
setLocalUploadingFiles((prev) => [...newLocalFiles, ...prev])
|
||||
}
|
||||
|
||||
// Invalidate queries immediately so any newly created folders appear
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
|
||||
// The RPC client returns an object that we cast to the expected type
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await uploadFiles(filesToUpload, data.presignedUrls as any, data.taskId!)
|
||||
|
||||
@@ -4,7 +4,7 @@ import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||
import type { SearchCondition, SearchSort } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { useMutation, useQuery } from '@tanstack/react-query'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
import { useState } from 'react'
|
||||
import { FieldsManager } from '../fields-manager'
|
||||
@@ -58,6 +58,7 @@ export function FileBrowserToolbar({
|
||||
|
||||
const activeFiltersCount = filterConditions.length
|
||||
const isCollection = !!collection
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const { data: folderInfo } = useQuery({
|
||||
queryKey: ['folders', assetId],
|
||||
@@ -134,6 +135,31 @@ export function FileBrowserToolbar({
|
||||
return res.code
|
||||
}
|
||||
|
||||
const updateMemberRoleMutation = useMutation({
|
||||
mutationFn: async ({ userId, role }: { userId: string; role: 'editor' | 'reviewer' }) => {
|
||||
const res = await client.api.projects[':projectId'].members[':userId'].$patch({
|
||||
param: { projectId, userId },
|
||||
json: { role },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update member role')
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects', projectId, 'members'] })
|
||||
},
|
||||
})
|
||||
|
||||
const removeMemberMutation = useMutation({
|
||||
mutationFn: async (userId: string) => {
|
||||
const res = await client.api.projects[':projectId'].members[':userId'].$delete({
|
||||
param: { projectId, userId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to remove member')
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects', projectId, 'members'] })
|
||||
},
|
||||
})
|
||||
|
||||
const getInitials = (name?: string) => {
|
||||
if (!name) return '??'
|
||||
return name
|
||||
@@ -310,6 +336,13 @@ export function FileBrowserToolbar({
|
||||
members={members || []}
|
||||
isOwner={me?.role === 'owner'}
|
||||
onInvite={handleInvite}
|
||||
onUpdateRole={async (memberId, role) => {
|
||||
await updateMemberRoleMutation.mutateAsync({ userId: memberId, role })
|
||||
}}
|
||||
onRemoveMember={async (memberId) => {
|
||||
await removeMemberMutation.mutateAsync(memberId)
|
||||
}}
|
||||
currentUserId={me?.id}
|
||||
/>
|
||||
|
||||
<SearchFilterDialog
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog'
|
||||
@@ -9,7 +19,7 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { ChevronDown, Copy, Loader2 } from 'lucide-react'
|
||||
import { ChevronDown, Copy, Loader2, Trash2 } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
@@ -27,6 +37,9 @@ interface MembersDialogProps {
|
||||
members: Member[]
|
||||
isOwner: boolean
|
||||
onInvite?: (role: 'editor' | 'reviewer') => Promise<string>
|
||||
onUpdateRole?: (memberId: string, role: 'editor' | 'reviewer') => Promise<void>
|
||||
onRemoveMember?: (memberId: string) => Promise<void>
|
||||
currentUserId?: string
|
||||
}
|
||||
|
||||
export function MembersDialog({
|
||||
@@ -36,10 +49,44 @@ export function MembersDialog({
|
||||
members,
|
||||
isOwner,
|
||||
onInvite,
|
||||
onUpdateRole,
|
||||
onRemoveMember,
|
||||
currentUserId,
|
||||
}: MembersDialogProps) {
|
||||
const [inviteRole, setInviteRole] = useState<'editor' | 'reviewer'>('editor')
|
||||
const [inviteLink, setInviteLink] = useState<string | null>(null)
|
||||
const [isGenerating, setIsGenerating] = useState(false)
|
||||
const [updatingMemberId, setUpdatingMemberId] = useState<string | null>(null)
|
||||
const [memberToRemove, setMemberToRemove] = useState<Member | null>(null)
|
||||
|
||||
const handleUpdateRole = async (memberId: string, role: 'editor' | 'reviewer') => {
|
||||
if (!onUpdateRole) return
|
||||
setUpdatingMemberId(memberId)
|
||||
try {
|
||||
await onUpdateRole(memberId, role)
|
||||
toast.success('Member role updated')
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
toast.error('Failed to update member role')
|
||||
} finally {
|
||||
setUpdatingMemberId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveMember = async () => {
|
||||
if (!onRemoveMember || !memberToRemove?.id) return
|
||||
setUpdatingMemberId(memberToRemove.id)
|
||||
try {
|
||||
await onRemoveMember(memberToRemove.id)
|
||||
toast.success('Member removed')
|
||||
setMemberToRemove(null)
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
toast.error('Failed to remove member')
|
||||
} finally {
|
||||
setUpdatingMemberId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleGenerate = async () => {
|
||||
if (!onInvite) return
|
||||
@@ -110,10 +157,80 @@ export function MembersDialog({
|
||||
<span className="text-xs text-muted-foreground capitalize">{member.role}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isOwner && member.role !== 'owner' && member.id !== currentUserId && (
|
||||
<div className="flex items-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 px-2 text-xs capitalize"
|
||||
disabled={updatingMemberId === member.id}
|
||||
>
|
||||
{member.role}
|
||||
<ChevronDown className="ml-1 h-3 w-3 opacity-50" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent>
|
||||
<DropdownMenuRadioGroup
|
||||
value={member.role}
|
||||
onValueChange={(v) =>
|
||||
handleUpdateRole(member.id!, v as 'editor' | 'reviewer')
|
||||
}
|
||||
>
|
||||
<DropdownMenuRadioItem value="editor" className="text-xs">
|
||||
Editor
|
||||
</DropdownMenuRadioItem>
|
||||
<DropdownMenuRadioItem value="reviewer" className="text-xs">
|
||||
Reviewer
|
||||
</DropdownMenuRadioItem>
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => setMemberToRemove(member)}
|
||||
disabled={updatingMemberId === member.id}
|
||||
>
|
||||
{updatingMemberId === member.id ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<AlertDialog
|
||||
open={!!memberToRemove}
|
||||
onOpenChange={(open) => !open && setMemberToRemove(null)}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Remove Member</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to remove <strong>{memberToRemove?.name}</strong> from this{' '}
|
||||
{title.toLowerCase()}? This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleRemoveMember}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Remove
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{isOwner && onInvite && (
|
||||
<div className="border-t pt-4">
|
||||
<h4 className="text-sm font-medium mb-3">Invite New Member</h4>
|
||||
|
||||
Vendored
+3
-3
@@ -1,4 +1,4 @@
|
||||
declare module "*.css" {
|
||||
const content: { [className: string]: string };
|
||||
export default content;
|
||||
declare module '*.css' {
|
||||
const content: { [className: string]: string }
|
||||
export default content
|
||||
}
|
||||
|
||||
@@ -212,6 +212,31 @@ function TeamPage() {
|
||||
return res.code
|
||||
}
|
||||
|
||||
const updateMemberRoleMutation = useMutation({
|
||||
mutationFn: async ({ userId, role }: { userId: string; role: 'editor' | 'reviewer' }) => {
|
||||
const res = await client.api.teams[':teamId'].members[':userId'].$patch({
|
||||
param: { teamId, userId },
|
||||
json: { role },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to update member role')
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'members'] })
|
||||
},
|
||||
})
|
||||
|
||||
const removeMemberMutation = useMutation({
|
||||
mutationFn: async (userId: string) => {
|
||||
const res = await client.api.teams[':teamId'].members[':userId'].$delete({
|
||||
param: { teamId, userId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to remove member')
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'members'] })
|
||||
},
|
||||
})
|
||||
|
||||
const getInitials = (name?: string) => {
|
||||
if (!name) return '??'
|
||||
return name
|
||||
@@ -418,6 +443,13 @@ function TeamPage() {
|
||||
members={safeMembers}
|
||||
isOwner={me?.role === 'owner'}
|
||||
onInvite={handleInvite}
|
||||
onUpdateRole={async (memberId, role) => {
|
||||
await updateMemberRoleMutation.mutateAsync({ userId: memberId, role })
|
||||
}}
|
||||
onRemoveMember={async (memberId) => {
|
||||
await removeMemberMutation.mutateAsync(memberId)
|
||||
}}
|
||||
currentUserId={me?.id}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user