Add multi-role permission system with a Role Management admin page

Users can now hold multiple roles, each with its own editable set of
create/edit/delete-style permissions across assets, shots, tasks, task
assignment, review approve/retake, submissions, uploads, and notes
(including internal vs. client note visibility). The 4 existing roles
(coordinator/director/artist/developer) are migrated into the new system
as system roles, seeded to reproduce today's actual behavior exactly;
admins can create custom roles (e.g. "Reviewer", "Outsourcing") via the
new Role Management page and assign multiple roles to a user via a new
"Manage Roles" action on the Team page.

Backend:
- New Role/Permission models and role_permissions/user_roles tables,
  plus a one-off, idempotent seed/backfill migration script.
- New require_permission()/user_has_permission() dependency, wired into
  the actual mutation endpoints across shots/assets/tasks/reviews,
  always preserving existing ownership- and self-service-based access
  (e.g. artists editing their own task status, own notes, own uploads,
  own submissions) as an unconditional fallback alongside the new
  permission checks - nothing that worked before now requires a role.
- New endpoints: PUT/DELETE on task submissions (wires up soft-deletion
  columns that existed on the model but were never exposed), plus full
  role CRUD and per-user role assignment.
- Along the way: fixed newly-created users not being linked to their
  matching system role (silently leaving them with zero permissions),
  and unified an inconsistency between the single vs. bulk task status
  endpoints that allowed different roles to bulk-update status.

Frontend:
- Role Management page with a grouped, human-readable permission editor
  (icons, plain-language action labels, per-resource select-all, live
  selected count) replacing an earlier dense matrix prototype.
- hasPermission() added to the existing usePermission() composable
  without touching its current isAdmin/isCoordinatorOrAdmin consumers.
- Note composer gets an Internal/Client toggle; submissions gain inline
  edit/delete actions gated the same ownership-or-permission way as notes.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-18 20:41:17 +08:00
