Add paginated users/roles, user status, frontend permissions, profile pictures, identifier file storage
- Users page: paginated, searchable, sortable with inline roles (no N+1) - Roles page: paginated, searchable, sortable + /roles/all for dropdowns - User is_active field with migration, PATCH toggle, auth check (disabled=401) - Frontend permission checks: auth store loads permissions, sidebar/buttons conditional - Profile pictures via file storage for users and members, avatar component - Identifier images use file storage API instead of base64 - Fix TypeScript errors across admin UI - 64 API tests passing (10 new)
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import type { MemberIdentifier } from '@/types/account'
|
||||
import type { PaginatedResponse } from '@forte/shared/schemas'
|
||||
|
||||
export const identifierKeys = {
|
||||
all: (memberId: string) => ['members', memberId, 'identifiers'] as const,
|
||||
@@ -9,7 +10,7 @@ export const identifierKeys = {
|
||||
export function identifierListOptions(memberId: string) {
|
||||
return queryOptions({
|
||||
queryKey: identifierKeys.all(memberId),
|
||||
queryFn: () => api.get<{ data: MemberIdentifier[] }>(`/v1/members/${memberId}/identifiers`),
|
||||
queryFn: () => api.get<PaginatedResponse<MemberIdentifier>>(`/v1/members/${memberId}/identifiers`, { page: 1, limit: 100, order: 'asc' }),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import type { PaymentMethod } from '@/types/account'
|
||||
import type { PaginatedResponse, PaginationInput } from '@forte/shared/schemas'
|
||||
|
||||
export const paymentMethodKeys = {
|
||||
all: (accountId: string) => ['accounts', accountId, 'payment-methods'] as const,
|
||||
list: (accountId: string, params: PaginationInput) => [...paymentMethodKeys.all(accountId), params] as const,
|
||||
}
|
||||
|
||||
export function paymentMethodListOptions(accountId: string) {
|
||||
export function paymentMethodListOptions(accountId: string, params: PaginationInput) {
|
||||
return queryOptions({
|
||||
queryKey: paymentMethodKeys.all(accountId),
|
||||
queryFn: () => api.get<{ data: PaymentMethod[] }>(`/v1/accounts/${accountId}/payment-methods`),
|
||||
queryKey: paymentMethodKeys.list(accountId, params),
|
||||
queryFn: () => api.get<PaginatedResponse<PaymentMethod>>(`/v1/accounts/${accountId}/payment-methods`, params),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import type { ProcessorLink } from '@/types/account'
|
||||
import type { PaginatedResponse, PaginationInput } from '@forte/shared/schemas'
|
||||
|
||||
export const processorLinkKeys = {
|
||||
all: (accountId: string) => ['accounts', accountId, 'processor-links'] as const,
|
||||
list: (accountId: string, params: PaginationInput) => [...processorLinkKeys.all(accountId), params] as const,
|
||||
}
|
||||
|
||||
export function processorLinkListOptions(accountId: string) {
|
||||
export function processorLinkListOptions(accountId: string, params: PaginationInput) {
|
||||
return queryOptions({
|
||||
queryKey: processorLinkKeys.all(accountId),
|
||||
queryFn: () => api.get<{ data: ProcessorLink[] }>(`/v1/accounts/${accountId}/processor-links`),
|
||||
queryKey: processorLinkKeys.list(accountId, params),
|
||||
queryFn: () => api.get<PaginatedResponse<ProcessorLink>>(`/v1/accounts/${accountId}/processor-links`, params),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import type { Permission, Role } from '@/types/rbac'
|
||||
import type { PaginationInput, PaginatedResponse } from '@forte/shared/schemas'
|
||||
|
||||
export const rbacKeys = {
|
||||
permissions: ['permissions'] as const,
|
||||
roles: ['roles'] as const,
|
||||
roleList: (params: PaginationInput) => ['roles', 'list', params] as const,
|
||||
role: (id: string) => ['roles', id] as const,
|
||||
userRoles: (userId: string) => ['users', userId, 'roles'] as const,
|
||||
myPermissions: ['me', 'permissions'] as const,
|
||||
@@ -17,10 +19,19 @@ export function permissionListOptions() {
|
||||
})
|
||||
}
|
||||
|
||||
/** All roles (for dropdowns, selectors) */
|
||||
export function roleListOptions() {
|
||||
return queryOptions({
|
||||
queryKey: rbacKeys.roles,
|
||||
queryFn: () => api.get<{ data: Role[] }>('/v1/roles'),
|
||||
queryFn: () => api.get<{ data: Role[] }>('/v1/roles/all'),
|
||||
})
|
||||
}
|
||||
|
||||
/** Paginated roles (for the roles list page) */
|
||||
export function rolePageOptions(params: PaginationInput) {
|
||||
return queryOptions({
|
||||
queryKey: rbacKeys.roleList(params),
|
||||
queryFn: () => api.get<PaginatedResponse<Role>>('/v1/roles', params as Record<string, unknown>),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import type { TaxExemption } from '@/types/account'
|
||||
import type { PaginatedResponse, PaginationInput } from '@forte/shared/schemas'
|
||||
|
||||
export const taxExemptionKeys = {
|
||||
all: (accountId: string) => ['accounts', accountId, 'tax-exemptions'] as const,
|
||||
list: (accountId: string, params: PaginationInput) => [...taxExemptionKeys.all(accountId), params] as const,
|
||||
}
|
||||
|
||||
export function taxExemptionListOptions(accountId: string) {
|
||||
export function taxExemptionListOptions(accountId: string, params: PaginationInput) {
|
||||
return queryOptions({
|
||||
queryKey: taxExemptionKeys.all(accountId),
|
||||
queryFn: () => api.get<{ data: TaxExemption[] }>(`/v1/accounts/${accountId}/tax-exemptions`),
|
||||
queryKey: taxExemptionKeys.list(accountId, params),
|
||||
queryFn: () => api.get<PaginatedResponse<TaxExemption>>(`/v1/accounts/${accountId}/tax-exemptions`, params),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import type { PaginationInput, PaginatedResponse } from '@forte/shared/schemas'
|
||||
|
||||
export interface UserRole {
|
||||
id: string
|
||||
name: string
|
||||
slug: string
|
||||
isSystem: boolean
|
||||
}
|
||||
|
||||
export interface UserRecord {
|
||||
id: string
|
||||
@@ -7,16 +15,31 @@ export interface UserRecord {
|
||||
firstName: string
|
||||
lastName: string
|
||||
role: string
|
||||
isActive: boolean
|
||||
createdAt: string
|
||||
roles: UserRole[]
|
||||
}
|
||||
|
||||
export const userKeys = {
|
||||
list: (params: PaginationInput) => ['users', params] as const,
|
||||
roles: (userId: string) => ['users', userId, 'roles'] as const,
|
||||
}
|
||||
|
||||
export function userListOptions(params: PaginationInput) {
|
||||
return queryOptions({
|
||||
queryKey: userKeys.list(params),
|
||||
queryFn: () => api.get<PaginatedResponse<UserRecord>>('/v1/users', params as Record<string, unknown>),
|
||||
})
|
||||
}
|
||||
|
||||
export function userRolesOptions(userId: string) {
|
||||
return queryOptions({
|
||||
queryKey: userKeys.roles(userId),
|
||||
queryFn: () => api.get<{ data: { id: string; name: string; slug: string; isSystem: boolean }[] }>(`/v1/users/${userId}/roles`),
|
||||
queryFn: () => api.get<{ data: UserRole[] }>(`/v1/users/${userId}/roles`),
|
||||
})
|
||||
}
|
||||
|
||||
export const userMutations = {
|
||||
toggleStatus: (userId: string, isActive: boolean) =>
|
||||
api.patch<{ id: string; isActive: boolean }>(`/v1/users/${userId}/status`, { isActive }),
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { useRef } from 'react'
|
||||
import { useRef, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import type { MemberIdentifier } from '@/types/account'
|
||||
import { Upload } from 'lucide-react'
|
||||
import { Upload, X } from 'lucide-react'
|
||||
|
||||
const ID_TYPES = [
|
||||
{ value: 'drivers_license', label: "Driver's License / State ID" },
|
||||
@@ -14,22 +14,18 @@ const ID_TYPES = [
|
||||
{ value: 'school_id', label: 'School ID' },
|
||||
]
|
||||
|
||||
export interface IdentifierFiles {
|
||||
front?: File
|
||||
back?: File
|
||||
}
|
||||
|
||||
interface IdentifierFormProps {
|
||||
memberId: string
|
||||
defaultValues?: Partial<MemberIdentifier>
|
||||
onSubmit: (data: Record<string, unknown>) => void
|
||||
onSubmit: (data: Record<string, unknown>, files: IdentifierFiles) => void
|
||||
loading?: boolean
|
||||
}
|
||||
|
||||
function fileToBase64(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(reader.result as string)
|
||||
reader.onerror = reject
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
}
|
||||
|
||||
export function IdentifierForm({ memberId, defaultValues, onSubmit, loading }: IdentifierFormProps) {
|
||||
const { register, handleSubmit, setValue, watch } = useForm({
|
||||
defaultValues: {
|
||||
@@ -41,20 +37,38 @@ export function IdentifierForm({ memberId, defaultValues, onSubmit, loading }: I
|
||||
expiresAt: defaultValues?.expiresAt ?? '',
|
||||
notes: defaultValues?.notes ?? '',
|
||||
isPrimary: defaultValues?.isPrimary ?? false,
|
||||
imageFront: defaultValues?.imageFront ?? '',
|
||||
imageBack: defaultValues?.imageBack ?? '',
|
||||
},
|
||||
})
|
||||
|
||||
const frontInputRef = useRef<HTMLInputElement>(null)
|
||||
const backInputRef = useRef<HTMLInputElement>(null)
|
||||
const imageFront = watch('imageFront')
|
||||
const imageBack = watch('imageBack')
|
||||
const [frontFile, setFrontFile] = useState<File | null>(null)
|
||||
const [backFile, setBackFile] = useState<File | null>(null)
|
||||
const [frontPreview, setFrontPreview] = useState<string | null>(null)
|
||||
const [backPreview, setBackPreview] = useState<string | null>(null)
|
||||
const idType = watch('type')
|
||||
|
||||
async function handleFileSelect(field: 'imageFront' | 'imageBack', file: File) {
|
||||
const base64 = await fileToBase64(file)
|
||||
setValue(field, base64)
|
||||
function handleFileSelect(side: 'front' | 'back', file: File) {
|
||||
const url = URL.createObjectURL(file)
|
||||
if (side === 'front') {
|
||||
setFrontFile(file)
|
||||
setFrontPreview(url)
|
||||
} else {
|
||||
setBackFile(file)
|
||||
setBackPreview(url)
|
||||
}
|
||||
}
|
||||
|
||||
function clearFile(side: 'front' | 'back') {
|
||||
if (side === 'front') {
|
||||
if (frontPreview) URL.revokeObjectURL(frontPreview)
|
||||
setFrontFile(null)
|
||||
setFrontPreview(null)
|
||||
} else {
|
||||
if (backPreview) URL.revokeObjectURL(backPreview)
|
||||
setBackFile(null)
|
||||
setBackPreview(null)
|
||||
}
|
||||
}
|
||||
|
||||
function handleFormSubmit(data: Record<string, unknown>) {
|
||||
@@ -62,14 +76,17 @@ export function IdentifierForm({ memberId, defaultValues, onSubmit, loading }: I
|
||||
for (const [key, value] of Object.entries(data)) {
|
||||
cleaned[key] = value === '' ? undefined : value
|
||||
}
|
||||
onSubmit(cleaned)
|
||||
onSubmit(cleaned, {
|
||||
front: frontFile ?? undefined,
|
||||
back: backFile ?? undefined,
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(handleFormSubmit)} noValidate className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>ID Type *</Label>
|
||||
<Select value={idType} onValueChange={(v) => setValue('type', v)}>
|
||||
<Select value={idType} onValueChange={(v: string) => setValue('type', v as 'drivers_license' | 'passport' | 'school_id')}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
@@ -114,21 +131,21 @@ export function IdentifierForm({ memberId, defaultValues, onSubmit, loading }: I
|
||||
<input
|
||||
ref={frontInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
className="hidden"
|
||||
onChange={(e) => e.target.files?.[0] && handleFileSelect('imageFront', e.target.files[0])}
|
||||
onChange={(e) => e.target.files?.[0] && handleFileSelect('front', e.target.files[0])}
|
||||
/>
|
||||
{imageFront ? (
|
||||
{frontPreview ? (
|
||||
<div className="relative">
|
||||
<img src={imageFront} alt="ID front" className="rounded-md border max-h-32 w-full object-cover" />
|
||||
<img src={frontPreview} alt="ID front" className="rounded-md border max-h-32 w-full object-cover" />
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="absolute top-1 right-1"
|
||||
onClick={() => setValue('imageFront', '')}
|
||||
className="absolute top-1 right-1 h-6 w-6 p-0"
|
||||
onClick={() => clearFile('front')}
|
||||
>
|
||||
Remove
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
@@ -142,21 +159,21 @@ export function IdentifierForm({ memberId, defaultValues, onSubmit, loading }: I
|
||||
<input
|
||||
ref={backInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
className="hidden"
|
||||
onChange={(e) => e.target.files?.[0] && handleFileSelect('imageBack', e.target.files[0])}
|
||||
onChange={(e) => e.target.files?.[0] && handleFileSelect('back', e.target.files[0])}
|
||||
/>
|
||||
{imageBack ? (
|
||||
{backPreview ? (
|
||||
<div className="relative">
|
||||
<img src={imageBack} alt="ID back" className="rounded-md border max-h-32 w-full object-cover" />
|
||||
<img src={backPreview} alt="ID back" className="rounded-md border max-h-32 w-full object-cover" />
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="absolute top-1 right-1"
|
||||
onClick={() => setValue('imageBack', '')}
|
||||
className="absolute top-1 right-1 h-6 w-6 p-0"
|
||||
onClick={() => clearFile('back')}
|
||||
>
|
||||
Remove
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
|
||||
@@ -20,7 +20,7 @@ export function PaymentMethodForm({ accountId, onSubmit, loading }: PaymentMetho
|
||||
setValue,
|
||||
watch,
|
||||
formState: { errors },
|
||||
} = useForm<PaymentMethodCreateInput>({
|
||||
} = useForm({
|
||||
resolver: zodResolver(PaymentMethodCreateSchema),
|
||||
defaultValues: {
|
||||
accountId,
|
||||
|
||||
@@ -18,7 +18,7 @@ export function TaxExemptionForm({ accountId, onSubmit, loading }: TaxExemptionF
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
} = useForm<TaxExemptionCreateInput>({
|
||||
} = useForm({
|
||||
resolver: zodResolver(TaxExemptionCreateSchema),
|
||||
defaultValues: {
|
||||
accountId,
|
||||
|
||||
146
packages/admin/src/components/shared/avatar-upload.tsx
Normal file
146
packages/admin/src/components/shared/avatar-upload.tsx
Normal file
@@ -0,0 +1,146 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Camera, User } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
interface FileRecord {
|
||||
id: string
|
||||
path: string
|
||||
url: string
|
||||
filename: string
|
||||
}
|
||||
|
||||
function entityFilesOptions(entityType: string, entityId: string) {
|
||||
return queryOptions({
|
||||
queryKey: ['files', entityType, entityId],
|
||||
queryFn: () => api.get<{ data: FileRecord[] }>('/v1/files', { entityType, entityId }),
|
||||
enabled: !!entityId,
|
||||
})
|
||||
}
|
||||
|
||||
interface AvatarUploadProps {
|
||||
entityType: 'user' | 'member'
|
||||
entityId: string
|
||||
size?: 'sm' | 'md' | 'lg'
|
||||
}
|
||||
|
||||
const sizeClasses = {
|
||||
sm: 'h-8 w-8',
|
||||
md: 'h-16 w-16',
|
||||
lg: 'h-24 w-24',
|
||||
}
|
||||
|
||||
const iconSizes = {
|
||||
sm: 'h-4 w-4',
|
||||
md: 'h-8 w-8',
|
||||
lg: 'h-12 w-12',
|
||||
}
|
||||
|
||||
export function AvatarUpload({ entityType, entityId, size = 'lg' }: AvatarUploadProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const token = useAuthStore((s) => s.token)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
|
||||
const { data: filesData } = useQuery(entityFilesOptions(entityType, entityId))
|
||||
|
||||
// Find profile image from files
|
||||
const profileFile = filesData?.data?.find((f) => f.path.includes('/profile-'))
|
||||
const imageUrl = profileFile ? `/v1/files/serve/${profileFile.path}` : null
|
||||
|
||||
async function handleUpload(file: File) {
|
||||
setUploading(true)
|
||||
try {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('entityType', entityType)
|
||||
formData.append('entityId', entityId)
|
||||
formData.append('category', 'profile')
|
||||
|
||||
// Delete existing profile image first
|
||||
if (profileFile) {
|
||||
await api.del(`/v1/files/${profileFile.id}`)
|
||||
}
|
||||
|
||||
const res = await fetch('/v1/files', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
body: formData,
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const err = await res.json()
|
||||
throw new Error(err.error?.message ?? 'Upload failed')
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: ['files', entityType, entityId] })
|
||||
toast.success('Profile picture updated')
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Upload failed')
|
||||
} finally {
|
||||
setUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) handleUpload(file)
|
||||
// Reset input so same file can be re-selected
|
||||
e.target.value = ''
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative inline-block">
|
||||
<div
|
||||
className={`${sizeClasses[size]} rounded-full bg-muted flex items-center justify-center overflow-hidden border-2 border-border`}
|
||||
>
|
||||
{imageUrl ? (
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt="Profile"
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
) : (
|
||||
<User className={`${iconSizes[size]} text-muted-foreground`} />
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="absolute -bottom-1 -right-1 h-7 w-7 rounded-full p-0"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={uploading}
|
||||
>
|
||||
<Camera className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp"
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Display-only avatar (no upload button) */
|
||||
export function Avatar({ entityType, entityId, size = 'sm' }: AvatarUploadProps) {
|
||||
const { data: filesData } = useQuery(entityFilesOptions(entityType, entityId))
|
||||
const profileFile = filesData?.data?.find((f) => f.path.includes('/profile-'))
|
||||
const imageUrl = profileFile ? `/v1/files/serve/${profileFile.path}` : null
|
||||
|
||||
return (
|
||||
<div className={`${sizeClasses[size]} rounded-full bg-muted flex items-center justify-center overflow-hidden`}>
|
||||
{imageUrl ? (
|
||||
<img src={imageUrl} alt="Profile" className="h-full w-full object-cover" />
|
||||
) : (
|
||||
<User className={`${iconSizes[size]} text-muted-foreground`} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -23,12 +23,12 @@ export function usePagination() {
|
||||
|
||||
function setParams(updates: Partial<PaginationSearch>) {
|
||||
navigate({
|
||||
search: (prev: PaginationSearch) => ({
|
||||
search: ((prev: PaginationSearch) => ({
|
||||
...prev,
|
||||
...updates,
|
||||
// Reset to page 1 when search or sort changes
|
||||
page: updates.q !== undefined || updates.sort !== undefined ? 1 : (updates.page ?? prev.page),
|
||||
}),
|
||||
})) as any,
|
||||
replace: true,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { createFileRoute, Outlet, Link, redirect, useRouter } from '@tanstack/react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useEffect } from 'react'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import { myPermissionsOptions } from '@/api/rbac'
|
||||
import { Avatar } from '@/components/shared/avatar-upload'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Users, UserRound, HelpCircle, Shield, UserCog, LogOut, User } from 'lucide-react'
|
||||
|
||||
@@ -13,16 +17,48 @@ export const Route = createFileRoute('/_authenticated')({
|
||||
component: AuthenticatedLayout,
|
||||
})
|
||||
|
||||
function NavLink({ to, icon, label }: { to: string; icon: React.ReactNode; label: string }) {
|
||||
return (
|
||||
<Link
|
||||
to={to as '/accounts'}
|
||||
search={{} as any}
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground' }}
|
||||
>
|
||||
{icon}
|
||||
{label}
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
|
||||
function AuthenticatedLayout() {
|
||||
const router = useRouter()
|
||||
const user = useAuthStore((s) => s.user)
|
||||
const logout = useAuthStore((s) => s.logout)
|
||||
const hasPermission = useAuthStore((s) => s.hasPermission)
|
||||
const setPermissions = useAuthStore((s) => s.setPermissions)
|
||||
const permissionsLoaded = useAuthStore((s) => s.permissionsLoaded)
|
||||
|
||||
// Fetch permissions on mount
|
||||
const { data: permData } = useQuery({
|
||||
...myPermissionsOptions(),
|
||||
enabled: !!useAuthStore.getState().token,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (permData?.permissions) {
|
||||
setPermissions(permData.permissions)
|
||||
}
|
||||
}, [permData, setPermissions])
|
||||
|
||||
function handleLogout() {
|
||||
logout()
|
||||
router.navigate({ to: '/login', replace: true })
|
||||
}
|
||||
|
||||
const canViewAccounts = !permissionsLoaded || hasPermission('accounts.view')
|
||||
const canViewUsers = !permissionsLoaded || hasPermission('users.view')
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-background text-foreground">
|
||||
<div className="flex">
|
||||
@@ -31,59 +67,37 @@ function AuthenticatedLayout() {
|
||||
<h2 className="text-lg font-semibold text-sidebar-foreground">Forte</h2>
|
||||
</div>
|
||||
|
||||
{/* Sidebar links use `as any` on search because TanStack Router
|
||||
requires the full validated search shape, but these links just
|
||||
navigate to the page with default params. */}
|
||||
<div className="flex-1 px-3 space-y-1">
|
||||
<Link
|
||||
to="/accounts"
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground' }}
|
||||
>
|
||||
<Users className="h-4 w-4" />
|
||||
Accounts
|
||||
</Link>
|
||||
<Link
|
||||
to="/members"
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground' }}
|
||||
>
|
||||
<UserRound className="h-4 w-4" />
|
||||
Members
|
||||
</Link>
|
||||
<div className="mt-4 mb-1 px-3">
|
||||
<span className="text-xs font-semibold text-sidebar-foreground/50 uppercase tracking-wide">Admin</span>
|
||||
</div>
|
||||
<Link
|
||||
to="/users"
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground' }}
|
||||
>
|
||||
<UserCog className="h-4 w-4" />
|
||||
Users
|
||||
</Link>
|
||||
<Link
|
||||
to="/roles"
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground' }}
|
||||
>
|
||||
<Shield className="h-4 w-4" />
|
||||
Roles
|
||||
</Link>
|
||||
<Link
|
||||
to="/help"
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground' }}
|
||||
>
|
||||
<HelpCircle className="h-4 w-4" />
|
||||
Help
|
||||
</Link>
|
||||
{canViewAccounts && (
|
||||
<>
|
||||
<NavLink to="/accounts" icon={<Users className="h-4 w-4" />} label="Accounts" />
|
||||
<NavLink to="/members" icon={<UserRound className="h-4 w-4" />} label="Members" />
|
||||
</>
|
||||
)}
|
||||
{canViewUsers && (
|
||||
<div className="mt-4 mb-1 px-3">
|
||||
<span className="text-xs font-semibold text-sidebar-foreground/50 uppercase tracking-wide">Admin</span>
|
||||
</div>
|
||||
)}
|
||||
{canViewUsers && (
|
||||
<>
|
||||
<NavLink to="/users" icon={<UserCog className="h-4 w-4" />} label="Users" />
|
||||
<NavLink to="/roles" icon={<Shield className="h-4 w-4" />} label="Roles" />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="p-3 border-t border-sidebar-border space-y-1">
|
||||
<NavLink to="/help" icon={<HelpCircle className="h-4 w-4" />} label="Help" />
|
||||
<Link
|
||||
to="/profile"
|
||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent w-full"
|
||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground w-full' }}
|
||||
>
|
||||
<User className="h-4 w-4" />
|
||||
{user?.id ? <Avatar entityType="user" entityId={user.id} size="sm" /> : <User className="h-4 w-4" />}
|
||||
<span className="truncate">{user?.firstName} {user?.lastName}</span>
|
||||
</Link>
|
||||
<Button
|
||||
|
||||
@@ -5,8 +5,11 @@ import { memberListOptions, memberMutations, memberKeys } from '@/api/members'
|
||||
import { identifierListOptions, identifierMutations, identifierKeys } from '@/api/identifiers'
|
||||
import { MemberForm } from '@/components/accounts/member-form'
|
||||
import { IdentifierForm } from '@/components/accounts/identifier-form'
|
||||
import { usePagination } from '@/hooks/use-pagination'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -16,11 +19,17 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { Plus, Trash2, CreditCard, ChevronDown, ChevronRight, MoreVertical, Pencil } from 'lucide-react'
|
||||
import { Plus, Trash2, CreditCard, ChevronDown, ChevronRight, ChevronLeft, MoreVertical, Pencil, Search, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { Member } from '@/types/account'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/accounts/$accountId/members')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
page: Number(search.page) || 1,
|
||||
limit: Number(search.limit) || 25,
|
||||
q: (search.q as string) || undefined,
|
||||
sort: (search.sort as string) || undefined,
|
||||
order: (search.order as 'asc' | 'desc') || 'asc',
|
||||
}),
|
||||
component: MembersTab,
|
||||
})
|
||||
|
||||
@@ -66,7 +75,7 @@ function MemberIdentifiers({ memberId }: { memberId: string }) {
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader><DialogTitle>Add Identity Document</DialogTitle></DialogHeader>
|
||||
<IdentifierForm memberId={memberId} onSubmit={createMutation.mutate} loading={createMutation.isPending} />
|
||||
<IdentifierForm memberId={memberId} onSubmit={(data) => createMutation.mutate(data)} loading={createMutation.isPending} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
@@ -96,7 +105,7 @@ function MemberIdentifiers({ memberId }: { memberId: string }) {
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{(id.imageFront || id.imageBack) && (
|
||||
{(id.imageFrontFileId || id.imageBackFileId) && (
|
||||
<Badge variant="outline" className="text-xs">Has images</Badge>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => deleteMutation.mutate(id.id)}>
|
||||
@@ -111,14 +120,44 @@ function MemberIdentifiers({ memberId }: { memberId: string }) {
|
||||
)
|
||||
}
|
||||
|
||||
function SortableHeader({ label, sortKey, currentSort, currentOrder, onSort }: {
|
||||
label: string
|
||||
sortKey: string
|
||||
currentSort?: string
|
||||
currentOrder?: 'asc' | 'desc'
|
||||
onSort: (sort: string, order: 'asc' | 'desc') => void
|
||||
}) {
|
||||
function handleClick() {
|
||||
if (currentSort === sortKey) {
|
||||
onSort(sortKey, currentOrder === 'asc' ? 'desc' : 'asc')
|
||||
} else {
|
||||
onSort(sortKey, 'asc')
|
||||
}
|
||||
}
|
||||
|
||||
const Icon = currentSort !== sortKey ? ArrowUpDown
|
||||
: currentOrder === 'asc' ? ArrowUp : ArrowDown
|
||||
|
||||
return (
|
||||
<TableHead className="cursor-pointer select-none" onClick={handleClick}>
|
||||
<span className="flex items-center">
|
||||
{label}
|
||||
<Icon className={`ml-1 h-3 w-3 ${currentSort !== sortKey ? 'opacity-40' : ''}`} />
|
||||
</span>
|
||||
</TableHead>
|
||||
)
|
||||
}
|
||||
|
||||
function MembersTab() {
|
||||
const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/members' })
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [expandedMember, setExpandedMember] = useState<string | null>(null)
|
||||
const { params, setPage, setSearch, setSort } = usePagination()
|
||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||
|
||||
const { data, isLoading } = useQuery(memberListOptions(accountId, { page: 1, limit: 100, order: 'asc' }))
|
||||
const { data, isLoading } = useQuery(memberListOptions(accountId, params))
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) => memberMutations.create(accountId, data),
|
||||
@@ -139,7 +178,24 @@ function MembersTab() {
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
function handleSearchSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setSearch(searchInput)
|
||||
}
|
||||
|
||||
const members = data?.data ?? []
|
||||
const totalPages = data?.pagination.totalPages ?? 1
|
||||
const total = data?.pagination.total ?? 0
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{Array.from({ length: 5 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-12 w-full" />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -156,89 +212,131 @@ function MembersTab() {
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
) : members.length === 0 ? (
|
||||
<p className="text-muted-foreground py-8 text-center">No members yet</p>
|
||||
) : (
|
||||
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search members..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
<Button type="submit" variant="secondary">Search</Button>
|
||||
</form>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-8"></TableHead>
|
||||
<TableHead>#</TableHead>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<SortableHeader label="Name" sortKey="last_name" currentSort={params.sort} currentOrder={params.order} onSort={setSort} />
|
||||
<SortableHeader label="Email" sortKey="email" currentSort={params.sort} currentOrder={params.order} onSort={setSort} />
|
||||
<TableHead>Phone</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="w-12"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{members.map((m) => (
|
||||
<>
|
||||
<TableRow key={m.id}>
|
||||
<TableCell>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0"
|
||||
onClick={() => setExpandedMember(expandedMember === m.id ? null : m.id)}
|
||||
title="Show IDs"
|
||||
>
|
||||
{expandedMember === m.id
|
||||
? <ChevronDown className="h-3 w-3" />
|
||||
: <ChevronRight className="h-3 w-3" />}
|
||||
</Button>
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-sm text-muted-foreground">{m.memberNumber ?? '-'}</TableCell>
|
||||
<TableCell className="font-medium">{m.firstName} {m.lastName}</TableCell>
|
||||
<TableCell>{m.email ?? '-'}</TableCell>
|
||||
<TableCell>{m.phone ?? '-'}</TableCell>
|
||||
<TableCell>
|
||||
{m.isMinor ? <Badge variant="secondary">Minor</Badge> : <Badge>Adult</Badge>}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => navigate({
|
||||
to: '/members/$memberId',
|
||||
params: { memberId: m.id },
|
||||
})}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setExpandedMember(expandedMember === m.id ? null : m.id)}>
|
||||
<CreditCard className="mr-2 h-4 w-4" />
|
||||
{expandedMember === m.id ? 'Hide IDs' : 'View IDs'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => deleteMutation.mutate(m.id)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{expandedMember === m.id && (
|
||||
<TableRow key={`${m.id}-ids`}>
|
||||
<TableCell colSpan={7} className="p-0">
|
||||
<MemberIdentifiers memberId={m.id} />
|
||||
{members.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={7} className="text-center py-8 text-muted-foreground">
|
||||
No members found
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
members.map((m) => (
|
||||
<>
|
||||
<TableRow key={m.id}>
|
||||
<TableCell>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0"
|
||||
onClick={() => setExpandedMember(expandedMember === m.id ? null : m.id)}
|
||||
title="Show IDs"
|
||||
>
|
||||
{expandedMember === m.id
|
||||
? <ChevronDown className="h-3 w-3" />
|
||||
: <ChevronRight className="h-3 w-3" />}
|
||||
</Button>
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-sm text-muted-foreground">{m.memberNumber ?? '-'}</TableCell>
|
||||
<TableCell className="font-medium">{m.firstName} {m.lastName}</TableCell>
|
||||
<TableCell>{m.email ?? '-'}</TableCell>
|
||||
<TableCell>{m.phone ?? '-'}</TableCell>
|
||||
<TableCell>
|
||||
{m.isMinor ? <Badge variant="secondary">Minor</Badge> : <Badge>Adult</Badge>}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => navigate({
|
||||
to: '/members/$memberId',
|
||||
params: { memberId: m.id },
|
||||
})}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setExpandedMember(expandedMember === m.id ? null : m.id)}>
|
||||
<CreditCard className="mr-2 h-4 w-4" />
|
||||
{expandedMember === m.id ? 'Hide IDs' : 'View IDs'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => deleteMutation.mutate(m.id)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</>
|
||||
))}
|
||||
{expandedMember === m.id && (
|
||||
<TableRow key={`${m.id}-ids`}>
|
||||
<TableCell colSpan={7} className="p-0">
|
||||
<MemberIdentifiers memberId={m.id} />
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</>
|
||||
))
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between text-sm text-muted-foreground">
|
||||
<span>{total} total</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={params.page <= 1}
|
||||
onClick={() => setPage(params.page - 1)}
|
||||
>
|
||||
<ChevronLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<span>
|
||||
Page {params.page} of {totalPages}
|
||||
</span>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={params.page >= totalPages}
|
||||
onClick={() => setPage(params.page + 1)}
|
||||
>
|
||||
<ChevronRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,14 +3,24 @@ import { createFileRoute, useParams } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { paymentMethodListOptions, paymentMethodMutations, paymentMethodKeys } from '@/api/payment-methods'
|
||||
import { PaymentMethodForm } from '@/components/accounts/payment-method-form'
|
||||
import { usePagination } from '@/hooks/use-pagination'
|
||||
import { DataTable, type Column } from '@/components/shared/data-table'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { Plus, Trash2, Star } from 'lucide-react'
|
||||
import { Plus, Trash2, Star, Search } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { PaymentMethod } from '@/types/account'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/accounts/$accountId/payment-methods')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
page: Number(search.page) || 1,
|
||||
limit: Number(search.limit) || 25,
|
||||
q: (search.q as string) || undefined,
|
||||
sort: (search.sort as string) || undefined,
|
||||
order: (search.order as 'asc' | 'desc') || 'asc',
|
||||
}),
|
||||
component: PaymentMethodsTab,
|
||||
})
|
||||
|
||||
@@ -18,8 +28,10 @@ function PaymentMethodsTab() {
|
||||
const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/payment-methods' })
|
||||
const queryClient = useQueryClient()
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const { params, setPage, setSearch, setSort } = usePagination()
|
||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||
|
||||
const { data, isLoading } = useQuery(paymentMethodListOptions(accountId))
|
||||
const { data, isLoading } = useQuery(paymentMethodListOptions(accountId, params))
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) => paymentMethodMutations.create(accountId, data),
|
||||
@@ -49,7 +61,56 @@ function PaymentMethodsTab() {
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const methods = data?.data ?? []
|
||||
function handleSearchSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setSearch(searchInput)
|
||||
}
|
||||
|
||||
const columns: Column<PaymentMethod>[] = [
|
||||
{
|
||||
key: 'card_brand',
|
||||
header: 'Card',
|
||||
sortable: true,
|
||||
render: (m) => <span className="font-medium">{m.cardBrand ?? 'Card'} {m.lastFour ? `****${m.lastFour}` : ''}</span>,
|
||||
},
|
||||
{
|
||||
key: 'processor',
|
||||
header: 'Processor',
|
||||
sortable: true,
|
||||
render: (m) => <Badge variant="outline">{m.processor}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'expires',
|
||||
header: 'Expires',
|
||||
render: (m) => <>{m.expMonth && m.expYear ? `${m.expMonth}/${m.expYear}` : '-'}</>,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: 'Status',
|
||||
render: (m) => (
|
||||
<div className="flex gap-1">
|
||||
{m.isDefault && <Badge>Default</Badge>}
|
||||
{m.requiresUpdate && <Badge variant="destructive">Needs Update</Badge>}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
header: 'Actions',
|
||||
render: (m) => (
|
||||
<div className="flex gap-1">
|
||||
{!m.isDefault && (
|
||||
<Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); setDefaultMutation.mutate(m.id) }}>
|
||||
<Star className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); deleteMutation.mutate(m.id) }}>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -66,52 +127,31 @@ function PaymentMethodsTab() {
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
) : methods.length === 0 ? (
|
||||
<p className="text-muted-foreground py-8 text-center">No payment methods</p>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Card</TableHead>
|
||||
<TableHead>Processor</TableHead>
|
||||
<TableHead>Expires</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="w-32">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{methods.map((m) => (
|
||||
<TableRow key={m.id}>
|
||||
<TableCell className="font-medium">
|
||||
{m.cardBrand ?? 'Card'} {m.lastFour ? `****${m.lastFour}` : ''}
|
||||
</TableCell>
|
||||
<TableCell><Badge variant="outline">{m.processor}</Badge></TableCell>
|
||||
<TableCell>{m.expMonth && m.expYear ? `${m.expMonth}/${m.expYear}` : '-'}</TableCell>
|
||||
<TableCell>
|
||||
{m.isDefault && <Badge>Default</Badge>}
|
||||
{m.requiresUpdate && <Badge variant="destructive">Needs Update</Badge>}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex gap-1">
|
||||
{!m.isDefault && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setDefaultMutation.mutate(m.id)}>
|
||||
<Star className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="ghost" size="sm" onClick={() => deleteMutation.mutate(m.id)}>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search payment methods..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Button type="submit" variant="secondary">Search</Button>
|
||||
</form>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
loading={isLoading}
|
||||
page={params.page}
|
||||
totalPages={data?.pagination.totalPages ?? 1}
|
||||
total={data?.pagination.total ?? 0}
|
||||
sort={params.sort}
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,14 +3,24 @@ import { createFileRoute, useParams } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { processorLinkListOptions, processorLinkMutations, processorLinkKeys } from '@/api/processor-links'
|
||||
import { ProcessorLinkForm } from '@/components/accounts/processor-link-form'
|
||||
import { usePagination } from '@/hooks/use-pagination'
|
||||
import { DataTable, type Column } from '@/components/shared/data-table'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { Plus, Trash2 } from 'lucide-react'
|
||||
import { Plus, Trash2, Search } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { ProcessorLink } from '@/types/account'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/accounts/$accountId/processor-links')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
page: Number(search.page) || 1,
|
||||
limit: Number(search.limit) || 25,
|
||||
q: (search.q as string) || undefined,
|
||||
sort: (search.sort as string) || undefined,
|
||||
order: (search.order as 'asc' | 'desc') || 'asc',
|
||||
}),
|
||||
component: ProcessorLinksTab,
|
||||
})
|
||||
|
||||
@@ -18,8 +28,10 @@ function ProcessorLinksTab() {
|
||||
const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/processor-links' })
|
||||
const queryClient = useQueryClient()
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const { params, setPage, setSearch, setSort } = usePagination()
|
||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||
|
||||
const { data, isLoading } = useQuery(processorLinkListOptions(accountId))
|
||||
const { data, isLoading } = useQuery(processorLinkListOptions(accountId, params))
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) => processorLinkMutations.create(accountId, data),
|
||||
@@ -40,7 +52,38 @@ function ProcessorLinksTab() {
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const links = data?.data ?? []
|
||||
function handleSearchSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setSearch(searchInput)
|
||||
}
|
||||
|
||||
const columns: Column<ProcessorLink>[] = [
|
||||
{
|
||||
key: 'processor',
|
||||
header: 'Processor',
|
||||
sortable: true,
|
||||
render: (l) => <Badge variant="outline">{l.processor}</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'customer_id',
|
||||
header: 'Customer ID',
|
||||
render: (l) => <span className="font-mono text-sm">{l.processorCustomerId}</span>,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: 'Status',
|
||||
render: (l) => l.isActive ? <Badge>Active</Badge> : <Badge variant="secondary">Inactive</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
header: 'Actions',
|
||||
render: (l) => (
|
||||
<Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); deleteMutation.mutate(l.id) }}>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -57,40 +100,31 @@ function ProcessorLinksTab() {
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
) : links.length === 0 ? (
|
||||
<p className="text-muted-foreground py-8 text-center">No processor links</p>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Processor</TableHead>
|
||||
<TableHead>Customer ID</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="w-24">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{links.map((l) => (
|
||||
<TableRow key={l.id}>
|
||||
<TableCell><Badge variant="outline">{l.processor}</Badge></TableCell>
|
||||
<TableCell className="font-mono text-sm">{l.processorCustomerId}</TableCell>
|
||||
<TableCell>
|
||||
{l.isActive ? <Badge>Active</Badge> : <Badge variant="secondary">Inactive</Badge>}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Button variant="ghost" size="sm" onClick={() => deleteMutation.mutate(l.id)}>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search processor links..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Button type="submit" variant="secondary">Search</Button>
|
||||
</form>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
loading={isLoading}
|
||||
page={params.page}
|
||||
totalPages={data?.pagination.totalPages ?? 1}
|
||||
total={data?.pagination.total ?? 0}
|
||||
sort={params.sort}
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -3,14 +3,24 @@ import { createFileRoute, useParams } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { taxExemptionListOptions, taxExemptionMutations, taxExemptionKeys } from '@/api/tax-exemptions'
|
||||
import { TaxExemptionForm } from '@/components/accounts/tax-exemption-form'
|
||||
import { usePagination } from '@/hooks/use-pagination'
|
||||
import { DataTable, type Column } from '@/components/shared/data-table'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { Plus, Check, X } from 'lucide-react'
|
||||
import { Plus, Check, X, Search } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import type { TaxExemption } from '@/types/account'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/accounts/$accountId/tax-exemptions')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
page: Number(search.page) || 1,
|
||||
limit: Number(search.limit) || 25,
|
||||
q: (search.q as string) || undefined,
|
||||
sort: (search.sort as string) || undefined,
|
||||
order: (search.order as 'asc' | 'desc') || 'asc',
|
||||
}),
|
||||
component: TaxExemptionsTab,
|
||||
})
|
||||
|
||||
@@ -26,8 +36,10 @@ function TaxExemptionsTab() {
|
||||
const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/tax-exemptions' })
|
||||
const queryClient = useQueryClient()
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const { params, setPage, setSearch, setSort } = usePagination()
|
||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||
|
||||
const { data, isLoading } = useQuery(taxExemptionListOptions(accountId))
|
||||
const { data, isLoading } = useQuery(taxExemptionListOptions(accountId, params))
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) => taxExemptionMutations.create(accountId, data),
|
||||
@@ -61,7 +73,59 @@ function TaxExemptionsTab() {
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const exemptions = data?.data ?? []
|
||||
function handleSearchSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setSearch(searchInput)
|
||||
}
|
||||
|
||||
const columns: Column<TaxExemption>[] = [
|
||||
{
|
||||
key: 'certificate_number',
|
||||
header: 'Certificate #',
|
||||
sortable: true,
|
||||
render: (e) => <span className="font-medium">{e.certificateNumber}</span>,
|
||||
},
|
||||
{
|
||||
key: 'type',
|
||||
header: 'Type',
|
||||
render: (e) => <>{e.certificateType ?? '-'}</>,
|
||||
},
|
||||
{
|
||||
key: 'state',
|
||||
header: 'State',
|
||||
render: (e) => <>{e.issuingState ?? '-'}</>,
|
||||
},
|
||||
{
|
||||
key: 'expires_at',
|
||||
header: 'Expires',
|
||||
sortable: true,
|
||||
render: (e) => <>{e.expiresAt ?? '-'}</>,
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: 'Status',
|
||||
sortable: true,
|
||||
render: (e) => statusBadge(e.status),
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
header: 'Actions',
|
||||
render: (e) => (
|
||||
<div className="flex gap-1">
|
||||
{e.status === 'pending' && (
|
||||
<Button variant="ghost" size="sm" onClick={(ev) => { ev.stopPropagation(); approveMutation.mutate(e.id) }}>
|
||||
<Check className="h-4 w-4 text-green-600" />
|
||||
</Button>
|
||||
)}
|
||||
{e.status === 'approved' && (
|
||||
<Button variant="ghost" size="sm" onClick={(ev) => { ev.stopPropagation(); revokeMutation.mutate(e.id) }}>
|
||||
<X className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -78,51 +142,31 @@ function TaxExemptionsTab() {
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
) : exemptions.length === 0 ? (
|
||||
<p className="text-muted-foreground py-8 text-center">No tax exemptions</p>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Certificate #</TableHead>
|
||||
<TableHead>Type</TableHead>
|
||||
<TableHead>State</TableHead>
|
||||
<TableHead>Expires</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead className="w-32">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{exemptions.map((e) => (
|
||||
<TableRow key={e.id}>
|
||||
<TableCell className="font-medium">{e.certificateNumber}</TableCell>
|
||||
<TableCell>{e.certificateType ?? '-'}</TableCell>
|
||||
<TableCell>{e.issuingState ?? '-'}</TableCell>
|
||||
<TableCell>{e.expiresAt ?? '-'}</TableCell>
|
||||
<TableCell>{statusBadge(e.status)}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex gap-1">
|
||||
{e.status === 'pending' && (
|
||||
<Button variant="ghost" size="sm" onClick={() => approveMutation.mutate(e.id)}>
|
||||
<Check className="h-4 w-4 text-green-600" />
|
||||
</Button>
|
||||
)}
|
||||
{e.status === 'approved' && (
|
||||
<Button variant="ghost" size="sm" onClick={() => revokeMutation.mutate(e.id)}>
|
||||
<X className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search tax exemptions..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Button type="submit" variant="secondary">Search</Button>
|
||||
</form>
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={data?.data ?? []}
|
||||
loading={isLoading}
|
||||
page={params.page}
|
||||
totalPages={data?.pagination.totalPages ?? 1}
|
||||
total={data?.pagination.total ?? 0}
|
||||
sort={params.sort}
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { accountColumns } from '@/components/accounts/account-table'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Plus, Search } from 'lucide-react'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import type { Account } from '@/types/account'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/accounts/')({
|
||||
@@ -23,6 +24,7 @@ export const Route = createFileRoute('/_authenticated/accounts/')({
|
||||
|
||||
function AccountsListPage() {
|
||||
const navigate = useNavigate()
|
||||
const hasPermission = useAuthStore((s) => s.hasPermission)
|
||||
const { params, setPage, setSearch, setSort } = usePagination()
|
||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||
|
||||
@@ -41,10 +43,12 @@ function AccountsListPage() {
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Accounts</h1>
|
||||
<Button onClick={() => navigate({ to: '/accounts/new' })}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Account
|
||||
</Button>
|
||||
{hasPermission('accounts.edit') && (
|
||||
<Button onClick={() => navigate({ to: '/accounts/new' })}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Account
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||
|
||||
@@ -2,6 +2,6 @@ import { createFileRoute, redirect } from '@tanstack/react-router'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/')({
|
||||
beforeLoad: () => {
|
||||
throw redirect({ to: '/accounts' })
|
||||
throw redirect({ to: '/accounts', search: {} as any })
|
||||
},
|
||||
})
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { identifierListOptions, identifierMutations, identifierKeys } from '@/api/identifiers'
|
||||
import { MemberForm } from '@/components/accounts/member-form'
|
||||
import { IdentifierForm } from '@/components/accounts/identifier-form'
|
||||
import { IdentifierForm, type IdentifierFiles } from '@/components/accounts/identifier-form'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
@@ -12,6 +12,8 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { ArrowLeft, Plus, Trash2, CreditCard } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { AvatarUpload } from '@/components/shared/avatar-upload'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import type { Member, MemberIdentifier } from '@/types/account'
|
||||
import { useState } from 'react'
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
@@ -27,6 +29,29 @@ export const Route = createFileRoute('/_authenticated/members/$memberId')({
|
||||
component: MemberDetailPage,
|
||||
})
|
||||
|
||||
function IdentifierImages({ identifierId }: { identifierId: string }) {
|
||||
const { data } = useQuery({
|
||||
queryKey: ['files', 'member_identifier', identifierId],
|
||||
queryFn: () => api.get<{ data: { id: string; path: string; category: string }[] }>('/v1/files', {
|
||||
entityType: 'member_identifier',
|
||||
entityId: identifierId,
|
||||
}),
|
||||
})
|
||||
|
||||
const files = data?.data ?? []
|
||||
const frontFile = files.find((f) => f.category === 'front')
|
||||
const backFile = files.find((f) => f.category === 'back')
|
||||
|
||||
if (!frontFile && !backFile) return null
|
||||
|
||||
return (
|
||||
<div className="flex gap-2 mt-2">
|
||||
{frontFile && <img src={`/v1/files/serve/${frontFile.path}`} alt="Front" className="h-20 rounded border object-cover" />}
|
||||
{backFile && <img src={`/v1/files/serve/${backFile.path}`} alt="Back" className="h-20 rounded border object-cover" />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const ID_TYPE_LABELS: Record<string, string> = {
|
||||
drivers_license: "Driver's License",
|
||||
passport: 'Passport',
|
||||
@@ -39,8 +64,10 @@ function MemberDetailPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const [addIdOpen, setAddIdOpen] = useState(false)
|
||||
|
||||
const token = useAuthStore((s) => s.token)
|
||||
const { data: member, isLoading } = useQuery(memberDetailOptions(memberId))
|
||||
const { data: idsData } = useQuery(identifierListOptions(memberId))
|
||||
const [createLoading, setCreateLoading] = useState(false)
|
||||
|
||||
const updateMutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) => api.patch<Member>(`/v1/members/${memberId}`, data),
|
||||
@@ -51,15 +78,52 @@ function MemberDetailPage() {
|
||||
onError: (err) => toast.error(err instanceof Error ? err.message : 'Update failed'),
|
||||
})
|
||||
|
||||
const createIdMutation = useMutation({
|
||||
mutationFn: (data: Record<string, unknown>) => identifierMutations.create(memberId, data),
|
||||
onSuccess: () => {
|
||||
async function uploadIdFile(identifierId: string, file: File, category: string): Promise<string | null> {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('entityType', 'member_identifier')
|
||||
formData.append('entityId', identifierId)
|
||||
formData.append('category', category)
|
||||
|
||||
const res = await fetch('/v1/files', {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
body: formData,
|
||||
})
|
||||
if (!res.ok) return null
|
||||
const data = await res.json()
|
||||
return data.id
|
||||
}
|
||||
|
||||
async function handleCreateIdentifier(data: Record<string, unknown>, files: IdentifierFiles) {
|
||||
setCreateLoading(true)
|
||||
try {
|
||||
const identifier = await identifierMutations.create(memberId, data)
|
||||
|
||||
// Upload images and update identifier with file IDs
|
||||
const updates: Record<string, unknown> = {}
|
||||
if (files.front) {
|
||||
const fileId = await uploadIdFile(identifier.id, files.front, 'front')
|
||||
if (fileId) updates.imageFrontFileId = fileId
|
||||
}
|
||||
if (files.back) {
|
||||
const fileId = await uploadIdFile(identifier.id, files.back, 'back')
|
||||
if (fileId) updates.imageBackFileId = fileId
|
||||
}
|
||||
|
||||
if (Object.keys(updates).length > 0) {
|
||||
await identifierMutations.update(identifier.id, updates)
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: identifierKeys.all(memberId) })
|
||||
toast.success('ID added')
|
||||
setAddIdOpen(false)
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to add ID')
|
||||
} finally {
|
||||
setCreateLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const deleteIdMutation = useMutation({
|
||||
mutationFn: identifierMutations.delete,
|
||||
@@ -88,7 +152,7 @@ function MemberDetailPage() {
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/accounts/$accountId/members', params: { accountId: member.accountId } })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/accounts/$accountId/members', params: { accountId: member.accountId }, search: {} as any })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div>
|
||||
@@ -111,7 +175,14 @@ function MemberDetailPage() {
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Details</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center gap-4">
|
||||
<AvatarUpload entityType="member" entityId={memberId} size="lg" />
|
||||
<div>
|
||||
<p className="font-medium">{member.firstName} {member.lastName}</p>
|
||||
<p className="text-sm text-muted-foreground">{member.email ?? 'No email'}</p>
|
||||
</div>
|
||||
</div>
|
||||
<MemberForm
|
||||
accountId={member.accountId}
|
||||
defaultValues={member}
|
||||
@@ -130,7 +201,7 @@ function MemberDetailPage() {
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader><DialogTitle>Add Identity Document</DialogTitle></DialogHeader>
|
||||
<IdentifierForm memberId={memberId} onSubmit={createIdMutation.mutate} loading={createIdMutation.isPending} />
|
||||
<IdentifierForm memberId={memberId} onSubmit={handleCreateIdentifier} loading={createLoading} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</CardHeader>
|
||||
@@ -154,11 +225,8 @@ function MemberDetailPage() {
|
||||
{id.issuedDate && <span>Issued: {id.issuedDate}</span>}
|
||||
{id.expiresAt && <span>Expires: {id.expiresAt}</span>}
|
||||
</div>
|
||||
{(id.imageFront || id.imageBack) && (
|
||||
<div className="flex gap-2 mt-2">
|
||||
{id.imageFront && <img src={id.imageFront} alt="Front" className="h-20 rounded border object-cover" />}
|
||||
{id.imageBack && <img src={id.imageBack} alt="Back" className="h-20 rounded border object-cover" />}
|
||||
</div>
|
||||
{(id.imageFrontFileId || id.imageBackFileId) && (
|
||||
<IdentifierImages identifierId={id.id} />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Search, Plus, MoreVertical, Pencil, Users } from 'lucide-react'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/members/')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
@@ -28,6 +29,7 @@ export const Route = createFileRoute('/_authenticated/members/')({
|
||||
|
||||
function MembersListPage() {
|
||||
const navigate = useNavigate()
|
||||
const hasPermission = useAuthStore((s) => s.hasPermission)
|
||||
const { params, setPage, setSearch, setSort } = usePagination()
|
||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||
|
||||
@@ -100,10 +102,12 @@ function MembersListPage() {
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Members</h1>
|
||||
<Button onClick={() => navigate({ to: '/accounts/new' })}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Member
|
||||
</Button>
|
||||
{hasPermission('accounts.edit') && (
|
||||
<Button onClick={() => navigate({ to: '/accounts/new' })}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Member
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||
|
||||
@@ -13,6 +13,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Sun, Moon, Monitor } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { AvatarUpload } from '@/components/shared/avatar-upload'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/profile')({
|
||||
component: ProfilePage,
|
||||
@@ -92,6 +93,15 @@ function ProfilePage() {
|
||||
<CardTitle className="text-lg">Account</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{profile?.id && (
|
||||
<div className="flex items-center gap-4">
|
||||
<AvatarUpload entityType="user" entityId={profile.id} size="lg" />
|
||||
<div>
|
||||
<p className="font-medium">{profile.firstName} {profile.lastName}</p>
|
||||
<p className="text-sm text-muted-foreground">{profile.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<Label>Email</Label>
|
||||
<Input value={profile?.email ?? ''} disabled className="opacity-60" />
|
||||
|
||||
@@ -100,7 +100,7 @@ function RoleDetailPage() {
|
||||
return (
|
||||
<div className="space-y-6 max-w-2xl">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/roles' })}>
|
||||
<Button variant="ghost" size="sm" onClick={() => navigate({ to: '/roles', search: {} as any })}>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
<div>
|
||||
@@ -177,7 +177,7 @@ function RoleDetailPage() {
|
||||
<Button onClick={handleSave} disabled={updateMutation.isPending}>
|
||||
{updateMutation.isPending ? 'Saving...' : 'Save Changes'}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles' })}>
|
||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles', search: {} as any })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { roleListOptions, rbacKeys, rbacMutations } from '@/api/rbac'
|
||||
import { useState } from 'react'
|
||||
import { rolePageOptions, rbacKeys, rbacMutations } from '@/api/rbac'
|
||||
import { usePagination } from '@/hooks/use-pagination'
|
||||
import { DataTable, type Column } from '@/components/shared/data-table'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
@@ -11,99 +14,142 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { Plus, MoreVertical, Pencil, Trash2, Shield } from 'lucide-react'
|
||||
import { Plus, MoreVertical, Pencil, Trash2, Shield, Search } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
import type { Role } from '@/types/rbac'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/roles/')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
page: Number(search.page) || 1,
|
||||
limit: Number(search.limit) || 25,
|
||||
q: (search.q as string) || undefined,
|
||||
sort: (search.sort as string) || undefined,
|
||||
order: (search.order as 'asc' | 'desc') || 'asc',
|
||||
}),
|
||||
component: RolesListPage,
|
||||
})
|
||||
|
||||
function RolesListPage() {
|
||||
const navigate = useNavigate()
|
||||
const queryClient = useQueryClient()
|
||||
const { data, isLoading } = useQuery(roleListOptions())
|
||||
const hasPermission = useAuthStore((s) => s.hasPermission)
|
||||
const { params, setPage, setSearch, setSort } = usePagination()
|
||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||
|
||||
const { data, isLoading } = useQuery(rolePageOptions(params))
|
||||
|
||||
const deleteMutation = useMutation({
|
||||
mutationFn: rbacMutations.deleteRole,
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
||||
queryClient.invalidateQueries({ queryKey: ['roles', 'list'] })
|
||||
toast.success('Role deleted')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
const roles = data?.data ?? []
|
||||
function handleSearchSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setSearch(searchInput)
|
||||
}
|
||||
|
||||
const roleColumns: Column<Role>[] = [
|
||||
{
|
||||
key: 'name',
|
||||
header: 'Name',
|
||||
sortable: true,
|
||||
render: (row) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">{row.name}</span>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'slug',
|
||||
header: 'Slug',
|
||||
sortable: true,
|
||||
render: (row) => <span className="font-mono text-sm text-muted-foreground">{row.slug}</span>,
|
||||
},
|
||||
{
|
||||
key: 'description',
|
||||
header: 'Description',
|
||||
render: (row) => <span className="text-sm text-muted-foreground">{row.description ?? '-'}</span>,
|
||||
},
|
||||
{
|
||||
key: 'type',
|
||||
header: 'Type',
|
||||
render: (row) =>
|
||||
row.isSystem ? <Badge variant="secondary">System</Badge> : <Badge>Custom</Badge>,
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
header: '',
|
||||
render: (row) => (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => navigate({ to: '/roles/$roleId', params: { roleId: row.id } })}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit Permissions
|
||||
</DropdownMenuItem>
|
||||
{!row.isSystem && hasPermission('users.admin') && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => deleteMutation.mutate(row.id)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Roles</h1>
|
||||
<Button onClick={() => navigate({ to: '/roles/new' })}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Role
|
||||
</Button>
|
||||
{hasPermission('users.admin') && (
|
||||
<Button onClick={() => navigate({ to: '/roles/new' })}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
New Role
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
) : roles.length === 0 ? (
|
||||
<p className="text-muted-foreground py-8 text-center">No roles found</p>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Slug</TableHead>
|
||||
<TableHead>Description</TableHead>
|
||||
<TableHead>Type</TableHead>
|
||||
<TableHead className="w-12"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{roles.map((role) => (
|
||||
<TableRow key={role.id}>
|
||||
<TableCell className="font-medium">
|
||||
<div className="flex items-center gap-2">
|
||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||
{role.name}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-sm text-muted-foreground">{role.slug}</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">{role.description ?? '-'}</TableCell>
|
||||
<TableCell>
|
||||
{role.isSystem ? <Badge variant="secondary">System</Badge> : <Badge>Custom</Badge>}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => navigate({ to: '/roles/$roleId', params: { roleId: role.id } })}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Edit Permissions
|
||||
</DropdownMenuItem>
|
||||
{!role.isSystem && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-destructive" onClick={() => deleteMutation.mutate(role.id)}>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search roles..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Button type="submit" variant="secondary">Search</Button>
|
||||
</form>
|
||||
|
||||
<DataTable
|
||||
columns={roleColumns}
|
||||
data={data?.data ?? []}
|
||||
loading={isLoading}
|
||||
page={params.page}
|
||||
totalPages={data?.pagination?.totalPages ?? 1}
|
||||
total={data?.pagination?.total ?? 0}
|
||||
sort={params.sort}
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ function NewRolePage() {
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
||||
toast.success('Role created')
|
||||
navigate({ to: '/roles' })
|
||||
navigate({ to: '/roles', search: {} as any })
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
@@ -153,7 +153,7 @@ function NewRolePage() {
|
||||
<Button onClick={handleSubmit} disabled={mutation.isPending}>
|
||||
{mutation.isPending ? 'Creating...' : 'Create Role'}
|
||||
</Button>
|
||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles' })}>
|
||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles', search: {} as any })}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { api } from '@/lib/api-client'
|
||||
import { roleListOptions, rbacKeys, rbacMutations } from '@/api/rbac'
|
||||
import { userRolesOptions, type UserRecord } from '@/api/users'
|
||||
import { userListOptions, userRolesOptions, userKeys, userMutations, type UserRecord } from '@/api/users'
|
||||
import { roleListOptions, rbacMutations } from '@/api/rbac'
|
||||
import { usePagination } from '@/hooks/use-pagination'
|
||||
import { DataTable, type Column } from '@/components/shared/data-table'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import {
|
||||
@@ -15,38 +17,21 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { MoreVertical, Shield, Plus, X, KeyRound } from 'lucide-react'
|
||||
import { MoreVertical, Shield, Plus, X, KeyRound, Search, UserCheck, UserX } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { queryOptions } from '@tanstack/react-query'
|
||||
|
||||
function userListOptions() {
|
||||
return queryOptions({
|
||||
queryKey: ['users'],
|
||||
queryFn: () => api.get<{ data: UserRecord[] }>('/v1/users'),
|
||||
})
|
||||
}
|
||||
import { useAuthStore } from '@/stores/auth.store'
|
||||
|
||||
export const Route = createFileRoute('/_authenticated/users')({
|
||||
validateSearch: (search: Record<string, unknown>) => ({
|
||||
page: Number(search.page) || 1,
|
||||
limit: Number(search.limit) || 25,
|
||||
q: (search.q as string) || undefined,
|
||||
sort: (search.sort as string) || undefined,
|
||||
order: (search.order as 'asc' | 'desc') || 'asc',
|
||||
}),
|
||||
component: UsersPage,
|
||||
})
|
||||
|
||||
function UserRoleBadges({ userId }: { userId: string }) {
|
||||
const { data } = useQuery(userRolesOptions(userId))
|
||||
const roles = data?.data ?? []
|
||||
|
||||
if (roles.length === 0) return <span className="text-sm text-muted-foreground">No roles</span>
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{roles.map((r) => (
|
||||
<Badge key={r.id} variant={r.isSystem ? 'secondary' : 'default'} className="text-xs">
|
||||
{r.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: boolean; onClose: () => void }) {
|
||||
const queryClient = useQueryClient()
|
||||
const { data: userRolesData } = useQuery(userRolesOptions(user.id))
|
||||
@@ -61,7 +46,7 @@ function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: bo
|
||||
const assignMutation = useMutation({
|
||||
mutationFn: (roleId: string) => rbacMutations.assignRole(user.id, roleId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['users', user.id, 'roles'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['users'] })
|
||||
setSelectedRoleId('')
|
||||
toast.success('Role assigned')
|
||||
},
|
||||
@@ -71,7 +56,7 @@ function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: bo
|
||||
const removeMutation = useMutation({
|
||||
mutationFn: (roleId: string) => rbacMutations.removeRole(user.id, roleId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['users', user.id, 'roles'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['users'] })
|
||||
toast.success('Role removed')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
@@ -135,10 +120,131 @@ function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: bo
|
||||
}
|
||||
|
||||
function UsersPage() {
|
||||
const { data, isLoading } = useQuery(userListOptions())
|
||||
const queryClient = useQueryClient()
|
||||
const hasPermission = useAuthStore((s) => s.hasPermission)
|
||||
const { params, setPage, setSearch, setSort } = usePagination()
|
||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||
const [managingUser, setManagingUser] = useState<UserRecord | null>(null)
|
||||
|
||||
const allUsers = data?.data ?? []
|
||||
const { data, isLoading } = useQuery(userListOptions(params))
|
||||
|
||||
const statusMutation = useMutation({
|
||||
mutationFn: ({ userId, isActive }: { userId: string; isActive: boolean }) =>
|
||||
userMutations.toggleStatus(userId, isActive),
|
||||
onSuccess: (_data, vars) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['users'] })
|
||||
toast.success(vars.isActive ? 'User enabled' : 'User disabled')
|
||||
},
|
||||
onError: (err) => toast.error(err.message),
|
||||
})
|
||||
|
||||
function handleSearchSubmit(e: React.FormEvent) {
|
||||
e.preventDefault()
|
||||
setSearch(searchInput)
|
||||
}
|
||||
|
||||
const userColumns: Column<UserRecord>[] = [
|
||||
{
|
||||
key: 'name',
|
||||
header: 'Name',
|
||||
sortable: true,
|
||||
render: (row) => (
|
||||
<span className={`font-medium ${!row.isActive ? 'text-muted-foreground' : ''}`}>
|
||||
{row.firstName} {row.lastName}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'email',
|
||||
header: 'Email',
|
||||
sortable: true,
|
||||
render: (row) => <span className={!row.isActive ? 'text-muted-foreground' : ''}>{row.email}</span>,
|
||||
},
|
||||
{
|
||||
key: 'roles',
|
||||
header: 'Roles',
|
||||
render: (row) =>
|
||||
row.roles.length === 0 ? (
|
||||
<span className="text-sm text-muted-foreground">No roles</span>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{row.roles.map((r) => (
|
||||
<Badge key={r.id} variant={r.isSystem ? 'secondary' : 'default'} className="text-xs">
|
||||
{r.name}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
header: 'Status',
|
||||
render: (row) =>
|
||||
row.isActive ? (
|
||||
<Badge variant="secondary" className="text-xs">Active</Badge>
|
||||
) : (
|
||||
<Badge variant="destructive" className="text-xs">Disabled</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'created_at',
|
||||
header: 'Created',
|
||||
sortable: true,
|
||||
render: (row) => new Date(row.createdAt).toLocaleDateString(),
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
header: '',
|
||||
render: (row) => (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{hasPermission('users.edit') && (
|
||||
<DropdownMenuItem onClick={() => setManagingUser(row)}>
|
||||
<Shield className="mr-2 h-4 w-4" />
|
||||
Manage Roles
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{hasPermission('users.admin') && (
|
||||
<DropdownMenuItem onClick={async () => {
|
||||
try {
|
||||
const res = await api.post<{ resetLink: string }>(`/v1/auth/reset-password/${row.id}`, {})
|
||||
await navigator.clipboard.writeText(res.resetLink)
|
||||
toast.success('Reset link copied to clipboard')
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to generate link')
|
||||
}
|
||||
}}>
|
||||
<KeyRound className="mr-2 h-4 w-4" />
|
||||
Reset Password Link
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{hasPermission('users.admin') && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => statusMutation.mutate({ userId: row.id, isActive: !row.isActive })}
|
||||
>
|
||||
{row.isActive ? (
|
||||
<>
|
||||
<UserX className="mr-2 h-4 w-4" />
|
||||
Disable User
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<UserCheck className="mr-2 h-4 w-4" />
|
||||
Enable User
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -148,60 +254,31 @@ function UsersPage() {
|
||||
<ManageRolesDialog user={managingUser} open={!!managingUser} onClose={() => setManagingUser(null)} />
|
||||
)}
|
||||
|
||||
{isLoading ? (
|
||||
<p className="text-muted-foreground">Loading...</p>
|
||||
) : allUsers.length === 0 ? (
|
||||
<p className="text-muted-foreground py-8 text-center">No users found</p>
|
||||
) : (
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Name</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Roles</TableHead>
|
||||
<TableHead className="w-12"></TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{allUsers.map((user) => (
|
||||
<TableRow key={user.id}>
|
||||
<TableCell className="font-medium">{user.firstName} {user.lastName}</TableCell>
|
||||
<TableCell>{user.email}</TableCell>
|
||||
<TableCell><UserRoleBadges userId={user.id} /></TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setManagingUser(user)}>
|
||||
<Shield className="mr-2 h-4 w-4" />
|
||||
Manage Roles
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={async () => {
|
||||
try {
|
||||
const res = await api.post<{ resetLink: string }>(`/v1/auth/reset-password/${user.id}`, {})
|
||||
await navigator.clipboard.writeText(res.resetLink)
|
||||
toast.success('Reset link copied to clipboard')
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Failed to generate link')
|
||||
}
|
||||
}}>
|
||||
<KeyRound className="mr-2 h-4 w-4" />
|
||||
Reset Password Link
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search users..."
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Button type="submit" variant="secondary">Search</Button>
|
||||
</form>
|
||||
|
||||
<DataTable
|
||||
columns={userColumns}
|
||||
data={data?.data ?? []}
|
||||
loading={isLoading}
|
||||
page={params.page}
|
||||
totalPages={data?.pagination?.totalPages ?? 1}
|
||||
total={data?.pagination?.total ?? 0}
|
||||
sort={params.sort}
|
||||
order={params.order}
|
||||
onPageChange={setPage}
|
||||
onSort={setSort}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ export const Route = createFileRoute('/login')({
|
||||
beforeLoad: () => {
|
||||
const { token } = useAuthStore.getState()
|
||||
if (token) {
|
||||
throw redirect({ to: '/accounts' })
|
||||
throw redirect({ to: '/accounts', search: {} as any })
|
||||
}
|
||||
},
|
||||
component: LoginPage,
|
||||
@@ -30,7 +30,7 @@ function LoginPage() {
|
||||
const res = await login(email, password)
|
||||
setAuth(res.token, res.user)
|
||||
await router.invalidate()
|
||||
await router.navigate({ to: '/accounts', replace: true })
|
||||
await router.navigate({ to: '/accounts', search: {} as any, replace: true })
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Login failed')
|
||||
} finally {
|
||||
|
||||
@@ -12,16 +12,49 @@ interface AuthState {
|
||||
token: string | null
|
||||
user: User | null
|
||||
companyId: string | null
|
||||
permissions: Set<string>
|
||||
permissionsLoaded: boolean
|
||||
setAuth: (token: string, user: User) => void
|
||||
setPermissions: (slugs: string[]) => void
|
||||
hasPermission: (slug: string) => boolean
|
||||
logout: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission inheritance: admin implies edit implies view for the same domain.
|
||||
* Must match the backend logic in plugins/auth.ts.
|
||||
*/
|
||||
const ACTION_HIERARCHY: Record<string, string[]> = {
|
||||
admin: ['admin', 'edit', 'view'],
|
||||
edit: ['edit', 'view'],
|
||||
view: ['view'],
|
||||
upload: ['upload'],
|
||||
delete: ['delete'],
|
||||
send: ['send'],
|
||||
export: ['export'],
|
||||
}
|
||||
|
||||
function expandPermissions(slugs: string[]): Set<string> {
|
||||
const expanded = new Set<string>()
|
||||
for (const slug of slugs) {
|
||||
expanded.add(slug)
|
||||
const [domain, action] = slug.split('.')
|
||||
const implied = ACTION_HIERARCHY[action]
|
||||
if (implied && domain) {
|
||||
for (const a of implied) {
|
||||
expanded.add(`${domain}.${a}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
return expanded
|
||||
}
|
||||
|
||||
function decodeJwtPayload(token: string): { id: string; companyId: string; role: string } {
|
||||
const payload = token.split('.')[1]
|
||||
return JSON.parse(atob(payload))
|
||||
}
|
||||
|
||||
function loadSession(): { token: string; user: User; companyId: string } | null {
|
||||
function loadSession(): { token: string; user: User; companyId: string; permissions?: string[] } | null {
|
||||
try {
|
||||
const raw = sessionStorage.getItem('forte-auth')
|
||||
if (!raw) return null
|
||||
@@ -31,20 +64,23 @@ function loadSession(): { token: string; user: User; companyId: string } | null
|
||||
}
|
||||
}
|
||||
|
||||
function saveSession(token: string, user: User, companyId: string) {
|
||||
sessionStorage.setItem('forte-auth', JSON.stringify({ token, user, companyId }))
|
||||
function saveSession(token: string, user: User, companyId: string, permissions?: string[]) {
|
||||
sessionStorage.setItem('forte-auth', JSON.stringify({ token, user, companyId, permissions }))
|
||||
}
|
||||
|
||||
function clearSession() {
|
||||
sessionStorage.removeItem('forte-auth')
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>((set) => {
|
||||
export const useAuthStore = create<AuthState>((set, get) => {
|
||||
const initial = typeof window !== 'undefined' ? loadSession() : null
|
||||
const initialPerms = initial?.permissions ? expandPermissions(initial.permissions) : new Set<string>()
|
||||
return {
|
||||
token: initial?.token ?? null,
|
||||
user: initial?.user ?? null,
|
||||
companyId: initial?.companyId ?? null,
|
||||
permissions: initialPerms,
|
||||
permissionsLoaded: initialPerms.size > 0,
|
||||
|
||||
setAuth: (token, user) => {
|
||||
const payload = decodeJwtPayload(token)
|
||||
@@ -52,8 +88,22 @@ export const useAuthStore = create<AuthState>((set) => {
|
||||
set({ token, user, companyId: payload.companyId })
|
||||
},
|
||||
|
||||
setPermissions: (slugs: string[]) => {
|
||||
const expanded = expandPermissions(slugs)
|
||||
// Update session storage to include permissions
|
||||
const { token, user, companyId } = get()
|
||||
if (token && user && companyId) {
|
||||
saveSession(token, user, companyId, slugs)
|
||||
}
|
||||
set({ permissions: expanded, permissionsLoaded: true })
|
||||
},
|
||||
|
||||
hasPermission: (slug: string) => {
|
||||
return get().permissions.has(slug)
|
||||
},
|
||||
|
||||
logout: () => {
|
||||
clearSession()
|
||||
set({ token: null, user: null, companyId: null })
|
||||
set({ token: null, user: null, companyId: null, permissions: new Set(), permissionsLoaded: false })
|
||||
},
|
||||
}})
|
||||
|
||||
@@ -74,8 +74,8 @@ export interface MemberIdentifier {
|
||||
issuingAuthority: string | null
|
||||
issuedDate: string | null
|
||||
expiresAt: string | null
|
||||
imageFront: string | null
|
||||
imageBack: string | null
|
||||
imageFrontFileId: string | null
|
||||
imageBackFileId: string | null
|
||||
notes: string | null
|
||||
isPrimary: boolean
|
||||
createdAt: string
|
||||
|
||||
Reference in New Issue
Block a user