parent 976ec40b52
commit db2c414c1a
33 changed files with 1697 additions and 137 deletions
@@ -181,6 +181,7 @@ import {
Camera,
Package,
ListTodo,
ShieldCheck,
} from 'lucide-vue-next'
import { useAuthStore } from '@/stores/auth'
@@ -271,6 +272,7 @@ const navigationItems = computed(() => {
// Admin-specific navigation items
const adminItems = computed(() => [
{ title: 'Recovery Management', url: '/admin/deleted-items', icon: RotateCcw },
{ title: 'Role Management', url: '/admin/roles', icon: ShieldCheck },
])
// Developer-specific navigation items
@@ -0,0 +1,226 @@
<template>
<Dialog :open="open" @update:open="$emit('update:open', $event)">
<DialogContent class="sm:max-w-2xl max-h-[85vh] flex flex-col">
<DialogHeader>
<DialogTitle>{{ role ? 'Edit Role' : 'Create Role' }}</DialogTitle>
<DialogDescription>
{{ role?.is_system
? 'System role permissions are editable, but the name and description cannot be changed.'
: 'Define a role and the permissions it grants.' }}
</DialogDescription>
</DialogHeader>
<form @submit.prevent="handleSubmit" class="flex-1 min-h-0 flex flex-col gap-4">
<div class="grid grid-cols-2 gap-4 flex-shrink-0">
<div class="space-y-2">
<Label for="role_name">Name</Label>
<Input
id="role_name"
v-model="formData.name"
placeholder="e.g. Reviewer"
required
:disabled="role?.is_system"
/>
</div>
<div class="space-y-2">
<Label for="role_description">Description</Label>
<Input
id="role_description"
v-model="formData.description"
placeholder="What this role is for"
:disabled="role?.is_system"
/>
</div>
</div>
<div class="flex-1 min-h-0 flex flex-col gap-2">
<div class="flex items-center justify-between flex-shrink-0">
<Label>Permissions</Label>
<span class="text-xs text-muted-foreground">{{ selectedPermissionIds.size }} of {{ permissions.length }} selected</span>
</div>
<div class="flex-1 min-h-0 overflow-y-auto rounded-md border p-3 space-y-4">
<div v-for="group in permissionGroups" :key="group.title" class="space-y-2">
<h4 class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{{ group.title }}</h4>
<div class="space-y-2">
<div v-for="resource in group.resources" :key="resource" class="rounded-md border bg-muted/30 p-2.5">
<div class="flex items-center justify-between mb-2">
<div class="flex items-center gap-2 text-sm font-medium capitalize">
<component :is="resourceIcon(resource)" class="h-4 w-4 text-muted-foreground" />
{{ resource }}
</div>
<button
type="button"
class="text-xs text-muted-foreground hover:text-foreground hover:underline"
@click="toggleAllForResource(resource)"
>
{{ allSelectedForResource(resource) ? 'Clear' : 'Select all' }}
</button>
</div>
<div class="flex flex-wrap gap-x-4 gap-y-1.5">
<label
v-for="perm in permissionsForResource(resource)"
:key="perm.id"
class="flex items-center gap-1.5 text-sm cursor-pointer"
:title="perm.description || undefined"
>
<Checkbox
:model-value="selectedPermissionIds.has(perm.id)"
@update:model-value="(val) => togglePermission(perm.id, !!val)"
/>
{{ actionLabel(perm.action) }}
</label>
</div>
</div>
</div>
</div>
</div>
</div>
<p v-if="formError" class="text-sm text-destructive flex-shrink-0">{{ formError }}</p>
<DialogFooter class="flex-shrink-0">
<Button type="button" variant="outline" @click="$emit('update:open', false)">Cancel</Button>
<Button type="submit" :disabled="saving">{{ saving ? 'Saving...' : 'Save' }}</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import {
Package, Camera, ListTodo, UserCheck, CheckCircle2, UploadCloud, Paperclip, MessageSquare, Shield
} from 'lucide-vue-next'
import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import type { Role, Permission } from '@/services/role'
interface Props {
open: boolean
role: Role | null
permissions: Permission[]
saving?: boolean
}
const props = defineProps<Props>()
const emit = defineEmits<{
'update:open': [value: boolean]
saved: [data: { name?: string; description?: string; permission_ids: number[] }]
}>()
const formData = ref({ name: '', description: '' })
const selectedPermissionIds = ref<Set<number>>(new Set())
const formError = ref('')
// Resources grouped into scannable sections, in a fixed, deliberate order
// (not alphabetical) so related concepts sit together.
const RESOURCE_GROUPS: { title: string; resources: string[] }[] = [
{ title: 'Production', resources: ['asset', 'shot', 'task'] },
{ title: 'Task workflow', resources: ['assignment', 'submission', 'upload'] },
{ title: 'Review', resources: ['review'] },
{ title: 'Notes', resources: ['note'] },
]
const RESOURCE_ICONS: Record<string, any> = {
asset: Package,
shot: Camera,
task: ListTodo,
assignment: UserCheck,
submission: UploadCloud,
upload: Paperclip,
review: CheckCircle2,
note: MessageSquare,
}
const ACTION_LABELS: Record<string, string> = {
create: 'Create',
edit: 'Edit',
delete: 'Delete',
publish: 'Approve',
retake: 'Request Retake',
view_internal: 'View Internal',
view_client: 'View Client',
change_status: 'Change Status',
}
function resourceIcon(resource: string) {
return RESOURCE_ICONS[resource] ?? Shield
}
function actionLabel(action: string): string {
return ACTION_LABELS[action] ?? action
}
// Only show groups/resources that actually have permissions in the catalog,
// and fall back to a catch-all group for any future resource not yet
// assigned to a section above (so nothing silently disappears from the UI).
const permissionGroups = computed(() => {
const knownResources = new Set(RESOURCE_GROUPS.flatMap(g => g.resources))
const groups = RESOURCE_GROUPS
.map(g => ({ title: g.title, resources: g.resources.filter(r => permissionsForResource(r).length > 0) }))
.filter(g => g.resources.length > 0)
const otherResources = [...new Set(props.permissions.map(p => p.resource))].filter(r => !knownResources.has(r))
if (otherResources.length > 0) {
groups.push({ title: 'Other', resources: otherResources })
}
return groups
})
function permissionsForResource(resource: string): Permission[] {
return props.permissions.filter(p => p.resource === resource)
}
function allSelectedForResource(resource: string): boolean {
const perms = permissionsForResource(resource)
return perms.length > 0 && perms.every(p => selectedPermissionIds.value.has(p.id))
}
function toggleAllForResource(resource: string) {
const perms = permissionsForResource(resource)
const shouldSelect = !allSelectedForResource(resource)
for (const perm of perms) {
if (shouldSelect) selectedPermissionIds.value.add(perm.id)
else selectedPermissionIds.value.delete(perm.id)
}
}
function togglePermission(id: number, checked: boolean) {
if (checked) selectedPermissionIds.value.add(id)
else selectedPermissionIds.value.delete(id)
}
watch(() => props.open, (isOpen) => {
if (!isOpen) return
formError.value = ''
formData.value = {
name: props.role?.name ?? '',
description: props.role?.description ?? ''
}
selectedPermissionIds.value = new Set(props.role?.permissions.map(p => p.id) ?? [])
})
function handleSubmit() {
formError.value = ''
if (!props.role && !formData.value.name.trim()) {
formError.value = 'Name is required'
return
}
const payload = props.role?.is_system
? { permission_ids: [...selectedPermissionIds.value] }
: {
name: formData.value.name,
description: formData.value.description || undefined,
permission_ids: [...selectedPermissionIds.value]
}
emit('saved', payload)
}
</script>
+8 -2
View File
@@ -30,6 +30,7 @@
<span v-if="note.updated_at !== note.created_at" class="text-xs text-muted-foreground">
(edited)
</span>
<Badge v-if="note.note_type === 'client'" variant="outline" class="text-xs">Client</Badge>
</div>
<!-- Note Content -->
@@ -117,6 +118,7 @@
import { ref, computed } from 'vue'
import { Reply, Pencil, Trash2 } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Textarea } from '@/components/ui/textarea'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import {
@@ -131,6 +133,7 @@ import {
} from '@/components/ui/alert-dialog'
import { taskService, type ProductionNote } from '@/services/task'
import { useAuthStore } from '@/stores/auth'
import { usePermission } from '@/composables/usePermission'
import { useToast } from '@/components/ui/toast/use-toast'
const props = defineProps<{
@@ -145,17 +148,20 @@ const emit = defineEmits<{
const { toast } = useToast()
const authStore = useAuthStore()
const { hasPermission } = usePermission()
const editing = ref(false)
const editContent = ref('')
const showDeleteDialog = ref(false)
const isOwnNote = computed(() => authStore.user?.id === props.note.user_id)
const canEdit = computed(() => {
return authStore.user?.id === props.note.user_id || authStore.user?.is_admin
return isOwnNote.value || authStore.user?.is_admin || hasPermission('note', 'edit')
})
const canDelete = computed(() => {
return authStore.user?.id === props.note.user_id || authStore.user?.is_admin
return isOwnNote.value || authStore.user?.is_admin || hasPermission('note', 'delete')
})
function getInitials(firstName: string, lastName: string): string {
+105 -12
View File
@@ -56,11 +56,19 @@
</div>
</div>
<div v-if="submission.notes" class="text-sm bg-muted p-2 rounded">
<div v-if="!editing && submission.notes" class="text-sm bg-muted p-2 rounded">
<p class="font-semibold text-xs mb-1">Notes:</p>
<p class="line-clamp-2">{{ submission.notes }}</p>
</div>
<div v-if="editing" class="space-y-2">
<Textarea v-model="editNotes" rows="2" class="resize-none text-sm" placeholder="Notes about this submission..." />
<div class="flex gap-2">
<Button size="sm" @click="handleSaveNotes">Save</Button>
<Button size="sm" variant="outline" @click="editing = false">Cancel</Button>
</div>
</div>
<div v-if="submission.latest_review?.feedback" class="text-sm border-l-2 pl-2" :class="getReviewBorderClass(submission.latest_review.decision)">
<p class="font-semibold text-xs mb-1">Review Feedback:</p>
<p class="line-clamp-2">{{ submission.latest_review.feedback }}</p>
@@ -69,37 +77,122 @@
</p>
</div>
<Button
variant="outline"
size="sm"
@click="emit('view', submission)"
>
<Eye class="h-4 w-4 mr-2" />
View Details
</Button>
<div v-if="!editing" class="flex gap-2">
<Button
variant="outline"
size="sm"
@click="emit('view', submission)"
>
<Eye class="h-4 w-4 mr-2" />
View Details
</Button>
<Button v-if="canEdit" variant="ghost" size="sm" @click="startEdit">
<Pencil class="h-4 w-4 mr-2" />
Edit
</Button>
<Button v-if="canDelete" variant="ghost" size="sm" @click="showDeleteDialog = true">
<Trash2 class="h-4 w-4 mr-2" />
Delete
</Button>
</div>
</div>
</div>
<AlertDialog :open="showDeleteDialog" @update:open="(val: boolean) => { showDeleteDialog = val }">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete Submission</AlertDialogTitle>
<AlertDialogDescription>
Are you sure you want to delete this submission? This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction @click="handleDelete" class="bg-destructive text-destructive-foreground hover:bg-destructive/90">
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</Card>
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { FileIcon, Download, Eye, Play } from 'lucide-vue-next'
import { ref, computed, onMounted, watch } from 'vue'
import { FileIcon, Download, Eye, Play, Pencil, Trash2 } from 'lucide-vue-next'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Textarea } from '@/components/ui/textarea'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import type { Submission } from '@/services/task'
import {
AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { taskService, type Submission } from '@/services/task'
import { apiClient } from '@/services/api'
import { useAuthStore } from '@/stores/auth'
import { usePermission } from '@/composables/usePermission'
import { useToast } from '@/components/ui/toast/use-toast'
const props = defineProps<{
taskId: number
submission: Submission
}>()
const emit = defineEmits<{
view: [submission: Submission]
submissionUpdated: []
}>()
const { toast } = useToast()
const authStore = useAuthStore()
const { hasPermission } = usePermission()
const isOwnSubmission = computed(() => authStore.user?.id === props.submission.user_id)
const canEdit = computed(() => isOwnSubmission.value || authStore.user?.is_admin || hasPermission('submission', 'edit'))
const canDelete = computed(() => isOwnSubmission.value || authStore.user?.is_admin || hasPermission('submission', 'delete'))
const editing = ref(false)
const editNotes = ref('')
const showDeleteDialog = ref(false)
function startEdit() {
editing.value = true
editNotes.value = props.submission.notes || ''
}
async function handleSaveNotes() {
try {
await taskService.updateSubmission(props.taskId, props.submission.id, editNotes.value)
editing.value = false
emit('submissionUpdated')
toast({ title: 'Success', description: 'Submission updated successfully' })
} catch (error: any) {
toast({
title: 'Error',
description: error.response?.data?.detail || 'Failed to update submission',
variant: 'destructive'
})
}
}
async function handleDelete() {
try {
await taskService.deleteSubmission(props.taskId, props.submission.id)
emit('submissionUpdated')
toast({ title: 'Success', description: 'Submission deleted successfully' })
} catch (error: any) {
toast({
title: 'Error',
description: error.response?.data?.detail || 'Failed to delete submission',
variant: 'destructive'
})
} finally {
showDeleteDialog.value = false
}
}
const thumbnailBlobUrl = ref<string | null>(null)
function getFileExtension(filename: string): string {
+24 -3
View File
@@ -26,7 +26,25 @@
rows="2"
class="resize-none text-sm"
/>
<div class="flex justify-end">
<div class="flex items-center justify-between">
<div class="flex gap-1">
<Button
type="button"
size="sm"
:variant="newNoteType === 'internal' ? 'secondary' : 'ghost'"
@click="newNoteType = 'internal'"
>
Internal
</Button>
<Button
type="button"
size="sm"
:variant="newNoteType === 'client' ? 'secondary' : 'ghost'"
@click="newNoteType = 'client'"
>
Client
</Button>
</div>
<Button
@click="handleAddNote"
:disabled="!newNoteContent.trim() || submitting"
@@ -47,7 +65,7 @@ import { MessageSquarePlus } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import NoteItem from './NoteItem.vue'
import { taskService, type ProductionNote } from '@/services/task'
import { taskService, type ProductionNote, type NoteType } from '@/services/task'
import { useToast } from '@/components/ui/toast/use-toast'
const props = defineProps<{
@@ -62,6 +80,7 @@ const emit = defineEmits<{
const { toast } = useToast()
const newNoteContent = ref('')
const newNoteType = ref<NoteType>('internal')
const submitting = ref(false)
const replyToNoteId = ref<number | null>(null)
@@ -73,9 +92,11 @@ async function handleAddNote() {
await taskService.createTaskNote(
props.taskId,
newNoteContent.value,
replyToNoteId.value || undefined
replyToNoteId.value || undefined,
newNoteType.value
)
newNoteContent.value = ''
newNoteType.value = 'internal'
replyToNoteId.value = null
emit('notesUpdated')
toast({
@@ -11,8 +11,10 @@
<SubmissionCard
v-for="submission in submissions"
:key="submission.id"
:task-id="taskId"
:submission="submission"
@view="handleView"
@submission-updated="emit('submissionsUpdated')"
/>
</div>
</div>
@@ -114,7 +114,10 @@
</div>
</TableCell>
<TableCell>
<Badge variant="outline">{{ formatRole(user.role) }}</Badge>
<div class="flex flex-wrap items-center gap-1">
<Badge variant="outline">{{ formatRole(user.role) }}</Badge>
<Badge v-for="role in user.roles" :key="role.id" variant="secondary">{{ role.name }}</Badge>
</div>
</TableCell>
<TableCell>
<Badge v-if="user.is_admin" variant="destructive">Admin</Badge>
@@ -144,6 +147,10 @@
<Key class="h-4 w-4 mr-2" />
Reset Password
</DropdownMenuItem>
<DropdownMenuItem @click="handleManageRoles(user)">
<ShieldCheck class="h-4 w-4 mr-2" />
Manage Roles
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
v-if="!user.is_approved"
@@ -216,7 +223,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { MoreHorizontal, Eye, Check, UserX, UserCheck, Edit, Key, Trash2, ArrowUpDown } from "lucide-vue-next";
import { MoreHorizontal, Eye, Check, UserX, UserCheck, Edit, Key, Trash2, ArrowUpDown, ShieldCheck } from "lucide-vue-next";
import type { User } from "@/types/auth";
interface Props {
@@ -232,6 +239,7 @@ interface Emits {
(e: "approveUser", userId: number): void;
(e: "editUser", user: User): void;
(e: "resetPassword", user: User): void;
(e: "manageRoles", user: User): void;
(e: "deleteUser", user: User): void;
}
@@ -378,6 +386,10 @@ const handleResetPassword = (user: User) => {
emit("resetPassword", user);
};
const handleManageRoles = (user: User) => {
emit("manageRoles", user);
};
const handleDeleteUser = (user: User) => {
emit("deleteUser", user);
};
@@ -0,0 +1,74 @@
<template>
<Dialog :open="open" @update:open="$emit('update:open', $event)">
<DialogContent class="sm:max-w-sm">
<DialogHeader>
<DialogTitle>Manage Roles</DialogTitle>
<DialogDescription>
{{ user ? `${user.first_name} ${user.last_name}` : '' }} assign custom roles in addition to their base role
</DialogDescription>
</DialogHeader>
<div class="space-y-2 max-h-72 overflow-auto">
<label
v-for="role in roles"
:key="role.id"
class="flex items-center gap-2 rounded-md p-2 hover:bg-accent cursor-pointer"
>
<Checkbox
:model-value="selectedRoleIds.has(role.id)"
@update:model-value="(val) => toggleRole(role.id, !!val)"
/>
<span class="flex-1">{{ role.name }}</span>
<Badge :variant="role.is_system ? 'secondary' : 'outline'">{{ role.is_system ? 'System' : 'Custom' }}</Badge>
</label>
<p v-if="roles.length === 0" class="text-sm text-muted-foreground p-2">No roles available.</p>
</div>
<DialogFooter>
<Button type="button" variant="outline" @click="$emit('update:open', false)">Cancel</Button>
<Button :disabled="saving" @click="handleSave">{{ saving ? 'Saving...' : 'Save' }}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Badge } from '@/components/ui/badge'
import type { Role } from '@/services/role'
import type { User } from '@/types/auth'
interface Props {
open: boolean
user: User | null
roles: Role[]
saving?: boolean
}
const props = defineProps<Props>()
const emit = defineEmits<{
'update:open': [value: boolean]
saved: [roleIds: number[]]
}>()
const selectedRoleIds = ref<Set<number>>(new Set())
watch(() => props.open, (isOpen) => {
if (!isOpen) return
selectedRoleIds.value = new Set(props.user?.roles?.map(r => r.id) ?? [])
})
function toggleRole(id: number, checked: boolean) {
if (checked) selectedRoleIds.value.add(id)
else selectedRoleIds.value.delete(id)
}
function handleSave() {
emit('saved', [...selectedRoleIds.value])
}
</script>
+11 -1
View File
@@ -15,5 +15,15 @@ export function usePermission() {
authStore.user?.role === 'coordinator' || !!authStore.user?.is_admin
)
return { isAdmin, isCoordinatorOrAdmin }
/**
* Resource/action check backed by the new multi-role permission system
* (e.g. hasPermission('shot', 'create')). Reads authStore.user.permissions,
* which is only ever populated on the current session's own user.
*/
function hasPermission(resource: string, action: string): boolean {
if (authStore.isAdmin) return true
return authStore.user?.permissions?.includes(`${resource}:${action}`) ?? false
}
return { isAdmin, isCoordinatorOrAdmin, hasPermission }
}
+12 -2
View File
@@ -129,12 +129,22 @@ const routes: RouteRecordRaw[] = [
path: '/admin/deleted-items',
name: 'RecoveryManagement',
component: () => import('@/views/admin/DeletedItemsManagementView.vue'),
meta: {
requiresAuth: true,
meta: {
requiresAuth: true,
adminPermission: 'required',
title: 'Recovery Management'
}
},
{
path: '/admin/roles',
name: 'RoleManagement',
component: () => import('@/views/admin/RoleManagementView.vue'),
meta: {
requiresAuth: true,
adminPermission: 'required',
title: 'Role Management'
}
},
// Developer routes
{
+63
View File
@@ -0,0 +1,63 @@
import { apiClient } from './api'
export interface Permission {
id: number
resource: string
action: string
description?: string | null
}
export interface Role {
id: number
name: string
description?: string | null
is_system: boolean
permissions: Permission[]
user_count: number
created_at: string
updated_at: string
}
export interface RoleCreate {
name: string
description?: string
permission_ids?: number[]
}
export interface RoleUpdate {
name?: string
description?: string
permission_ids?: number[]
}
export const roleService = {
async getRoles(): Promise<Role[]> {
const response = await apiClient.get('/roles/')
return response.data
},
async getPermissions(): Promise<Permission[]> {
const response = await apiClient.get('/roles/permissions')
return response.data
},
async createRole(data: RoleCreate): Promise<Role> {
const response = await apiClient.post('/roles/', data)
return response.data
},
async updateRole(roleId: number, data: RoleUpdate): Promise<Role> {
const response = await apiClient.put(`/roles/${roleId}`, data)
return response.data
},
async deleteRole(roleId: number): Promise<{ message: string }> {
const response = await apiClient.delete(`/roles/${roleId}`)
return response.data
},
async updateUserRoles(userId: number, roleIds: number[]): Promise<{ message: string; user_id: number; role_ids: number[] }> {
const response = await apiClient.put(`/users/${userId}/roles`, { role_ids: roleIds })
return response.data
}
}
+15 -2
View File
@@ -55,9 +55,12 @@ export interface TaskStatusInfo {
assigned_user_id?: number
}
export type NoteType = 'internal' | 'client'
export interface ProductionNote {
id: number
content: string
note_type: NoteType
parent_note_id?: number
task_id: number
user_id: number
@@ -184,10 +187,11 @@ class TaskService {
return response.data
}
async createTaskNote(taskId: number, content: string, parentNoteId?: number): Promise<ProductionNote> {
async createTaskNote(taskId: number, content: string, parentNoteId?: number, noteType: NoteType = 'internal'): Promise<ProductionNote> {
const response = await apiClient.post(`/tasks/${taskId}/notes`, {
content,
parent_note_id: parentNoteId
parent_note_id: parentNoteId,
note_type: noteType
})
return response.data
}
@@ -256,6 +260,15 @@ class TaskService {
return response.data
}
async updateSubmission(taskId: number, submissionId: number, notes: string): Promise<Submission> {
const response = await apiClient.put(`/tasks/${taskId}/submissions/${submissionId}`, { notes })
return response.data
}
async deleteSubmission(taskId: number, submissionId: number): Promise<void> {
await apiClient.delete(`/tasks/${taskId}/submissions/${submissionId}`)
}
async createAssetTask(assetId: number, taskType: string): Promise<TaskStatusInfo> {
const response = await apiClient.post(`/assets/${assetId}/tasks?task_type=${taskType}`)
return response.data
+99
View File
@@ -0,0 +1,99 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { roleService, type Role, type Permission, type RoleCreate, type RoleUpdate } from '@/services/role'
// Cache duration: 5 minutes
const CACHE_DURATION = 5 * 60 * 1000
export const useRolesStore = defineStore('roles', () => {
const roles = ref<Role[] | null>(null)
const permissions = ref<Permission[] | null>(null)
const rolesLastFetched = ref<number>(0)
const permissionsLastFetched = ref<number>(0)
const isLoading = ref(false)
const error = ref<string | null>(null)
let rolesInFlight: Promise<Role[]> | null = null
let permissionsInFlight: Promise<Permission[]> | null = null
async function fetchRoles(force = false): Promise<Role[]> {
const now = Date.now()
if (!force && roles.value && now - rolesLastFetched.value < CACHE_DURATION) {
return roles.value
}
if (rolesInFlight) return rolesInFlight
isLoading.value = true
error.value = null
rolesInFlight = (async () => {
try {
const data = await roleService.getRoles()
roles.value = data
rolesLastFetched.value = Date.now()
return data
} catch (err: any) {
error.value = err.response?.data?.detail || 'Failed to fetch roles'
throw err
} finally {
isLoading.value = false
rolesInFlight = null
}
})()
return rolesInFlight
}
async function fetchPermissions(force = false): Promise<Permission[]> {
const now = Date.now()
if (!force && permissions.value && now - permissionsLastFetched.value < CACHE_DURATION) {
return permissions.value
}
if (permissionsInFlight) return permissionsInFlight
permissionsInFlight = (async () => {
try {
const data = await roleService.getPermissions()
permissions.value = data
permissionsLastFetched.value = Date.now()
return data
} catch (err: any) {
error.value = err.response?.data?.detail || 'Failed to fetch permissions'
throw err
} finally {
permissionsInFlight = null
}
})()
return permissionsInFlight
}
async function createRole(data: RoleCreate): Promise<Role> {
const role = await roleService.createRole(data)
if (roles.value) roles.value = [...roles.value, role]
return role
}
async function updateRole(roleId: number, data: RoleUpdate): Promise<Role> {
const role = await roleService.updateRole(roleId, data)
if (roles.value) roles.value = roles.value.map(r => r.id === roleId ? role : r)
return role
}
async function deleteRole(roleId: number): Promise<void> {
await roleService.deleteRole(roleId)
if (roles.value) roles.value = roles.value.filter(r => r.id !== roleId)
}
return {
roles,
permissions,
isLoading,
error,
fetchRoles,
fetchPermissions,
createRole,
updateRole,
deleteRole
}
})
+9
View File
@@ -1,3 +1,9 @@
export interface RoleSummary {
id: number
name: string
is_system: boolean
}
export interface User {
id: number
email: string
@@ -9,6 +15,9 @@ export interface User {
avatar_url?: string | null
created_at: string
updated_at: string
roles?: RoleSummary[]
/** Only populated on the current session's own user (from GET /users/me). */
permissions?: string[]
}
export interface LoginCredentials {
+42
View File
@@ -56,6 +56,7 @@
@approve-user="handleApproveUser"
@edit-user="handleEditUser"
@reset-password="handleResetPassword"
@manage-roles="handleManageRoles"
@delete-user="handleDeleteUser"
/>
</div>
@@ -112,6 +113,16 @@
:is-deleting="isDeletingUser"
/>
<!-- User Roles (custom multi-role) Dialog -->
<UserRolesDialog
:open="showRolesDialog"
@update:open="showRolesDialog = $event"
:user="selectedUser"
:roles="rolesStore.roles ?? []"
:saving="isSavingRoles"
@saved="handleUserRolesSubmit"
/>
<!-- Success Toast -->
<div v-if="successMessage" class="fixed bottom-4 right-4 z-50">
<Alert class="w-80 bg-green-50 border-green-200 dark:bg-green-950 dark:border-green-800">
@@ -131,12 +142,15 @@ import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Users, UserPlus, RefreshCw, AlertCircle, Loader2, CheckCircle } from 'lucide-vue-next'
import { useUserStore } from '@/stores/user'
import { useAuthStore } from '@/stores/auth'
import { useRolesStore } from '@/stores/roles'
import { roleService } from '@/services/role'
import PendingUsersDashboard from '@/components/user/PendingUsersDashboard.vue'
import UserManagementTable from '@/components/user/UserManagementTable.vue'
import UserCreateDialog from '@/components/user/UserCreateDialog.vue'
import UserEditDialog from '@/components/user/UserEditDialog.vue'
import PasswordResetDialog from '@/components/user/PasswordResetDialog.vue'
import UserDeleteConfirmDialog from '@/components/user/UserDeleteConfirmDialog.vue'
import UserRolesDialog from '@/components/user/UserRolesDialog.vue'
import type { User } from '@/types/auth'
import type { UserCreateData } from '@/components/user/UserCreateDialog.vue'
import type { UserEditData } from '@/components/user/UserEditDialog.vue'
@@ -144,6 +158,7 @@ import type { UserEditData } from '@/components/user/UserEditDialog.vue'
const router = useRouter()
const userStore = useUserStore()
const authStore = useAuthStore()
const rolesStore = useRolesStore()
// Local state
const processingUserId = ref<number | null>(null)
@@ -157,12 +172,14 @@ const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const showPasswordResetDialog = ref(false)
const showDeleteDialog = ref(false)
const showRolesDialog = ref(false)
// Loading states
const isCreatingUser = ref(false)
const isEditingUser = ref(false)
const isResettingPassword = ref(false)
const isDeletingUser = ref(false)
const isSavingRoles = ref(false)
// Computed
const users = computed(() => userStore.users)
@@ -287,6 +304,31 @@ const handleResetPassword = (user: User) => {
showPasswordResetDialog.value = true
}
const handleManageRoles = async (user: User) => {
selectedUser.value = user
showRolesDialog.value = true
try {
await rolesStore.fetchRoles()
} catch (err) {
console.error('Failed to load roles:', err)
}
}
const handleUserRolesSubmit = async (roleIds: number[]) => {
if (!selectedUser.value) return
try {
isSavingRoles.value = true
await roleService.updateUserRoles(selectedUser.value.id, roleIds)
showRolesDialog.value = false
showSuccessMessage('User roles updated successfully')
await refreshData()
} catch (err: any) {
showErrorMessage(err.response?.data?.detail || 'Failed to update user roles')
} finally {
isSavingRoles.value = false
}
}
const handlePasswordResetSubmit = async (userId: number, password: string) => {
try {
isResettingPassword.value = true
@@ -0,0 +1,171 @@
<template>
<div class="container mx-auto py-6 space-y-6">
<div class="flex items-center justify-between">
<div>
<h1 class="text-3xl font-bold">Role Management</h1>
<p class="text-muted-foreground">
Create custom roles and edit create/edit/delete permissions for assets, shots, and tasks
</p>
</div>
<Button @click="openCreateDialog">
<Plus class="w-4 h-4 mr-2" />
Create Role
</Button>
</div>
<Card>
<CardContent class="p-0">
<div v-if="isLoading" class="p-6 text-center text-muted-foreground">Loading roles...</div>
<table v-else class="w-full text-sm">
<thead>
<tr class="border-b bg-muted/50">
<th class="text-left font-medium p-3">Name</th>
<th class="text-left font-medium p-3">Description</th>
<th class="text-left font-medium p-3">Permissions</th>
<th class="text-left font-medium p-3">Users</th>
<th class="text-right font-medium p-3">Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="role in roles" :key="role.id" class="border-b last:border-b-0">
<td class="p-3 font-medium">
{{ role.name }}
<Badge :variant="role.is_system ? 'secondary' : 'outline'" class="ml-2">
{{ role.is_system ? 'System' : 'Custom' }}
</Badge>
</td>
<td class="p-3 text-muted-foreground">{{ role.description || '—' }}</td>
<td class="p-3">{{ role.permissions.length }}</td>
<td class="p-3">{{ role.user_count }}</td>
<td class="p-3 text-right space-x-2">
<Button variant="ghost" size="sm" @click="openEditDialog(role)">
<Pencil class="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="sm"
:disabled="role.is_system || role.user_count > 0"
:title="role.is_system ? 'System roles cannot be deleted' : role.user_count > 0 ? 'Reassign users before deleting' : 'Delete role'"
@click="confirmDelete(role)"
>
<Trash2 class="w-4 h-4" />
</Button>
</td>
</tr>
</tbody>
</table>
</CardContent>
</Card>
<RoleFormDialog
v-model:open="showFormDialog"
:role="editingRole"
:permissions="permissions"
:saving="isSaving"
@saved="handleSave"
/>
<AlertDialog :open="showDeleteDialog" @update:open="(val: boolean) => { showDeleteDialog = val }">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete role "{{ roleToDelete?.name }}"?</AlertDialogTitle>
<AlertDialogDescription>This cannot be undone.</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction @click="handleDelete">Delete</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Plus, Pencil, Trash2 } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent } from '@/components/ui/card'
import {
AlertDialog, AlertDialogContent, AlertDialogHeader, AlertDialogTitle,
AlertDialogDescription, AlertDialogFooter, AlertDialogCancel, AlertDialogAction
} from '@/components/ui/alert-dialog'
import { useToast } from '@/components/ui/toast/use-toast'
import { useRolesStore } from '@/stores/roles'
import RoleFormDialog from '@/components/role/RoleFormDialog.vue'
import type { Role } from '@/services/role'
const { toast } = useToast()
const rolesStore = useRolesStore()
const isLoading = ref(true)
const isSaving = ref(false)
const showFormDialog = ref(false)
const editingRole = ref<Role | null>(null)
const showDeleteDialog = ref(false)
const roleToDelete = ref<Role | null>(null)
const roles = computed(() => rolesStore.roles ?? [])
const permissions = computed(() => rolesStore.permissions ?? [])
onMounted(async () => {
try {
await Promise.all([rolesStore.fetchRoles(), rolesStore.fetchPermissions()])
} catch (err: any) {
toast({ title: 'Error', description: err.response?.data?.detail || 'Failed to load roles', variant: 'destructive' })
} finally {
isLoading.value = false
}
})
function openCreateDialog() {
editingRole.value = null
showFormDialog.value = true
}
function openEditDialog(role: Role) {
editingRole.value = role
showFormDialog.value = true
}
async function handleSave(data: { name?: string; description?: string; permission_ids: number[] }) {
isSaving.value = true
try {
if (editingRole.value) {
await rolesStore.updateRole(editingRole.value.id, data)
toast({ title: 'Role updated', description: `"${editingRole.value.name}" was updated.` })
} else {
const role = await rolesStore.createRole({ name: data.name!, description: data.description, permission_ids: data.permission_ids })
toast({ title: 'Role created', description: `"${role.name}" was created.` })
}
showFormDialog.value = false
} catch (err: any) {
toast({ title: 'Error', description: err.response?.data?.detail || 'Failed to save role', variant: 'destructive' })
} finally {
isSaving.value = false
}
}
function confirmDelete(role: Role) {
roleToDelete.value = role
showDeleteDialog.value = true
}
async function handleDelete() {
// Captured locally: AlertDialogAction closes the dialog (and fires @update:open)
// as part of the same click, so showDeleteDialog can't be trusted to still
// reflect "open" by the time this runs - roleToDelete is never reset by that
// close, only here, so it's safe to read.
const role = roleToDelete.value
if (!role) return
try {
await rolesStore.deleteRole(role.id)
toast({ title: 'Role deleted', description: `"${role.name}" was deleted.` })
} catch (err: any) {
toast({ title: 'Error', description: err.response?.data?.detail || 'Failed to delete role', variant: 'destructive' })
} finally {
showDeleteDialog.value = false
roleToDelete.value = null
}
}
</script>