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:
11
CLAUDE.md
11
CLAUDE.md
@@ -40,7 +40,7 @@
|
|||||||
- `bun run format` — format all files with Prettier
|
- `bun run format` — format all files with Prettier
|
||||||
|
|
||||||
## API Conventions
|
## API Conventions
|
||||||
- All list endpoints support server-side pagination, search, and sorting via query params:
|
- **Every endpoint that returns a list must support pagination, search, and sorting** — no exceptions unless the endpoint is explicitly a lightweight lookup (see below)
|
||||||
- `?page=1&limit=25` — pagination (default: page 1, 25 per page, max 100)
|
- `?page=1&limit=25` — pagination (default: page 1, 25 per page, max 100)
|
||||||
- `?q=search+term` — full-text search across relevant columns
|
- `?q=search+term` — full-text search across relevant columns
|
||||||
- `?sort=name&order=asc` — sorting by field name, asc or desc
|
- `?sort=name&order=asc` — sorting by field name, asc or desc
|
||||||
@@ -48,6 +48,15 @@
|
|||||||
- Search and filtering is ALWAYS server-side, never client-side
|
- Search and filtering is ALWAYS server-side, never client-side
|
||||||
- Use `PaginationSchema` from `@forte/shared/schemas` to parse query params
|
- Use `PaginationSchema` from `@forte/shared/schemas` to parse query params
|
||||||
- Use pagination helpers from `packages/backend/src/utils/pagination.ts`
|
- Use pagination helpers from `packages/backend/src/utils/pagination.ts`
|
||||||
|
- **Lookup endpoints** (e.g., `/roles/all`, `/statuses/all`) are the exception — these return a flat unpaginated list for populating dropdowns/selects. Use a `/all` suffix to distinguish from the paginated list endpoint for the same resource.
|
||||||
|
|
||||||
|
## Frontend Table Conventions
|
||||||
|
- **Every table that displays data must use the shared `DataTable` component** (`components/shared/data-table.tsx`)
|
||||||
|
- All tables must support: **search** (via `?q=`), **sortable columns**, and **server-side pagination**
|
||||||
|
- Use the `usePagination()` hook (`hooks/use-pagination.ts`) — it manages page, search, and sort state via URL params
|
||||||
|
- All data columns that make sense to sort by should be sortable (e.g., name, email, date, status) — don't limit to just 1-2 columns
|
||||||
|
- Sub-resource tables (e.g., members within an account, payment methods) follow the same rules — use `DataTable` with pagination, not raw `<Table>` with unbounded queries
|
||||||
|
- Loading states should use skeleton loading (built into `DataTable`), not plain "Loading..." text
|
||||||
|
|
||||||
## Conventions
|
## Conventions
|
||||||
- Shared Zod schemas are the single source of truth for validation (used on both frontend and backend)
|
- Shared Zod schemas are the single source of truth for validation (used on both frontend and backend)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { queryOptions } from '@tanstack/react-query'
|
import { queryOptions } from '@tanstack/react-query'
|
||||||
import { api } from '@/lib/api-client'
|
import { api } from '@/lib/api-client'
|
||||||
import type { MemberIdentifier } from '@/types/account'
|
import type { MemberIdentifier } from '@/types/account'
|
||||||
|
import type { PaginatedResponse } from '@forte/shared/schemas'
|
||||||
|
|
||||||
export const identifierKeys = {
|
export const identifierKeys = {
|
||||||
all: (memberId: string) => ['members', memberId, 'identifiers'] as const,
|
all: (memberId: string) => ['members', memberId, 'identifiers'] as const,
|
||||||
@@ -9,7 +10,7 @@ export const identifierKeys = {
|
|||||||
export function identifierListOptions(memberId: string) {
|
export function identifierListOptions(memberId: string) {
|
||||||
return queryOptions({
|
return queryOptions({
|
||||||
queryKey: identifierKeys.all(memberId),
|
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 { queryOptions } from '@tanstack/react-query'
|
||||||
import { api } from '@/lib/api-client'
|
import { api } from '@/lib/api-client'
|
||||||
import type { PaymentMethod } from '@/types/account'
|
import type { PaymentMethod } from '@/types/account'
|
||||||
|
import type { PaginatedResponse, PaginationInput } from '@forte/shared/schemas'
|
||||||
|
|
||||||
export const paymentMethodKeys = {
|
export const paymentMethodKeys = {
|
||||||
all: (accountId: string) => ['accounts', accountId, 'payment-methods'] as const,
|
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({
|
return queryOptions({
|
||||||
queryKey: paymentMethodKeys.all(accountId),
|
queryKey: paymentMethodKeys.list(accountId, params),
|
||||||
queryFn: () => api.get<{ data: PaymentMethod[] }>(`/v1/accounts/${accountId}/payment-methods`),
|
queryFn: () => api.get<PaginatedResponse<PaymentMethod>>(`/v1/accounts/${accountId}/payment-methods`, params),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
import { queryOptions } from '@tanstack/react-query'
|
import { queryOptions } from '@tanstack/react-query'
|
||||||
import { api } from '@/lib/api-client'
|
import { api } from '@/lib/api-client'
|
||||||
import type { ProcessorLink } from '@/types/account'
|
import type { ProcessorLink } from '@/types/account'
|
||||||
|
import type { PaginatedResponse, PaginationInput } from '@forte/shared/schemas'
|
||||||
|
|
||||||
export const processorLinkKeys = {
|
export const processorLinkKeys = {
|
||||||
all: (accountId: string) => ['accounts', accountId, 'processor-links'] as const,
|
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({
|
return queryOptions({
|
||||||
queryKey: processorLinkKeys.all(accountId),
|
queryKey: processorLinkKeys.list(accountId, params),
|
||||||
queryFn: () => api.get<{ data: ProcessorLink[] }>(`/v1/accounts/${accountId}/processor-links`),
|
queryFn: () => api.get<PaginatedResponse<ProcessorLink>>(`/v1/accounts/${accountId}/processor-links`, params),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { queryOptions } from '@tanstack/react-query'
|
import { queryOptions } from '@tanstack/react-query'
|
||||||
import { api } from '@/lib/api-client'
|
import { api } from '@/lib/api-client'
|
||||||
import type { Permission, Role } from '@/types/rbac'
|
import type { Permission, Role } from '@/types/rbac'
|
||||||
|
import type { PaginationInput, PaginatedResponse } from '@forte/shared/schemas'
|
||||||
|
|
||||||
export const rbacKeys = {
|
export const rbacKeys = {
|
||||||
permissions: ['permissions'] as const,
|
permissions: ['permissions'] as const,
|
||||||
roles: ['roles'] as const,
|
roles: ['roles'] as const,
|
||||||
|
roleList: (params: PaginationInput) => ['roles', 'list', params] as const,
|
||||||
role: (id: string) => ['roles', id] as const,
|
role: (id: string) => ['roles', id] as const,
|
||||||
userRoles: (userId: string) => ['users', userId, 'roles'] as const,
|
userRoles: (userId: string) => ['users', userId, 'roles'] as const,
|
||||||
myPermissions: ['me', 'permissions'] as const,
|
myPermissions: ['me', 'permissions'] as const,
|
||||||
@@ -17,10 +19,19 @@ export function permissionListOptions() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** All roles (for dropdowns, selectors) */
|
||||||
export function roleListOptions() {
|
export function roleListOptions() {
|
||||||
return queryOptions({
|
return queryOptions({
|
||||||
queryKey: rbacKeys.roles,
|
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 { queryOptions } from '@tanstack/react-query'
|
||||||
import { api } from '@/lib/api-client'
|
import { api } from '@/lib/api-client'
|
||||||
import type { TaxExemption } from '@/types/account'
|
import type { TaxExemption } from '@/types/account'
|
||||||
|
import type { PaginatedResponse, PaginationInput } from '@forte/shared/schemas'
|
||||||
|
|
||||||
export const taxExemptionKeys = {
|
export const taxExemptionKeys = {
|
||||||
all: (accountId: string) => ['accounts', accountId, 'tax-exemptions'] as const,
|
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({
|
return queryOptions({
|
||||||
queryKey: taxExemptionKeys.all(accountId),
|
queryKey: taxExemptionKeys.list(accountId, params),
|
||||||
queryFn: () => api.get<{ data: TaxExemption[] }>(`/v1/accounts/${accountId}/tax-exemptions`),
|
queryFn: () => api.get<PaginatedResponse<TaxExemption>>(`/v1/accounts/${accountId}/tax-exemptions`, params),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,13 @@
|
|||||||
import { queryOptions } from '@tanstack/react-query'
|
import { queryOptions } from '@tanstack/react-query'
|
||||||
import { api } from '@/lib/api-client'
|
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 {
|
export interface UserRecord {
|
||||||
id: string
|
id: string
|
||||||
@@ -7,16 +15,31 @@ export interface UserRecord {
|
|||||||
firstName: string
|
firstName: string
|
||||||
lastName: string
|
lastName: string
|
||||||
role: string
|
role: string
|
||||||
|
isActive: boolean
|
||||||
createdAt: string
|
createdAt: string
|
||||||
|
roles: UserRole[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export const userKeys = {
|
export const userKeys = {
|
||||||
|
list: (params: PaginationInput) => ['users', params] as const,
|
||||||
roles: (userId: string) => ['users', userId, 'roles'] 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) {
|
export function userRolesOptions(userId: string) {
|
||||||
return queryOptions({
|
return queryOptions({
|
||||||
queryKey: userKeys.roles(userId),
|
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 { useForm } from 'react-hook-form'
|
||||||
import { useRef } from 'react'
|
import { useRef, useState } from 'react'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { Label } from '@/components/ui/label'
|
import { Label } from '@/components/ui/label'
|
||||||
import { Textarea } from '@/components/ui/textarea'
|
import { Textarea } from '@/components/ui/textarea'
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
import type { MemberIdentifier } from '@/types/account'
|
import type { MemberIdentifier } from '@/types/account'
|
||||||
import { Upload } from 'lucide-react'
|
import { Upload, X } from 'lucide-react'
|
||||||
|
|
||||||
const ID_TYPES = [
|
const ID_TYPES = [
|
||||||
{ value: 'drivers_license', label: "Driver's License / State ID" },
|
{ value: 'drivers_license', label: "Driver's License / State ID" },
|
||||||
@@ -14,22 +14,18 @@ const ID_TYPES = [
|
|||||||
{ value: 'school_id', label: 'School ID' },
|
{ value: 'school_id', label: 'School ID' },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
export interface IdentifierFiles {
|
||||||
|
front?: File
|
||||||
|
back?: File
|
||||||
|
}
|
||||||
|
|
||||||
interface IdentifierFormProps {
|
interface IdentifierFormProps {
|
||||||
memberId: string
|
memberId: string
|
||||||
defaultValues?: Partial<MemberIdentifier>
|
defaultValues?: Partial<MemberIdentifier>
|
||||||
onSubmit: (data: Record<string, unknown>) => void
|
onSubmit: (data: Record<string, unknown>, files: IdentifierFiles) => void
|
||||||
loading?: boolean
|
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) {
|
export function IdentifierForm({ memberId, defaultValues, onSubmit, loading }: IdentifierFormProps) {
|
||||||
const { register, handleSubmit, setValue, watch } = useForm({
|
const { register, handleSubmit, setValue, watch } = useForm({
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
@@ -41,20 +37,38 @@ export function IdentifierForm({ memberId, defaultValues, onSubmit, loading }: I
|
|||||||
expiresAt: defaultValues?.expiresAt ?? '',
|
expiresAt: defaultValues?.expiresAt ?? '',
|
||||||
notes: defaultValues?.notes ?? '',
|
notes: defaultValues?.notes ?? '',
|
||||||
isPrimary: defaultValues?.isPrimary ?? false,
|
isPrimary: defaultValues?.isPrimary ?? false,
|
||||||
imageFront: defaultValues?.imageFront ?? '',
|
|
||||||
imageBack: defaultValues?.imageBack ?? '',
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const frontInputRef = useRef<HTMLInputElement>(null)
|
const frontInputRef = useRef<HTMLInputElement>(null)
|
||||||
const backInputRef = useRef<HTMLInputElement>(null)
|
const backInputRef = useRef<HTMLInputElement>(null)
|
||||||
const imageFront = watch('imageFront')
|
const [frontFile, setFrontFile] = useState<File | null>(null)
|
||||||
const imageBack = watch('imageBack')
|
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')
|
const idType = watch('type')
|
||||||
|
|
||||||
async function handleFileSelect(field: 'imageFront' | 'imageBack', file: File) {
|
function handleFileSelect(side: 'front' | 'back', file: File) {
|
||||||
const base64 = await fileToBase64(file)
|
const url = URL.createObjectURL(file)
|
||||||
setValue(field, base64)
|
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>) {
|
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)) {
|
for (const [key, value] of Object.entries(data)) {
|
||||||
cleaned[key] = value === '' ? undefined : value
|
cleaned[key] = value === '' ? undefined : value
|
||||||
}
|
}
|
||||||
onSubmit(cleaned)
|
onSubmit(cleaned, {
|
||||||
|
front: frontFile ?? undefined,
|
||||||
|
back: backFile ?? undefined,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form onSubmit={handleSubmit(handleFormSubmit)} noValidate className="space-y-4">
|
<form onSubmit={handleSubmit(handleFormSubmit)} noValidate className="space-y-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label>ID Type *</Label>
|
<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>
|
<SelectTrigger>
|
||||||
<SelectValue />
|
<SelectValue />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
@@ -114,21 +131,21 @@ export function IdentifierForm({ memberId, defaultValues, onSubmit, loading }: I
|
|||||||
<input
|
<input
|
||||||
ref={frontInputRef}
|
ref={frontInputRef}
|
||||||
type="file"
|
type="file"
|
||||||
accept="image/*"
|
accept="image/jpeg,image/png,image/webp"
|
||||||
className="hidden"
|
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">
|
<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
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
size="sm"
|
size="sm"
|
||||||
className="absolute top-1 right-1"
|
className="absolute top-1 right-1 h-6 w-6 p-0"
|
||||||
onClick={() => setValue('imageFront', '')}
|
onClick={() => clearFile('front')}
|
||||||
>
|
>
|
||||||
Remove
|
<X className="h-3 w-3" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
@@ -142,21 +159,21 @@ export function IdentifierForm({ memberId, defaultValues, onSubmit, loading }: I
|
|||||||
<input
|
<input
|
||||||
ref={backInputRef}
|
ref={backInputRef}
|
||||||
type="file"
|
type="file"
|
||||||
accept="image/*"
|
accept="image/jpeg,image/png,image/webp"
|
||||||
className="hidden"
|
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">
|
<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
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="secondary"
|
variant="secondary"
|
||||||
size="sm"
|
size="sm"
|
||||||
className="absolute top-1 right-1"
|
className="absolute top-1 right-1 h-6 w-6 p-0"
|
||||||
onClick={() => setValue('imageBack', '')}
|
onClick={() => clearFile('back')}
|
||||||
>
|
>
|
||||||
Remove
|
<X className="h-3 w-3" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ export function PaymentMethodForm({ accountId, onSubmit, loading }: PaymentMetho
|
|||||||
setValue,
|
setValue,
|
||||||
watch,
|
watch,
|
||||||
formState: { errors },
|
formState: { errors },
|
||||||
} = useForm<PaymentMethodCreateInput>({
|
} = useForm({
|
||||||
resolver: zodResolver(PaymentMethodCreateSchema),
|
resolver: zodResolver(PaymentMethodCreateSchema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
accountId,
|
accountId,
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ export function TaxExemptionForm({ accountId, onSubmit, loading }: TaxExemptionF
|
|||||||
register,
|
register,
|
||||||
handleSubmit,
|
handleSubmit,
|
||||||
formState: { errors },
|
formState: { errors },
|
||||||
} = useForm<TaxExemptionCreateInput>({
|
} = useForm({
|
||||||
resolver: zodResolver(TaxExemptionCreateSchema),
|
resolver: zodResolver(TaxExemptionCreateSchema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
accountId,
|
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>) {
|
function setParams(updates: Partial<PaginationSearch>) {
|
||||||
navigate({
|
navigate({
|
||||||
search: (prev: PaginationSearch) => ({
|
search: ((prev: PaginationSearch) => ({
|
||||||
...prev,
|
...prev,
|
||||||
...updates,
|
...updates,
|
||||||
// Reset to page 1 when search or sort changes
|
// Reset to page 1 when search or sort changes
|
||||||
page: updates.q !== undefined || updates.sort !== undefined ? 1 : (updates.page ?? prev.page),
|
page: updates.q !== undefined || updates.sort !== undefined ? 1 : (updates.page ?? prev.page),
|
||||||
}),
|
})) as any,
|
||||||
replace: true,
|
replace: true,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import { createFileRoute, Outlet, Link, redirect, useRouter } from '@tanstack/react-router'
|
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 { useAuthStore } from '@/stores/auth.store'
|
||||||
|
import { myPermissionsOptions } from '@/api/rbac'
|
||||||
|
import { Avatar } from '@/components/shared/avatar-upload'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Users, UserRound, HelpCircle, Shield, UserCog, LogOut, User } from 'lucide-react'
|
import { Users, UserRound, HelpCircle, Shield, UserCog, LogOut, User } from 'lucide-react'
|
||||||
|
|
||||||
@@ -13,16 +17,48 @@ export const Route = createFileRoute('/_authenticated')({
|
|||||||
component: AuthenticatedLayout,
|
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() {
|
function AuthenticatedLayout() {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const user = useAuthStore((s) => s.user)
|
const user = useAuthStore((s) => s.user)
|
||||||
const logout = useAuthStore((s) => s.logout)
|
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() {
|
function handleLogout() {
|
||||||
logout()
|
logout()
|
||||||
router.navigate({ to: '/login', replace: true })
|
router.navigate({ to: '/login', replace: true })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const canViewAccounts = !permissionsLoaded || hasPermission('accounts.view')
|
||||||
|
const canViewUsers = !permissionsLoaded || hasPermission('users.view')
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-background text-foreground">
|
<div className="min-h-screen bg-background text-foreground">
|
||||||
<div className="flex">
|
<div className="flex">
|
||||||
@@ -31,59 +67,37 @@ function AuthenticatedLayout() {
|
|||||||
<h2 className="text-lg font-semibold text-sidebar-foreground">Forte</h2>
|
<h2 className="text-lg font-semibold text-sidebar-foreground">Forte</h2>
|
||||||
</div>
|
</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">
|
<div className="flex-1 px-3 space-y-1">
|
||||||
<Link
|
{canViewAccounts && (
|
||||||
to="/accounts"
|
<>
|
||||||
className="flex items-center gap-2 px-3 py-2 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent"
|
<NavLink to="/accounts" icon={<Users className="h-4 w-4" />} label="Accounts" />
|
||||||
activeProps={{ className: 'flex items-center gap-2 px-3 py-2 rounded-md text-sm bg-sidebar-accent text-sidebar-accent-foreground' }}
|
<NavLink to="/members" icon={<UserRound className="h-4 w-4" />} label="Members" />
|
||||||
>
|
</>
|
||||||
<Users className="h-4 w-4" />
|
)}
|
||||||
Accounts
|
{canViewUsers && (
|
||||||
</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">
|
<div className="mt-4 mb-1 px-3">
|
||||||
<span className="text-xs font-semibold text-sidebar-foreground/50 uppercase tracking-wide">Admin</span>
|
<span className="text-xs font-semibold text-sidebar-foreground/50 uppercase tracking-wide">Admin</span>
|
||||||
</div>
|
</div>
|
||||||
<Link
|
)}
|
||||||
to="/users"
|
{canViewUsers && (
|
||||||
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' }}
|
<NavLink to="/users" icon={<UserCog className="h-4 w-4" />} label="Users" />
|
||||||
>
|
<NavLink to="/roles" icon={<Shield className="h-4 w-4" />} label="Roles" />
|
||||||
<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>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="p-3 border-t border-sidebar-border space-y-1">
|
<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
|
<Link
|
||||||
to="/profile"
|
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"
|
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' }}
|
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>
|
<span className="truncate">{user?.firstName} {user?.lastName}</span>
|
||||||
</Link>
|
</Link>
|
||||||
<Button
|
<Button
|
||||||
|
|||||||
@@ -5,8 +5,11 @@ import { memberListOptions, memberMutations, memberKeys } from '@/api/members'
|
|||||||
import { identifierListOptions, identifierMutations, identifierKeys } from '@/api/identifiers'
|
import { identifierListOptions, identifierMutations, identifierKeys } from '@/api/identifiers'
|
||||||
import { MemberForm } from '@/components/accounts/member-form'
|
import { MemberForm } from '@/components/accounts/member-form'
|
||||||
import { IdentifierForm } from '@/components/accounts/identifier-form'
|
import { IdentifierForm } from '@/components/accounts/identifier-form'
|
||||||
|
import { usePagination } from '@/hooks/use-pagination'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Badge } from '@/components/ui/badge'
|
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 { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
@@ -16,11 +19,17 @@ import {
|
|||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu'
|
} from '@/components/ui/dropdown-menu'
|
||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
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 { toast } from 'sonner'
|
||||||
import type { Member } from '@/types/account'
|
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/accounts/$accountId/members')({
|
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,
|
component: MembersTab,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -66,7 +75,7 @@ function MemberIdentifiers({ memberId }: { memberId: string }) {
|
|||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
<DialogHeader><DialogTitle>Add Identity Document</DialogTitle></DialogHeader>
|
<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>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
@@ -96,7 +105,7 @@ function MemberIdentifiers({ memberId }: { memberId: string }) {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-1">
|
<div className="flex items-center gap-1">
|
||||||
{(id.imageFront || id.imageBack) && (
|
{(id.imageFrontFileId || id.imageBackFileId) && (
|
||||||
<Badge variant="outline" className="text-xs">Has images</Badge>
|
<Badge variant="outline" className="text-xs">Has images</Badge>
|
||||||
)}
|
)}
|
||||||
<Button variant="ghost" size="sm" onClick={() => deleteMutation.mutate(id.id)}>
|
<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() {
|
function MembersTab() {
|
||||||
const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/members' })
|
const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/members' })
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const [dialogOpen, setDialogOpen] = useState(false)
|
const [dialogOpen, setDialogOpen] = useState(false)
|
||||||
const [expandedMember, setExpandedMember] = useState<string | null>(null)
|
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({
|
const createMutation = useMutation({
|
||||||
mutationFn: (data: Record<string, unknown>) => memberMutations.create(accountId, data),
|
mutationFn: (data: Record<string, unknown>) => memberMutations.create(accountId, data),
|
||||||
@@ -139,7 +178,24 @@ function MembersTab() {
|
|||||||
onError: (err) => toast.error(err.message),
|
onError: (err) => toast.error(err.message),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
function handleSearchSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
setSearch(searchInput)
|
||||||
|
}
|
||||||
|
|
||||||
const members = data?.data ?? []
|
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 (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
@@ -156,26 +212,42 @@ function MembersTab() {
|
|||||||
</Dialog>
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isLoading ? (
|
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||||
<p className="text-muted-foreground">Loading...</p>
|
<div className="relative flex-1">
|
||||||
) : members.length === 0 ? (
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
<p className="text-muted-foreground py-8 text-center">No members yet</p>
|
<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">
|
<div className="rounded-md border">
|
||||||
<Table>
|
<Table>
|
||||||
<TableHeader>
|
<TableHeader>
|
||||||
<TableRow>
|
<TableRow>
|
||||||
<TableHead className="w-8"></TableHead>
|
<TableHead className="w-8"></TableHead>
|
||||||
<TableHead>#</TableHead>
|
<TableHead>#</TableHead>
|
||||||
<TableHead>Name</TableHead>
|
<SortableHeader label="Name" sortKey="last_name" currentSort={params.sort} currentOrder={params.order} onSort={setSort} />
|
||||||
<TableHead>Email</TableHead>
|
<SortableHeader label="Email" sortKey="email" currentSort={params.sort} currentOrder={params.order} onSort={setSort} />
|
||||||
<TableHead>Phone</TableHead>
|
<TableHead>Phone</TableHead>
|
||||||
<TableHead>Status</TableHead>
|
<TableHead>Status</TableHead>
|
||||||
<TableHead className="w-12"></TableHead>
|
<TableHead className="w-12"></TableHead>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{members.map((m) => (
|
{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}>
|
<TableRow key={m.id}>
|
||||||
<TableCell>
|
<TableCell>
|
||||||
@@ -234,11 +306,37 @@ function MembersTab() {
|
|||||||
</TableRow>
|
</TableRow>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
))}
|
))
|
||||||
|
)}
|
||||||
</TableBody>
|
</TableBody>
|
||||||
</Table>
|
</Table>
|
||||||
</div>
|
</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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,14 +3,24 @@ import { createFileRoute, useParams } from '@tanstack/react-router'
|
|||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import { paymentMethodListOptions, paymentMethodMutations, paymentMethodKeys } from '@/api/payment-methods'
|
import { paymentMethodListOptions, paymentMethodMutations, paymentMethodKeys } from '@/api/payment-methods'
|
||||||
import { PaymentMethodForm } from '@/components/accounts/payment-method-form'
|
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 { Button } from '@/components/ui/button'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
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, Search } from 'lucide-react'
|
||||||
import { Plus, Trash2, Star } from 'lucide-react'
|
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
import type { PaymentMethod } from '@/types/account'
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/accounts/$accountId/payment-methods')({
|
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,
|
component: PaymentMethodsTab,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -18,8 +28,10 @@ function PaymentMethodsTab() {
|
|||||||
const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/payment-methods' })
|
const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/payment-methods' })
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const [dialogOpen, setDialogOpen] = useState(false)
|
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({
|
const createMutation = useMutation({
|
||||||
mutationFn: (data: Record<string, unknown>) => paymentMethodMutations.create(accountId, data),
|
mutationFn: (data: Record<string, unknown>) => paymentMethodMutations.create(accountId, data),
|
||||||
@@ -49,7 +61,56 @@ function PaymentMethodsTab() {
|
|||||||
onError: (err) => toast.error(err.message),
|
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 (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
@@ -66,52 +127,31 @@ function PaymentMethodsTab() {
|
|||||||
</Dialog>
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isLoading ? (
|
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||||
<p className="text-muted-foreground">Loading...</p>
|
<div className="relative flex-1">
|
||||||
) : methods.length === 0 ? (
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
<p className="text-muted-foreground py-8 text-center">No payment methods</p>
|
<Input
|
||||||
) : (
|
placeholder="Search payment methods..."
|
||||||
<div className="rounded-md border">
|
value={searchInput}
|
||||||
<Table>
|
onChange={(e) => setSearchInput(e.target.value)}
|
||||||
<TableHeader>
|
className="pl-9"
|
||||||
<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>
|
</div>
|
||||||
</TableCell>
|
<Button type="submit" variant="secondary">Search</Button>
|
||||||
</TableRow>
|
</form>
|
||||||
))}
|
|
||||||
</TableBody>
|
<DataTable
|
||||||
</Table>
|
columns={columns}
|
||||||
</div>
|
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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,14 +3,24 @@ import { createFileRoute, useParams } from '@tanstack/react-router'
|
|||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import { processorLinkListOptions, processorLinkMutations, processorLinkKeys } from '@/api/processor-links'
|
import { processorLinkListOptions, processorLinkMutations, processorLinkKeys } from '@/api/processor-links'
|
||||||
import { ProcessorLinkForm } from '@/components/accounts/processor-link-form'
|
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 { Button } from '@/components/ui/button'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
import { Plus, Trash2, Search } from 'lucide-react'
|
||||||
import { Plus, Trash2 } from 'lucide-react'
|
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
import type { ProcessorLink } from '@/types/account'
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/accounts/$accountId/processor-links')({
|
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,
|
component: ProcessorLinksTab,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -18,8 +28,10 @@ function ProcessorLinksTab() {
|
|||||||
const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/processor-links' })
|
const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/processor-links' })
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const [dialogOpen, setDialogOpen] = useState(false)
|
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({
|
const createMutation = useMutation({
|
||||||
mutationFn: (data: Record<string, unknown>) => processorLinkMutations.create(accountId, data),
|
mutationFn: (data: Record<string, unknown>) => processorLinkMutations.create(accountId, data),
|
||||||
@@ -40,7 +52,38 @@ function ProcessorLinksTab() {
|
|||||||
onError: (err) => toast.error(err.message),
|
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 (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
@@ -57,40 +100,31 @@ function ProcessorLinksTab() {
|
|||||||
</Dialog>
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isLoading ? (
|
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||||
<p className="text-muted-foreground">Loading...</p>
|
<div className="relative flex-1">
|
||||||
) : links.length === 0 ? (
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
<p className="text-muted-foreground py-8 text-center">No processor links</p>
|
<Input
|
||||||
) : (
|
placeholder="Search processor links..."
|
||||||
<div className="rounded-md border">
|
value={searchInput}
|
||||||
<Table>
|
onChange={(e) => setSearchInput(e.target.value)}
|
||||||
<TableHeader>
|
className="pl-9"
|
||||||
<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>
|
|
||||||
</div>
|
</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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,14 +3,24 @@ import { createFileRoute, useParams } from '@tanstack/react-router'
|
|||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import { taxExemptionListOptions, taxExemptionMutations, taxExemptionKeys } from '@/api/tax-exemptions'
|
import { taxExemptionListOptions, taxExemptionMutations, taxExemptionKeys } from '@/api/tax-exemptions'
|
||||||
import { TaxExemptionForm } from '@/components/accounts/tax-exemption-form'
|
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 { Button } from '@/components/ui/button'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
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, Search } from 'lucide-react'
|
||||||
import { Plus, Check, X } from 'lucide-react'
|
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
import type { TaxExemption } from '@/types/account'
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/accounts/$accountId/tax-exemptions')({
|
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,
|
component: TaxExemptionsTab,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -26,8 +36,10 @@ function TaxExemptionsTab() {
|
|||||||
const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/tax-exemptions' })
|
const { accountId } = useParams({ from: '/_authenticated/accounts/$accountId/tax-exemptions' })
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const [dialogOpen, setDialogOpen] = useState(false)
|
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({
|
const createMutation = useMutation({
|
||||||
mutationFn: (data: Record<string, unknown>) => taxExemptionMutations.create(accountId, data),
|
mutationFn: (data: Record<string, unknown>) => taxExemptionMutations.create(accountId, data),
|
||||||
@@ -61,7 +73,59 @@ function TaxExemptionsTab() {
|
|||||||
onError: (err) => toast.error(err.message),
|
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 (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
@@ -78,51 +142,31 @@ function TaxExemptionsTab() {
|
|||||||
</Dialog>
|
</Dialog>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{isLoading ? (
|
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
||||||
<p className="text-muted-foreground">Loading...</p>
|
<div className="relative flex-1">
|
||||||
) : exemptions.length === 0 ? (
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||||
<p className="text-muted-foreground py-8 text-center">No tax exemptions</p>
|
<Input
|
||||||
) : (
|
placeholder="Search tax exemptions..."
|
||||||
<div className="rounded-md border">
|
value={searchInput}
|
||||||
<Table>
|
onChange={(e) => setSearchInput(e.target.value)}
|
||||||
<TableHeader>
|
className="pl-9"
|
||||||
<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>
|
</div>
|
||||||
</TableCell>
|
<Button type="submit" variant="secondary">Search</Button>
|
||||||
</TableRow>
|
</form>
|
||||||
))}
|
|
||||||
</TableBody>
|
<DataTable
|
||||||
</Table>
|
columns={columns}
|
||||||
</div>
|
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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { accountColumns } from '@/components/accounts/account-table'
|
|||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { Plus, Search } from 'lucide-react'
|
import { Plus, Search } from 'lucide-react'
|
||||||
|
import { useAuthStore } from '@/stores/auth.store'
|
||||||
import type { Account } from '@/types/account'
|
import type { Account } from '@/types/account'
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/accounts/')({
|
export const Route = createFileRoute('/_authenticated/accounts/')({
|
||||||
@@ -23,6 +24,7 @@ export const Route = createFileRoute('/_authenticated/accounts/')({
|
|||||||
|
|
||||||
function AccountsListPage() {
|
function AccountsListPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const hasPermission = useAuthStore((s) => s.hasPermission)
|
||||||
const { params, setPage, setSearch, setSort } = usePagination()
|
const { params, setPage, setSearch, setSort } = usePagination()
|
||||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||||
|
|
||||||
@@ -41,10 +43,12 @@ function AccountsListPage() {
|
|||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<h1 className="text-2xl font-bold">Accounts</h1>
|
<h1 className="text-2xl font-bold">Accounts</h1>
|
||||||
|
{hasPermission('accounts.edit') && (
|
||||||
<Button onClick={() => navigate({ to: '/accounts/new' })}>
|
<Button onClick={() => navigate({ to: '/accounts/new' })}>
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
New Account
|
New Account
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
<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/')({
|
export const Route = createFileRoute('/_authenticated/')({
|
||||||
beforeLoad: () => {
|
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 { api } from '@/lib/api-client'
|
||||||
import { identifierListOptions, identifierMutations, identifierKeys } from '@/api/identifiers'
|
import { identifierListOptions, identifierMutations, identifierKeys } from '@/api/identifiers'
|
||||||
import { MemberForm } from '@/components/accounts/member-form'
|
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 { Button } from '@/components/ui/button'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
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 { Skeleton } from '@/components/ui/skeleton'
|
||||||
import { ArrowLeft, Plus, Trash2, CreditCard } from 'lucide-react'
|
import { ArrowLeft, Plus, Trash2, CreditCard } from 'lucide-react'
|
||||||
import { toast } from 'sonner'
|
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 type { Member, MemberIdentifier } from '@/types/account'
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { queryOptions } from '@tanstack/react-query'
|
import { queryOptions } from '@tanstack/react-query'
|
||||||
@@ -27,6 +29,29 @@ export const Route = createFileRoute('/_authenticated/members/$memberId')({
|
|||||||
component: MemberDetailPage,
|
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> = {
|
const ID_TYPE_LABELS: Record<string, string> = {
|
||||||
drivers_license: "Driver's License",
|
drivers_license: "Driver's License",
|
||||||
passport: 'Passport',
|
passport: 'Passport',
|
||||||
@@ -39,8 +64,10 @@ function MemberDetailPage() {
|
|||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const [addIdOpen, setAddIdOpen] = useState(false)
|
const [addIdOpen, setAddIdOpen] = useState(false)
|
||||||
|
|
||||||
|
const token = useAuthStore((s) => s.token)
|
||||||
const { data: member, isLoading } = useQuery(memberDetailOptions(memberId))
|
const { data: member, isLoading } = useQuery(memberDetailOptions(memberId))
|
||||||
const { data: idsData } = useQuery(identifierListOptions(memberId))
|
const { data: idsData } = useQuery(identifierListOptions(memberId))
|
||||||
|
const [createLoading, setCreateLoading] = useState(false)
|
||||||
|
|
||||||
const updateMutation = useMutation({
|
const updateMutation = useMutation({
|
||||||
mutationFn: (data: Record<string, unknown>) => api.patch<Member>(`/v1/members/${memberId}`, data),
|
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'),
|
onError: (err) => toast.error(err instanceof Error ? err.message : 'Update failed'),
|
||||||
})
|
})
|
||||||
|
|
||||||
const createIdMutation = useMutation({
|
async function uploadIdFile(identifierId: string, file: File, category: string): Promise<string | null> {
|
||||||
mutationFn: (data: Record<string, unknown>) => identifierMutations.create(memberId, data),
|
const formData = new FormData()
|
||||||
onSuccess: () => {
|
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) })
|
queryClient.invalidateQueries({ queryKey: identifierKeys.all(memberId) })
|
||||||
toast.success('ID added')
|
toast.success('ID added')
|
||||||
setAddIdOpen(false)
|
setAddIdOpen(false)
|
||||||
},
|
} catch (err) {
|
||||||
onError: (err) => toast.error(err.message),
|
toast.error(err instanceof Error ? err.message : 'Failed to add ID')
|
||||||
})
|
} finally {
|
||||||
|
setCreateLoading(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const deleteIdMutation = useMutation({
|
const deleteIdMutation = useMutation({
|
||||||
mutationFn: identifierMutations.delete,
|
mutationFn: identifierMutations.delete,
|
||||||
@@ -88,7 +152,7 @@ function MemberDetailPage() {
|
|||||||
return (
|
return (
|
||||||
<div className="space-y-6 max-w-2xl">
|
<div className="space-y-6 max-w-2xl">
|
||||||
<div className="flex items-center gap-3">
|
<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" />
|
<ArrowLeft className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
<div>
|
<div>
|
||||||
@@ -111,7 +175,14 @@ function MemberDetailPage() {
|
|||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle className="text-lg">Details</CardTitle>
|
<CardTitle className="text-lg">Details</CardTitle>
|
||||||
</CardHeader>
|
</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
|
<MemberForm
|
||||||
accountId={member.accountId}
|
accountId={member.accountId}
|
||||||
defaultValues={member}
|
defaultValues={member}
|
||||||
@@ -130,7 +201,7 @@ function MemberDetailPage() {
|
|||||||
</DialogTrigger>
|
</DialogTrigger>
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
<DialogHeader><DialogTitle>Add Identity Document</DialogTitle></DialogHeader>
|
<DialogHeader><DialogTitle>Add Identity Document</DialogTitle></DialogHeader>
|
||||||
<IdentifierForm memberId={memberId} onSubmit={createIdMutation.mutate} loading={createIdMutation.isPending} />
|
<IdentifierForm memberId={memberId} onSubmit={handleCreateIdentifier} loading={createLoading} />
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
@@ -154,11 +225,8 @@ function MemberDetailPage() {
|
|||||||
{id.issuedDate && <span>Issued: {id.issuedDate}</span>}
|
{id.issuedDate && <span>Issued: {id.issuedDate}</span>}
|
||||||
{id.expiresAt && <span>Expires: {id.expiresAt}</span>}
|
{id.expiresAt && <span>Expires: {id.expiresAt}</span>}
|
||||||
</div>
|
</div>
|
||||||
{(id.imageFront || id.imageBack) && (
|
{(id.imageFrontFileId || id.imageBackFileId) && (
|
||||||
<div className="flex gap-2 mt-2">
|
<IdentifierImages identifierId={id.id} />
|
||||||
{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>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu'
|
} from '@/components/ui/dropdown-menu'
|
||||||
import { Search, Plus, MoreVertical, Pencil, Users } from 'lucide-react'
|
import { Search, Plus, MoreVertical, Pencil, Users } from 'lucide-react'
|
||||||
|
import { useAuthStore } from '@/stores/auth.store'
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/members/')({
|
export const Route = createFileRoute('/_authenticated/members/')({
|
||||||
validateSearch: (search: Record<string, unknown>) => ({
|
validateSearch: (search: Record<string, unknown>) => ({
|
||||||
@@ -28,6 +29,7 @@ export const Route = createFileRoute('/_authenticated/members/')({
|
|||||||
|
|
||||||
function MembersListPage() {
|
function MembersListPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
|
const hasPermission = useAuthStore((s) => s.hasPermission)
|
||||||
const { params, setPage, setSearch, setSort } = usePagination()
|
const { params, setPage, setSearch, setSort } = usePagination()
|
||||||
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
const [searchInput, setSearchInput] = useState(params.q ?? '')
|
||||||
|
|
||||||
@@ -100,10 +102,12 @@ function MembersListPage() {
|
|||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<h1 className="text-2xl font-bold">Members</h1>
|
<h1 className="text-2xl font-bold">Members</h1>
|
||||||
|
{hasPermission('accounts.edit') && (
|
||||||
<Button onClick={() => navigate({ to: '/accounts/new' })}>
|
<Button onClick={() => navigate({ to: '/accounts/new' })}>
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
New Member
|
New Member
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<form onSubmit={handleSearchSubmit} className="flex gap-2 max-w-sm">
|
<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 { Separator } from '@/components/ui/separator'
|
||||||
import { Sun, Moon, Monitor } from 'lucide-react'
|
import { Sun, Moon, Monitor } from 'lucide-react'
|
||||||
import { toast } from 'sonner'
|
import { toast } from 'sonner'
|
||||||
|
import { AvatarUpload } from '@/components/shared/avatar-upload'
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/profile')({
|
export const Route = createFileRoute('/_authenticated/profile')({
|
||||||
component: ProfilePage,
|
component: ProfilePage,
|
||||||
@@ -92,6 +93,15 @@ function ProfilePage() {
|
|||||||
<CardTitle className="text-lg">Account</CardTitle>
|
<CardTitle className="text-lg">Account</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-4">
|
<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">
|
<div className="space-y-2">
|
||||||
<Label>Email</Label>
|
<Label>Email</Label>
|
||||||
<Input value={profile?.email ?? ''} disabled className="opacity-60" />
|
<Input value={profile?.email ?? ''} disabled className="opacity-60" />
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ function RoleDetailPage() {
|
|||||||
return (
|
return (
|
||||||
<div className="space-y-6 max-w-2xl">
|
<div className="space-y-6 max-w-2xl">
|
||||||
<div className="flex items-center gap-3">
|
<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" />
|
<ArrowLeft className="h-4 w-4" />
|
||||||
</Button>
|
</Button>
|
||||||
<div>
|
<div>
|
||||||
@@ -177,7 +177,7 @@ function RoleDetailPage() {
|
|||||||
<Button onClick={handleSave} disabled={updateMutation.isPending}>
|
<Button onClick={handleSave} disabled={updateMutation.isPending}>
|
||||||
{updateMutation.isPending ? 'Saving...' : 'Save Changes'}
|
{updateMutation.isPending ? 'Saving...' : 'Save Changes'}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles' })}>
|
<Button variant="secondary" onClick={() => navigate({ to: '/roles', search: {} as any })}>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
import { createFileRoute, useNavigate } from '@tanstack/react-router'
|
||||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
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 { Button } from '@/components/ui/button'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
|
import { Input } from '@/components/ui/input'
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
@@ -11,70 +14,79 @@ import {
|
|||||||
DropdownMenuSeparator,
|
DropdownMenuSeparator,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu'
|
} 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 { toast } from 'sonner'
|
||||||
|
import { useAuthStore } from '@/stores/auth.store'
|
||||||
|
import type { Role } from '@/types/rbac'
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/roles/')({
|
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,
|
component: RolesListPage,
|
||||||
})
|
})
|
||||||
|
|
||||||
function RolesListPage() {
|
function RolesListPage() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
const queryClient = useQueryClient()
|
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({
|
const deleteMutation = useMutation({
|
||||||
mutationFn: rbacMutations.deleteRole,
|
mutationFn: rbacMutations.deleteRole,
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
||||||
|
queryClient.invalidateQueries({ queryKey: ['roles', 'list'] })
|
||||||
toast.success('Role deleted')
|
toast.success('Role deleted')
|
||||||
},
|
},
|
||||||
onError: (err) => toast.error(err.message),
|
onError: (err) => toast.error(err.message),
|
||||||
})
|
})
|
||||||
|
|
||||||
const roles = data?.data ?? []
|
function handleSearchSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault()
|
||||||
|
setSearch(searchInput)
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
const roleColumns: Column<Role>[] = [
|
||||||
<div className="space-y-6">
|
{
|
||||||
<div className="flex items-center justify-between">
|
key: 'name',
|
||||||
<h1 className="text-2xl font-bold">Roles</h1>
|
header: 'Name',
|
||||||
<Button onClick={() => navigate({ to: '/roles/new' })}>
|
sortable: true,
|
||||||
<Plus className="mr-2 h-4 w-4" />
|
render: (row) => (
|
||||||
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">
|
<div className="flex items-center gap-2">
|
||||||
<Shield className="h-4 w-4 text-muted-foreground" />
|
<Shield className="h-4 w-4 text-muted-foreground" />
|
||||||
{role.name}
|
<span className="font-medium">{row.name}</span>
|
||||||
</div>
|
</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>
|
key: 'slug',
|
||||||
{role.isSystem ? <Badge variant="secondary">System</Badge> : <Badge>Custom</Badge>}
|
header: 'Slug',
|
||||||
</TableCell>
|
sortable: true,
|
||||||
<TableCell>
|
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>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||||
@@ -82,14 +94,14 @@ function RolesListPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => navigate({ to: '/roles/$roleId', params: { roleId: role.id } })}>
|
<DropdownMenuItem onClick={() => navigate({ to: '/roles/$roleId', params: { roleId: row.id } })}>
|
||||||
<Pencil className="mr-2 h-4 w-4" />
|
<Pencil className="mr-2 h-4 w-4" />
|
||||||
Edit Permissions
|
Edit Permissions
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
{!role.isSystem && (
|
{!row.isSystem && hasPermission('users.admin') && (
|
||||||
<>
|
<>
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
<DropdownMenuItem className="text-destructive" onClick={() => deleteMutation.mutate(role.id)}>
|
<DropdownMenuItem className="text-destructive" onClick={() => deleteMutation.mutate(row.id)}>
|
||||||
<Trash2 className="mr-2 h-4 w-4" />
|
<Trash2 className="mr-2 h-4 w-4" />
|
||||||
Delete
|
Delete
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
@@ -97,13 +109,47 @@ function RolesListPage() {
|
|||||||
)}
|
)}
|
||||||
</DropdownMenuContent>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</TableCell>
|
),
|
||||||
</TableRow>
|
},
|
||||||
))}
|
]
|
||||||
</TableBody>
|
|
||||||
</Table>
|
return (
|
||||||
</div>
|
<div className="space-y-6">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h1 className="text-2xl font-bold">Roles</h1>
|
||||||
|
{hasPermission('users.admin') && (
|
||||||
|
<Button onClick={() => navigate({ to: '/roles/new' })}>
|
||||||
|
<Plus className="mr-2 h-4 w-4" />
|
||||||
|
New Role
|
||||||
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<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: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
queryClient.invalidateQueries({ queryKey: rbacKeys.roles })
|
||||||
toast.success('Role created')
|
toast.success('Role created')
|
||||||
navigate({ to: '/roles' })
|
navigate({ to: '/roles', search: {} as any })
|
||||||
},
|
},
|
||||||
onError: (err) => toast.error(err.message),
|
onError: (err) => toast.error(err.message),
|
||||||
})
|
})
|
||||||
@@ -153,7 +153,7 @@ function NewRolePage() {
|
|||||||
<Button onClick={handleSubmit} disabled={mutation.isPending}>
|
<Button onClick={handleSubmit} disabled={mutation.isPending}>
|
||||||
{mutation.isPending ? 'Creating...' : 'Create Role'}
|
{mutation.isPending ? 'Creating...' : 'Create Role'}
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="secondary" onClick={() => navigate({ to: '/roles' })}>
|
<Button variant="secondary" onClick={() => navigate({ to: '/roles', search: {} as any })}>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</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 { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||||
import { useState } from 'react'
|
import { useState } from 'react'
|
||||||
import { api } from '@/lib/api-client'
|
import { api } from '@/lib/api-client'
|
||||||
import { roleListOptions, rbacKeys, rbacMutations } from '@/api/rbac'
|
import { userListOptions, userRolesOptions, userKeys, userMutations, type UserRecord } from '@/api/users'
|
||||||
import { userRolesOptions, 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 { Button } from '@/components/ui/button'
|
||||||
import { Badge } from '@/components/ui/badge'
|
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 { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||||
import {
|
import {
|
||||||
@@ -15,38 +17,21 @@ import {
|
|||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu'
|
} 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 { toast } from 'sonner'
|
||||||
import { queryOptions } from '@tanstack/react-query'
|
import { useAuthStore } from '@/stores/auth.store'
|
||||||
|
|
||||||
function userListOptions() {
|
|
||||||
return queryOptions({
|
|
||||||
queryKey: ['users'],
|
|
||||||
queryFn: () => api.get<{ data: UserRecord[] }>('/v1/users'),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
export const Route = createFileRoute('/_authenticated/users')({
|
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,
|
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 }) {
|
function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: boolean; onClose: () => void }) {
|
||||||
const queryClient = useQueryClient()
|
const queryClient = useQueryClient()
|
||||||
const { data: userRolesData } = useQuery(userRolesOptions(user.id))
|
const { data: userRolesData } = useQuery(userRolesOptions(user.id))
|
||||||
@@ -61,7 +46,7 @@ function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: bo
|
|||||||
const assignMutation = useMutation({
|
const assignMutation = useMutation({
|
||||||
mutationFn: (roleId: string) => rbacMutations.assignRole(user.id, roleId),
|
mutationFn: (roleId: string) => rbacMutations.assignRole(user.id, roleId),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['users', user.id, 'roles'] })
|
queryClient.invalidateQueries({ queryKey: ['users'] })
|
||||||
setSelectedRoleId('')
|
setSelectedRoleId('')
|
||||||
toast.success('Role assigned')
|
toast.success('Role assigned')
|
||||||
},
|
},
|
||||||
@@ -71,7 +56,7 @@ function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: bo
|
|||||||
const removeMutation = useMutation({
|
const removeMutation = useMutation({
|
||||||
mutationFn: (roleId: string) => rbacMutations.removeRole(user.id, roleId),
|
mutationFn: (roleId: string) => rbacMutations.removeRole(user.id, roleId),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
queryClient.invalidateQueries({ queryKey: ['users', user.id, 'roles'] })
|
queryClient.invalidateQueries({ queryKey: ['users'] })
|
||||||
toast.success('Role removed')
|
toast.success('Role removed')
|
||||||
},
|
},
|
||||||
onError: (err) => toast.error(err.message),
|
onError: (err) => toast.error(err.message),
|
||||||
@@ -135,41 +120,82 @@ function ManageRolesDialog({ user, open, onClose }: { user: UserRecord; open: bo
|
|||||||
}
|
}
|
||||||
|
|
||||||
function UsersPage() {
|
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 [managingUser, setManagingUser] = useState<UserRecord | null>(null)
|
||||||
|
|
||||||
const allUsers = data?.data ?? []
|
const { data, isLoading } = useQuery(userListOptions(params))
|
||||||
|
|
||||||
return (
|
const statusMutation = useMutation({
|
||||||
<div className="space-y-6">
|
mutationFn: ({ userId, isActive }: { userId: string; isActive: boolean }) =>
|
||||||
<h1 className="text-2xl font-bold">Users</h1>
|
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),
|
||||||
|
})
|
||||||
|
|
||||||
{managingUser && (
|
function handleSearchSubmit(e: React.FormEvent) {
|
||||||
<ManageRolesDialog user={managingUser} open={!!managingUser} onClose={() => setManagingUser(null)} />
|
e.preventDefault()
|
||||||
)}
|
setSearch(searchInput)
|
||||||
|
}
|
||||||
|
|
||||||
{isLoading ? (
|
const userColumns: Column<UserRecord>[] = [
|
||||||
<p className="text-muted-foreground">Loading...</p>
|
{
|
||||||
) : allUsers.length === 0 ? (
|
key: 'name',
|
||||||
<p className="text-muted-foreground py-8 text-center">No users found</p>
|
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="rounded-md border">
|
<div className="flex flex-wrap gap-1">
|
||||||
<Table>
|
{row.roles.map((r) => (
|
||||||
<TableHeader>
|
<Badge key={r.id} variant={r.isSystem ? 'secondary' : 'default'} className="text-xs">
|
||||||
<TableRow>
|
{r.name}
|
||||||
<TableHead>Name</TableHead>
|
</Badge>
|
||||||
<TableHead>Email</TableHead>
|
))}
|
||||||
<TableHead>Roles</TableHead>
|
</div>
|
||||||
<TableHead className="w-12"></TableHead>
|
),
|
||||||
</TableRow>
|
},
|
||||||
</TableHeader>
|
{
|
||||||
<TableBody>
|
key: 'status',
|
||||||
{allUsers.map((user) => (
|
header: 'Status',
|
||||||
<TableRow key={user.id}>
|
render: (row) =>
|
||||||
<TableCell className="font-medium">{user.firstName} {user.lastName}</TableCell>
|
row.isActive ? (
|
||||||
<TableCell>{user.email}</TableCell>
|
<Badge variant="secondary" className="text-xs">Active</Badge>
|
||||||
<TableCell><UserRoleBadges userId={user.id} /></TableCell>
|
) : (
|
||||||
<TableCell>
|
<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>
|
<DropdownMenu>
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenuTrigger asChild>
|
||||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
|
||||||
@@ -177,13 +203,16 @@ function UsersPage() {
|
|||||||
</Button>
|
</Button>
|
||||||
</DropdownMenuTrigger>
|
</DropdownMenuTrigger>
|
||||||
<DropdownMenuContent align="end">
|
<DropdownMenuContent align="end">
|
||||||
<DropdownMenuItem onClick={() => setManagingUser(user)}>
|
{hasPermission('users.edit') && (
|
||||||
|
<DropdownMenuItem onClick={() => setManagingUser(row)}>
|
||||||
<Shield className="mr-2 h-4 w-4" />
|
<Shield className="mr-2 h-4 w-4" />
|
||||||
Manage Roles
|
Manage Roles
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
|
{hasPermission('users.admin') && (
|
||||||
<DropdownMenuItem onClick={async () => {
|
<DropdownMenuItem onClick={async () => {
|
||||||
try {
|
try {
|
||||||
const res = await api.post<{ resetLink: string }>(`/v1/auth/reset-password/${user.id}`, {})
|
const res = await api.post<{ resetLink: string }>(`/v1/auth/reset-password/${row.id}`, {})
|
||||||
await navigator.clipboard.writeText(res.resetLink)
|
await navigator.clipboard.writeText(res.resetLink)
|
||||||
toast.success('Reset link copied to clipboard')
|
toast.success('Reset link copied to clipboard')
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -193,15 +222,63 @@ function UsersPage() {
|
|||||||
<KeyRound className="mr-2 h-4 w-4" />
|
<KeyRound className="mr-2 h-4 w-4" />
|
||||||
Reset Password Link
|
Reset Password Link
|
||||||
</DropdownMenuItem>
|
</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>
|
</DropdownMenuContent>
|
||||||
</DropdownMenu>
|
</DropdownMenu>
|
||||||
</TableCell>
|
),
|
||||||
</TableRow>
|
},
|
||||||
))}
|
]
|
||||||
</TableBody>
|
|
||||||
</Table>
|
return (
|
||||||
</div>
|
<div className="space-y-6">
|
||||||
|
<h1 className="text-2xl font-bold">Users</h1>
|
||||||
|
|
||||||
|
{managingUser && (
|
||||||
|
<ManageRolesDialog user={managingUser} open={!!managingUser} onClose={() => setManagingUser(null)} />
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<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>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ export const Route = createFileRoute('/login')({
|
|||||||
beforeLoad: () => {
|
beforeLoad: () => {
|
||||||
const { token } = useAuthStore.getState()
|
const { token } = useAuthStore.getState()
|
||||||
if (token) {
|
if (token) {
|
||||||
throw redirect({ to: '/accounts' })
|
throw redirect({ to: '/accounts', search: {} as any })
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
component: LoginPage,
|
component: LoginPage,
|
||||||
@@ -30,7 +30,7 @@ function LoginPage() {
|
|||||||
const res = await login(email, password)
|
const res = await login(email, password)
|
||||||
setAuth(res.token, res.user)
|
setAuth(res.token, res.user)
|
||||||
await router.invalidate()
|
await router.invalidate()
|
||||||
await router.navigate({ to: '/accounts', replace: true })
|
await router.navigate({ to: '/accounts', search: {} as any, replace: true })
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : 'Login failed')
|
setError(err instanceof Error ? err.message : 'Login failed')
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -12,16 +12,49 @@ interface AuthState {
|
|||||||
token: string | null
|
token: string | null
|
||||||
user: User | null
|
user: User | null
|
||||||
companyId: string | null
|
companyId: string | null
|
||||||
|
permissions: Set<string>
|
||||||
|
permissionsLoaded: boolean
|
||||||
setAuth: (token: string, user: User) => void
|
setAuth: (token: string, user: User) => void
|
||||||
|
setPermissions: (slugs: string[]) => void
|
||||||
|
hasPermission: (slug: string) => boolean
|
||||||
logout: () => void
|
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 } {
|
function decodeJwtPayload(token: string): { id: string; companyId: string; role: string } {
|
||||||
const payload = token.split('.')[1]
|
const payload = token.split('.')[1]
|
||||||
return JSON.parse(atob(payload))
|
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 {
|
try {
|
||||||
const raw = sessionStorage.getItem('forte-auth')
|
const raw = sessionStorage.getItem('forte-auth')
|
||||||
if (!raw) return null
|
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) {
|
function saveSession(token: string, user: User, companyId: string, permissions?: string[]) {
|
||||||
sessionStorage.setItem('forte-auth', JSON.stringify({ token, user, companyId }))
|
sessionStorage.setItem('forte-auth', JSON.stringify({ token, user, companyId, permissions }))
|
||||||
}
|
}
|
||||||
|
|
||||||
function clearSession() {
|
function clearSession() {
|
||||||
sessionStorage.removeItem('forte-auth')
|
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 initial = typeof window !== 'undefined' ? loadSession() : null
|
||||||
|
const initialPerms = initial?.permissions ? expandPermissions(initial.permissions) : new Set<string>()
|
||||||
return {
|
return {
|
||||||
token: initial?.token ?? null,
|
token: initial?.token ?? null,
|
||||||
user: initial?.user ?? null,
|
user: initial?.user ?? null,
|
||||||
companyId: initial?.companyId ?? null,
|
companyId: initial?.companyId ?? null,
|
||||||
|
permissions: initialPerms,
|
||||||
|
permissionsLoaded: initialPerms.size > 0,
|
||||||
|
|
||||||
setAuth: (token, user) => {
|
setAuth: (token, user) => {
|
||||||
const payload = decodeJwtPayload(token)
|
const payload = decodeJwtPayload(token)
|
||||||
@@ -52,8 +88,22 @@ export const useAuthStore = create<AuthState>((set) => {
|
|||||||
set({ token, user, companyId: payload.companyId })
|
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: () => {
|
logout: () => {
|
||||||
clearSession()
|
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
|
issuingAuthority: string | null
|
||||||
issuedDate: string | null
|
issuedDate: string | null
|
||||||
expiresAt: string | null
|
expiresAt: string | null
|
||||||
imageFront: string | null
|
imageFrontFileId: string | null
|
||||||
imageBack: string | null
|
imageBackFileId: string | null
|
||||||
notes: string | null
|
notes: string | null
|
||||||
isPrimary: boolean
|
isPrimary: boolean
|
||||||
createdAt: string
|
createdAt: string
|
||||||
|
|||||||
@@ -139,6 +139,35 @@ suite('Files', { tags: ['files', 'storage'] }, (t) => {
|
|||||||
t.assert.equal(res.status, 400)
|
t.assert.equal(res.status, 400)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.test('uploads profile picture for user entity type', { tags: ['upload', 'profile'] }, async () => {
|
||||||
|
// Get the current test user ID from the users list
|
||||||
|
const usersRes = await t.api.get('/v1/users')
|
||||||
|
const testUser = usersRes.data.data[0]
|
||||||
|
t.assert.ok(testUser)
|
||||||
|
|
||||||
|
const formData = new FormData()
|
||||||
|
formData.append('file', new Blob([TINY_JPEG], { type: 'image/jpeg' }), 'avatar.jpg')
|
||||||
|
formData.append('entityType', 'user')
|
||||||
|
formData.append('entityId', testUser.id)
|
||||||
|
formData.append('category', 'profile')
|
||||||
|
|
||||||
|
const res = await fetch(`${t.baseUrl}/v1/files`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { Authorization: `Bearer ${t.token}` },
|
||||||
|
body: formData,
|
||||||
|
})
|
||||||
|
const data = await res.json()
|
||||||
|
|
||||||
|
t.assert.equal(res.status, 201)
|
||||||
|
t.assert.equal(data.entityType, 'user')
|
||||||
|
t.assert.equal(data.category, 'profile')
|
||||||
|
|
||||||
|
// Verify it shows up in files list
|
||||||
|
const listRes = await t.api.get('/v1/files', { entityType: 'user', entityId: testUser.id })
|
||||||
|
t.assert.status(listRes, 200)
|
||||||
|
t.assert.greaterThan(listRes.data.data.length, 0)
|
||||||
|
})
|
||||||
|
|
||||||
t.test('returns 404 for missing file', { tags: ['read'] }, async () => {
|
t.test('returns 404 for missing file', { tags: ['read'] }, async () => {
|
||||||
const res = await t.api.get('/v1/files/a0000000-0000-0000-0000-999999999999')
|
const res = await t.api.get('/v1/files/a0000000-0000-0000-0000-999999999999')
|
||||||
t.assert.status(res, 404)
|
t.assert.status(res, 404)
|
||||||
|
|||||||
@@ -172,6 +172,7 @@ suite('RBAC', { tags: ['rbac', 'permissions'] }, (t) => {
|
|||||||
t.test('roles list returns system roles', { tags: ['roles'] }, async () => {
|
t.test('roles list returns system roles', { tags: ['roles'] }, async () => {
|
||||||
const res = await t.api.get('/v1/roles')
|
const res = await t.api.get('/v1/roles')
|
||||||
t.assert.status(res, 200)
|
t.assert.status(res, 200)
|
||||||
|
t.assert.ok(res.data.pagination)
|
||||||
const slugs = res.data.data.map((r: { slug: string }) => r.slug)
|
const slugs = res.data.data.map((r: { slug: string }) => r.slug)
|
||||||
t.assert.includes(slugs, 'admin')
|
t.assert.includes(slugs, 'admin')
|
||||||
t.assert.includes(slugs, 'manager')
|
t.assert.includes(slugs, 'manager')
|
||||||
@@ -181,6 +182,13 @@ suite('RBAC', { tags: ['rbac', 'permissions'] }, (t) => {
|
|||||||
t.assert.includes(slugs, 'viewer')
|
t.assert.includes(slugs, 'viewer')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.test('roles/all returns unpaginated list', { tags: ['roles'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/roles/all')
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.greaterThan(res.data.data.length, 5)
|
||||||
|
t.assert.equal(res.data.pagination, undefined)
|
||||||
|
})
|
||||||
|
|
||||||
t.test('permissions list returns all system permissions', { tags: ['permissions'] }, async () => {
|
t.test('permissions list returns all system permissions', { tags: ['permissions'] }, async () => {
|
||||||
const res = await t.api.get('/v1/permissions')
|
const res = await t.api.get('/v1/permissions')
|
||||||
t.assert.status(res, 200)
|
t.assert.status(res, 200)
|
||||||
@@ -196,6 +204,120 @@ suite('RBAC', { tags: ['rbac', 'permissions'] }, (t) => {
|
|||||||
t.assert.equal(deleteRes.status, 403)
|
t.assert.equal(deleteRes.status, 403)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.test('roles search by name', { tags: ['roles', 'search'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/roles', { q: 'admin' })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.greaterThan(res.data.data.length, 0)
|
||||||
|
t.assert.ok(res.data.data.every((r: { name: string }) => r.name.toLowerCase().includes('admin')))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('roles sort by name descending', { tags: ['roles', 'sort'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/roles', { sort: 'name', order: 'desc' })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
const names = res.data.data.map((r: { name: string }) => r.name)
|
||||||
|
const sorted = [...names].sort().reverse()
|
||||||
|
t.assert.equal(JSON.stringify(names), JSON.stringify(sorted))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('users list is paginated with roles', { tags: ['users', 'pagination'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/users')
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.ok(res.data.pagination)
|
||||||
|
t.assert.greaterThan(res.data.data.length, 0)
|
||||||
|
// Each user should have a roles array
|
||||||
|
const first = res.data.data[0]
|
||||||
|
t.assert.ok(Array.isArray(first.roles))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('users search by name', { tags: ['users', 'search'] }, async () => {
|
||||||
|
// Create a user with a distinctive name
|
||||||
|
await fetch(`${t.baseUrl}/v1/auth/register`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', 'x-company-id': 'a0000000-0000-0000-0000-000000000001' },
|
||||||
|
body: JSON.stringify({ email: `searchme-${Date.now()}@test.com`, password: 'testpassword1234', firstName: 'Searchable', lastName: 'Pessoa', role: 'staff' }),
|
||||||
|
})
|
||||||
|
|
||||||
|
const res = await t.api.get('/v1/users', { q: 'Searchable' })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
t.assert.equal(res.data.data.length, 1)
|
||||||
|
t.assert.equal(res.data.data[0].firstName, 'Searchable')
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('users sort by email ascending', { tags: ['users', 'sort'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/users', { sort: 'email', order: 'asc' })
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
const emails = res.data.data.map((u: { email: string }) => u.email)
|
||||||
|
const sorted = [...emails].sort()
|
||||||
|
t.assert.equal(JSON.stringify(emails), JSON.stringify(sorted))
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('can disable and re-enable a user', { tags: ['users', 'status'] }, async () => {
|
||||||
|
// Create a user
|
||||||
|
const email = `disable-${Date.now()}@test.com`
|
||||||
|
const password = 'testpassword1234'
|
||||||
|
const regRes = await fetch(`${t.baseUrl}/v1/auth/register`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', 'x-company-id': 'a0000000-0000-0000-0000-000000000001' },
|
||||||
|
body: JSON.stringify({ email, password, firstName: 'Disable', lastName: 'Me', role: 'staff' }),
|
||||||
|
})
|
||||||
|
const regData = await regRes.json() as { user: { id: string } }
|
||||||
|
const userId = regData.user.id
|
||||||
|
|
||||||
|
// Disable the user
|
||||||
|
const disableRes = await t.api.patch(`/v1/users/${userId}/status`, { isActive: false })
|
||||||
|
t.assert.status(disableRes, 200)
|
||||||
|
t.assert.equal(disableRes.data.isActive, false)
|
||||||
|
|
||||||
|
// Disabled user cannot authenticate
|
||||||
|
const loginRes = await fetch(`${t.baseUrl}/v1/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ email, password }),
|
||||||
|
})
|
||||||
|
const loginData = await loginRes.json() as { token: string }
|
||||||
|
|
||||||
|
// Try to use the token — should get 401
|
||||||
|
const authRes = await fetch(`${t.baseUrl}/v1/accounts`, {
|
||||||
|
headers: { Authorization: `Bearer ${loginData.token}` },
|
||||||
|
})
|
||||||
|
t.assert.equal(authRes.status, 401)
|
||||||
|
|
||||||
|
// Re-enable the user
|
||||||
|
const enableRes = await t.api.patch(`/v1/users/${userId}/status`, { isActive: true })
|
||||||
|
t.assert.status(enableRes, 200)
|
||||||
|
t.assert.equal(enableRes.data.isActive, true)
|
||||||
|
|
||||||
|
// Now they can authenticate again
|
||||||
|
const reLoginRes = await fetch(`${t.baseUrl}/v1/auth/login`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ email, password }),
|
||||||
|
})
|
||||||
|
const reLoginData = await reLoginRes.json() as { token: string }
|
||||||
|
const reAuthRes = await fetch(`${t.baseUrl}/v1/accounts`, {
|
||||||
|
headers: { Authorization: `Bearer ${reLoginData.token}` },
|
||||||
|
})
|
||||||
|
// Will be 403 (no permissions) but NOT 401 (not disabled)
|
||||||
|
t.assert.notEqual(reAuthRes.status, 401)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('cannot disable yourself', { tags: ['users', 'status'] }, async () => {
|
||||||
|
// Get current user ID from the users list
|
||||||
|
const usersRes = await t.api.get('/v1/users')
|
||||||
|
const currentUser = usersRes.data.data.find((u: { email: string }) => u.email === 'test@forte.dev')
|
||||||
|
t.assert.ok(currentUser)
|
||||||
|
|
||||||
|
const res = await t.api.patch(`/v1/users/${currentUser.id}/status`, { isActive: false })
|
||||||
|
t.assert.equal(res.status, 400)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test('users list includes isActive field', { tags: ['users'] }, async () => {
|
||||||
|
const res = await t.api.get('/v1/users')
|
||||||
|
t.assert.status(res, 200)
|
||||||
|
const first = res.data.data[0]
|
||||||
|
t.assert.equal(typeof first.isActive, 'boolean')
|
||||||
|
})
|
||||||
|
|
||||||
t.test('can create and delete custom role', { tags: ['roles'] }, async () => {
|
t.test('can create and delete custom role', { tags: ['roles'] }, async () => {
|
||||||
const createRes = await t.api.post('/v1/roles', {
|
const createRes = await t.api.post('/v1/roles', {
|
||||||
name: 'Temp Role',
|
name: 'Temp Role',
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "user" ADD COLUMN "is_active" boolean NOT NULL DEFAULT true;
|
||||||
@@ -99,6 +99,13 @@
|
|||||||
"when": 1774730000000,
|
"when": 1774730000000,
|
||||||
"tag": "0013_rbac",
|
"tag": "0013_rbac",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 14,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1774740000000,
|
||||||
|
"tag": "0014_user_is_active",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { pgTable, uuid, varchar, timestamp, pgEnum, uniqueIndex } from 'drizzle-orm/pg-core'
|
import { pgTable, uuid, varchar, timestamp, pgEnum, uniqueIndex, boolean } from 'drizzle-orm/pg-core'
|
||||||
import { companies } from './stores.js'
|
import { companies } from './stores.js'
|
||||||
|
|
||||||
export const userRoleEnum = pgEnum('user_role', [
|
export const userRoleEnum = pgEnum('user_role', [
|
||||||
@@ -19,6 +19,7 @@ export const users = pgTable('user', {
|
|||||||
firstName: varchar('first_name', { length: 100 }).notNull(),
|
firstName: varchar('first_name', { length: 100 }).notNull(),
|
||||||
lastName: varchar('last_name', { length: 100 }).notNull(),
|
lastName: varchar('last_name', { length: 100 }).notNull(),
|
||||||
role: userRoleEnum('role').notNull().default('staff'),
|
role: userRoleEnum('role').notNull().default('staff'),
|
||||||
|
isActive: boolean('is_active').notNull().default(true),
|
||||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import fp from 'fastify-plugin'
|
import fp from 'fastify-plugin'
|
||||||
import fjwt from '@fastify/jwt'
|
import fjwt from '@fastify/jwt'
|
||||||
|
import { eq } from 'drizzle-orm'
|
||||||
|
import { users } from '../db/schema/users.js'
|
||||||
import { RbacService } from '../services/rbac.service.js'
|
import { RbacService } from '../services/rbac.service.js'
|
||||||
|
|
||||||
declare module 'fastify' {
|
declare module 'fastify' {
|
||||||
@@ -72,6 +74,18 @@ export const authPlugin = fp(async (app) => {
|
|||||||
await request.jwtVerify()
|
await request.jwtVerify()
|
||||||
request.companyId = request.user.companyId
|
request.companyId = request.user.companyId
|
||||||
|
|
||||||
|
// Check if user account is active
|
||||||
|
const [dbUser] = await app.db
|
||||||
|
.select({ isActive: users.isActive })
|
||||||
|
.from(users)
|
||||||
|
.where(eq(users.id, request.user.id))
|
||||||
|
.limit(1)
|
||||||
|
|
||||||
|
if (!dbUser || !dbUser.isActive) {
|
||||||
|
reply.status(401).send({ error: { message: 'Account disabled', statusCode: 401 } })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// Load permissions from DB and expand with inheritance
|
// Load permissions from DB and expand with inheritance
|
||||||
const permSlugs = await RbacService.getUserPermissions(app.db, request.user.id)
|
const permSlugs = await RbacService.getUserPermissions(app.db, request.user.id)
|
||||||
request.permissions = expandPermissions(permSlugs)
|
request.permissions = expandPermissions(permSlugs)
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import fp from 'fastify-plugin'
|
|||||||
import { AppError, ValidationError } from '../lib/errors.js'
|
import { AppError, ValidationError } from '../lib/errors.js'
|
||||||
|
|
||||||
export const errorHandlerPlugin = fp(async (app) => {
|
export const errorHandlerPlugin = fp(async (app) => {
|
||||||
app.setErrorHandler((error, request, reply) => {
|
app.setErrorHandler((error: Error & { statusCode?: number; stack?: string }, request, reply) => {
|
||||||
// Use AppError statusCode if available, else Fastify's, else 500
|
// Use AppError statusCode if available, else Fastify's, else 500
|
||||||
const statusCode = error instanceof AppError
|
const statusCode = error instanceof AppError
|
||||||
? error.statusCode
|
? error.statusCode
|
||||||
|
|||||||
@@ -124,6 +124,7 @@ export const accountRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
if (!member) return reply.status(404).send({ error: { message: 'Member not found', statusCode: 404 } })
|
if (!member) return reply.status(404).send({ error: { message: 'Member not found', statusCode: 404 } })
|
||||||
const account = await AccountService.create(app.db, request.companyId, {
|
const account = await AccountService.create(app.db, request.companyId, {
|
||||||
name: `${member.firstName} ${member.lastName}`,
|
name: `${member.firstName} ${member.lastName}`,
|
||||||
|
billingMode: 'consolidated',
|
||||||
})
|
})
|
||||||
targetAccountId = account.id
|
targetAccountId = account.id
|
||||||
}
|
}
|
||||||
@@ -148,8 +149,9 @@ export const accountRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
|
|
||||||
app.get('/members/:memberId/identifiers', { preHandler: [app.authenticate, app.requirePermission('accounts.view')] }, async (request, reply) => {
|
app.get('/members/:memberId/identifiers', { preHandler: [app.authenticate, app.requirePermission('accounts.view')] }, async (request, reply) => {
|
||||||
const { memberId } = request.params as { memberId: string }
|
const { memberId } = request.params as { memberId: string }
|
||||||
const identifiers = await MemberIdentifierService.listByMember(app.db, request.companyId, memberId)
|
const params = PaginationSchema.parse(request.query)
|
||||||
return reply.send({ data: identifiers })
|
const result = await MemberIdentifierService.listByMember(app.db, request.companyId, memberId, params)
|
||||||
|
return reply.send(result)
|
||||||
})
|
})
|
||||||
|
|
||||||
app.patch('/identifiers/:id', { preHandler: [app.authenticate, app.requirePermission('accounts.edit')] }, async (request, reply) => {
|
app.patch('/identifiers/:id', { preHandler: [app.authenticate, app.requirePermission('accounts.edit')] }, async (request, reply) => {
|
||||||
@@ -191,8 +193,9 @@ export const accountRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
|
|
||||||
app.get('/accounts/:accountId/processor-links', { preHandler: [app.authenticate, app.requirePermission('accounts.view')] }, async (request, reply) => {
|
app.get('/accounts/:accountId/processor-links', { preHandler: [app.authenticate, app.requirePermission('accounts.view')] }, async (request, reply) => {
|
||||||
const { accountId } = request.params as { accountId: string }
|
const { accountId } = request.params as { accountId: string }
|
||||||
const links = await ProcessorLinkService.listByAccount(app.db, request.companyId, accountId)
|
const params = PaginationSchema.parse(request.query)
|
||||||
return reply.send({ data: links })
|
const result = await ProcessorLinkService.listByAccount(app.db, request.companyId, accountId, params)
|
||||||
|
return reply.send(result)
|
||||||
})
|
})
|
||||||
|
|
||||||
app.patch('/processor-links/:id', { preHandler: [app.authenticate, app.requirePermission('accounts.edit')] }, async (request, reply) => {
|
app.patch('/processor-links/:id', { preHandler: [app.authenticate, app.requirePermission('accounts.edit')] }, async (request, reply) => {
|
||||||
@@ -227,8 +230,9 @@ export const accountRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
|
|
||||||
app.get('/accounts/:accountId/payment-methods', { preHandler: [app.authenticate, app.requirePermission('accounts.view')] }, async (request, reply) => {
|
app.get('/accounts/:accountId/payment-methods', { preHandler: [app.authenticate, app.requirePermission('accounts.view')] }, async (request, reply) => {
|
||||||
const { accountId } = request.params as { accountId: string }
|
const { accountId } = request.params as { accountId: string }
|
||||||
const methods = await PaymentMethodService.listByAccount(app.db, request.companyId, accountId)
|
const params = PaginationSchema.parse(request.query)
|
||||||
return reply.send({ data: methods })
|
const result = await PaymentMethodService.listByAccount(app.db, request.companyId, accountId, params)
|
||||||
|
return reply.send(result)
|
||||||
})
|
})
|
||||||
|
|
||||||
app.get('/payment-methods/:id', { preHandler: [app.authenticate, app.requirePermission('accounts.view')] }, async (request, reply) => {
|
app.get('/payment-methods/:id', { preHandler: [app.authenticate, app.requirePermission('accounts.view')] }, async (request, reply) => {
|
||||||
@@ -270,8 +274,9 @@ export const accountRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
|
|
||||||
app.get('/accounts/:accountId/tax-exemptions', { preHandler: [app.authenticate, app.requirePermission('accounts.view')] }, async (request, reply) => {
|
app.get('/accounts/:accountId/tax-exemptions', { preHandler: [app.authenticate, app.requirePermission('accounts.view')] }, async (request, reply) => {
|
||||||
const { accountId } = request.params as { accountId: string }
|
const { accountId } = request.params as { accountId: string }
|
||||||
const exemptions = await TaxExemptionService.listByAccount(app.db, request.companyId, accountId)
|
const params = PaginationSchema.parse(request.query)
|
||||||
return reply.send({ data: exemptions })
|
const result = await TaxExemptionService.listByAccount(app.db, request.companyId, accountId, params)
|
||||||
|
return reply.send(result)
|
||||||
})
|
})
|
||||||
|
|
||||||
app.get('/tax-exemptions/:id', { preHandler: [app.authenticate, app.requirePermission('accounts.view')] }, async (request, reply) => {
|
app.get('/tax-exemptions/:id', { preHandler: [app.authenticate, app.requirePermission('accounts.view')] }, async (request, reply) => {
|
||||||
|
|||||||
@@ -176,7 +176,7 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
if (!user) return reply.status(404).send({ error: { message: 'User not found', statusCode: 404 } })
|
if (!user) return reply.status(404).send({ error: { message: 'User not found', statusCode: 404 } })
|
||||||
|
|
||||||
// Generate a signed reset token that expires in 1 hour
|
// Generate a signed reset token that expires in 1 hour
|
||||||
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' }, { expiresIn: '1h' })
|
const resetToken = app.jwt.sign({ userId: user.id, purpose: 'password-reset' } as any, { expiresIn: '1h' })
|
||||||
const resetLink = `${process.env.APP_URL ?? 'http://localhost:5173'}/reset-password?token=${resetToken}`
|
const resetLink = `${process.env.APP_URL ?? 'http://localhost:5173'}/reset-password?token=${resetToken}`
|
||||||
|
|
||||||
request.log.info({ userId, generatedBy: request.user.id }, 'Password reset link generated')
|
request.log.info({ userId, generatedBy: request.user.id }, 'Password reset link generated')
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ export const fileRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Validate entityType is a known type
|
// Validate entityType is a known type
|
||||||
const allowedEntityTypes = ['member', 'member_identifier', 'product', 'rental_agreement', 'repair_ticket']
|
const allowedEntityTypes = ['user', 'member', 'member_identifier', 'product', 'rental_agreement', 'repair_ticket']
|
||||||
if (!allowedEntityTypes.includes(entityType)) {
|
if (!allowedEntityTypes.includes(entityType)) {
|
||||||
throw new ValidationError(`Invalid entityType: ${entityType}`)
|
throw new ValidationError(`Invalid entityType: ${entityType}`)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,28 +1,110 @@
|
|||||||
import type { FastifyPluginAsync } from 'fastify'
|
import type { FastifyPluginAsync } from 'fastify'
|
||||||
import { eq, and } from 'drizzle-orm'
|
import { eq, and, count, sql, type Column } from 'drizzle-orm'
|
||||||
|
import { PaginationSchema } from '@forte/shared/schemas'
|
||||||
import { RbacService } from '../../services/rbac.service.js'
|
import { RbacService } from '../../services/rbac.service.js'
|
||||||
import { ValidationError } from '../../lib/errors.js'
|
import { ValidationError } from '../../lib/errors.js'
|
||||||
import { users } from '../../db/schema/users.js'
|
import { users } from '../../db/schema/users.js'
|
||||||
|
import { roles, userRoles } from '../../db/schema/rbac.js'
|
||||||
|
import { withPagination, withSort, buildSearchCondition, paginatedResponse } from '../../utils/pagination.js'
|
||||||
|
|
||||||
export const rbacRoutes: FastifyPluginAsync = async (app) => {
|
export const rbacRoutes: FastifyPluginAsync = async (app) => {
|
||||||
// --- Users list ---
|
// --- Users list ---
|
||||||
|
|
||||||
app.get('/users', { preHandler: [app.authenticate, app.requirePermission('users.view')] }, async (request, reply) => {
|
app.get('/users', { preHandler: [app.authenticate, app.requirePermission('users.view')] }, async (request, reply) => {
|
||||||
const allUsers = await app.db
|
const params = PaginationSchema.parse(request.query)
|
||||||
|
const baseWhere = eq(users.companyId, request.companyId)
|
||||||
|
|
||||||
|
const searchCondition = params.q
|
||||||
|
? buildSearchCondition(params.q, [users.firstName, users.lastName, users.email])
|
||||||
|
: undefined
|
||||||
|
|
||||||
|
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
||||||
|
|
||||||
|
const sortableColumns: Record<string, Column> = {
|
||||||
|
name: users.lastName,
|
||||||
|
email: users.email,
|
||||||
|
created_at: users.createdAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
let query = app.db
|
||||||
.select({
|
.select({
|
||||||
id: users.id,
|
id: users.id,
|
||||||
email: users.email,
|
email: users.email,
|
||||||
firstName: users.firstName,
|
firstName: users.firstName,
|
||||||
lastName: users.lastName,
|
lastName: users.lastName,
|
||||||
role: users.role,
|
role: users.role,
|
||||||
|
isActive: users.isActive,
|
||||||
createdAt: users.createdAt,
|
createdAt: users.createdAt,
|
||||||
})
|
})
|
||||||
.from(users)
|
.from(users)
|
||||||
.where(eq(users.companyId, request.companyId))
|
.where(where)
|
||||||
.orderBy(users.lastName)
|
.$dynamic()
|
||||||
|
|
||||||
return reply.send({ data: allUsers })
|
query = withSort(query, params.sort, params.order, sortableColumns, users.lastName)
|
||||||
|
query = withPagination(query, params.page, params.limit)
|
||||||
|
|
||||||
|
const [data, [{ total }]] = await Promise.all([
|
||||||
|
query,
|
||||||
|
app.db.select({ total: count() }).from(users).where(where),
|
||||||
|
])
|
||||||
|
|
||||||
|
// Attach roles to each user
|
||||||
|
const userIds = data.map((u) => u.id)
|
||||||
|
const roleAssignments = userIds.length > 0
|
||||||
|
? await app.db
|
||||||
|
.select({
|
||||||
|
userId: userRoles.userId,
|
||||||
|
roleId: roles.id,
|
||||||
|
roleName: roles.name,
|
||||||
|
roleSlug: roles.slug,
|
||||||
|
isSystem: roles.isSystem,
|
||||||
})
|
})
|
||||||
|
.from(userRoles)
|
||||||
|
.innerJoin(roles, eq(userRoles.roleId, roles.id))
|
||||||
|
.where(sql`${userRoles.userId} IN ${userIds}`)
|
||||||
|
: []
|
||||||
|
|
||||||
|
const rolesByUser = new Map<string, { id: string; name: string; slug: string; isSystem: boolean }[]>()
|
||||||
|
for (const ra of roleAssignments) {
|
||||||
|
const list = rolesByUser.get(ra.userId) ?? []
|
||||||
|
list.push({ id: ra.roleId, name: ra.roleName, slug: ra.roleSlug, isSystem: ra.isSystem })
|
||||||
|
rolesByUser.set(ra.userId, list)
|
||||||
|
}
|
||||||
|
|
||||||
|
const usersWithRoles = data.map((u) => ({
|
||||||
|
...u,
|
||||||
|
roles: rolesByUser.get(u.id) ?? [],
|
||||||
|
}))
|
||||||
|
|
||||||
|
return reply.send(paginatedResponse(usersWithRoles, total, params.page, params.limit))
|
||||||
|
})
|
||||||
|
// --- User status ---
|
||||||
|
|
||||||
|
app.patch('/users/:userId/status', { preHandler: [app.authenticate, app.requirePermission('users.admin')] }, async (request, reply) => {
|
||||||
|
const { userId } = request.params as { userId: string }
|
||||||
|
const { isActive } = request.body as { isActive?: boolean }
|
||||||
|
|
||||||
|
if (typeof isActive !== 'boolean') {
|
||||||
|
throw new ValidationError('isActive (boolean) is required')
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prevent disabling yourself
|
||||||
|
if (userId === request.user.id) {
|
||||||
|
throw new ValidationError('Cannot change your own account status')
|
||||||
|
}
|
||||||
|
|
||||||
|
const [updated] = await app.db
|
||||||
|
.update(users)
|
||||||
|
.set({ isActive, updatedAt: new Date() })
|
||||||
|
.where(and(eq(users.id, userId), eq(users.companyId, request.companyId)))
|
||||||
|
.returning({ id: users.id, isActive: users.isActive })
|
||||||
|
|
||||||
|
if (!updated) return reply.status(404).send({ error: { message: 'User not found', statusCode: 404 } })
|
||||||
|
|
||||||
|
request.log.info({ userId, isActive, changedBy: request.user.id }, 'User status changed')
|
||||||
|
return reply.send(updated)
|
||||||
|
})
|
||||||
|
|
||||||
// --- Permissions ---
|
// --- Permissions ---
|
||||||
|
|
||||||
app.get('/permissions', { preHandler: [app.authenticate, app.requirePermission('users.view')] }, async (request, reply) => {
|
app.get('/permissions', { preHandler: [app.authenticate, app.requirePermission('users.view')] }, async (request, reply) => {
|
||||||
@@ -33,7 +115,18 @@ export const rbacRoutes: FastifyPluginAsync = async (app) => {
|
|||||||
// --- Roles ---
|
// --- Roles ---
|
||||||
|
|
||||||
app.get('/roles', { preHandler: [app.authenticate, app.requirePermission('users.view')] }, async (request, reply) => {
|
app.get('/roles', { preHandler: [app.authenticate, app.requirePermission('users.view')] }, async (request, reply) => {
|
||||||
const data = await RbacService.listRoles(app.db, request.companyId)
|
const params = PaginationSchema.parse(request.query)
|
||||||
|
const result = await RbacService.listRoles(app.db, request.companyId, params)
|
||||||
|
return reply.send(result)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Unpaginated list for dropdowns/selectors
|
||||||
|
app.get('/roles/all', { preHandler: [app.authenticate, app.requirePermission('users.view')] }, async (request, reply) => {
|
||||||
|
const data = await app.db
|
||||||
|
.select()
|
||||||
|
.from(roles)
|
||||||
|
.where(and(eq(roles.companyId, request.companyId), eq(roles.isActive, true)))
|
||||||
|
.orderBy(roles.name)
|
||||||
return reply.send({ data })
|
return reply.send({ data })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { eq, and, sql, count, exists } from 'drizzle-orm'
|
import { eq, and, sql, count, exists, type Column } from 'drizzle-orm'
|
||||||
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
|
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
|
||||||
import {
|
import {
|
||||||
accounts,
|
accounts,
|
||||||
@@ -30,11 +30,11 @@ import {
|
|||||||
} from '../utils/pagination.js'
|
} from '../utils/pagination.js'
|
||||||
|
|
||||||
async function generateUniqueNumber(
|
async function generateUniqueNumber(
|
||||||
db: PostgresJsDatabase,
|
db: PostgresJsDatabase<any>,
|
||||||
table: typeof accounts | typeof members,
|
table: typeof accounts | typeof members,
|
||||||
column: typeof accounts.accountNumber | typeof members.memberNumber,
|
column: typeof accounts.accountNumber | typeof members.memberNumber,
|
||||||
companyId: string,
|
companyId: string,
|
||||||
companyIdColumn: typeof accounts.companyId,
|
companyIdColumn: Column,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
for (let attempt = 0; attempt < 10; attempt++) {
|
for (let attempt = 0; attempt < 10; attempt++) {
|
||||||
const num = String(Math.floor(100000 + Math.random() * 900000))
|
const num = String(Math.floor(100000 + Math.random() * 900000))
|
||||||
@@ -58,7 +58,7 @@ function normalizeAddress(address?: { street?: string; city?: string; state?: st
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const AccountService = {
|
export const AccountService = {
|
||||||
async create(db: PostgresJsDatabase, companyId: string, input: AccountCreateInput) {
|
async create(db: PostgresJsDatabase<any>, companyId: string, input: AccountCreateInput) {
|
||||||
const accountNumber = await generateUniqueNumber(db, accounts, accounts.accountNumber, companyId, accounts.companyId)
|
const accountNumber = await generateUniqueNumber(db, accounts, accounts.accountNumber, companyId, accounts.companyId)
|
||||||
|
|
||||||
const [account] = await db
|
const [account] = await db
|
||||||
@@ -78,7 +78,7 @@ export const AccountService = {
|
|||||||
return account
|
return account
|
||||||
},
|
},
|
||||||
|
|
||||||
async getById(db: PostgresJsDatabase, companyId: string, id: string) {
|
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [account] = await db
|
const [account] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(accounts)
|
.from(accounts)
|
||||||
@@ -88,7 +88,7 @@ export const AccountService = {
|
|||||||
return account ?? null
|
return account ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async update(db: PostgresJsDatabase, companyId: string, id: string, input: AccountUpdateInput) {
|
async update(db: PostgresJsDatabase<any>, companyId: string, id: string, input: AccountUpdateInput) {
|
||||||
const [account] = await db
|
const [account] = await db
|
||||||
.update(accounts)
|
.update(accounts)
|
||||||
.set({ ...input, updatedAt: new Date() })
|
.set({ ...input, updatedAt: new Date() })
|
||||||
@@ -98,7 +98,7 @@ export const AccountService = {
|
|||||||
return account ?? null
|
return account ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async softDelete(db: PostgresJsDatabase, companyId: string, id: string) {
|
async softDelete(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [account] = await db
|
const [account] = await db
|
||||||
.update(accounts)
|
.update(accounts)
|
||||||
.set({ isActive: false, updatedAt: new Date() })
|
.set({ isActive: false, updatedAt: new Date() })
|
||||||
@@ -108,7 +108,7 @@ export const AccountService = {
|
|||||||
return account ?? null
|
return account ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async list(db: PostgresJsDatabase, companyId: string, params: PaginationInput) {
|
async list(db: PostgresJsDatabase<any>, companyId: string, params: PaginationInput) {
|
||||||
const baseWhere = and(eq(accounts.companyId, companyId), eq(accounts.isActive, true))
|
const baseWhere = and(eq(accounts.companyId, companyId), eq(accounts.isActive, true))
|
||||||
|
|
||||||
const accountSearch = params.q
|
const accountSearch = params.q
|
||||||
@@ -133,7 +133,7 @@ export const AccountService = {
|
|||||||
|
|
||||||
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
||||||
|
|
||||||
const sortableColumns: Record<string, typeof accounts.name> = {
|
const sortableColumns: Record<string, Column> = {
|
||||||
name: accounts.name,
|
name: accounts.name,
|
||||||
email: accounts.email,
|
email: accounts.email,
|
||||||
created_at: accounts.createdAt,
|
created_at: accounts.createdAt,
|
||||||
@@ -155,7 +155,7 @@ export const AccountService = {
|
|||||||
|
|
||||||
export const MemberService = {
|
export const MemberService = {
|
||||||
async create(
|
async create(
|
||||||
db: PostgresJsDatabase,
|
db: PostgresJsDatabase<any>,
|
||||||
companyId: string,
|
companyId: string,
|
||||||
input: {
|
input: {
|
||||||
accountId: string
|
accountId: string
|
||||||
@@ -210,7 +210,7 @@ export const MemberService = {
|
|||||||
return member
|
return member
|
||||||
},
|
},
|
||||||
|
|
||||||
async getById(db: PostgresJsDatabase, companyId: string, id: string) {
|
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [member] = await db
|
const [member] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(members)
|
.from(members)
|
||||||
@@ -220,7 +220,7 @@ export const MemberService = {
|
|||||||
return member ?? null
|
return member ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async list(db: PostgresJsDatabase, companyId: string, params: PaginationInput) {
|
async list(db: PostgresJsDatabase<any>, companyId: string, params: PaginationInput) {
|
||||||
const baseWhere = eq(members.companyId, companyId)
|
const baseWhere = eq(members.companyId, companyId)
|
||||||
|
|
||||||
const searchCondition = params.q
|
const searchCondition = params.q
|
||||||
@@ -229,7 +229,7 @@ export const MemberService = {
|
|||||||
|
|
||||||
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
||||||
|
|
||||||
const sortableColumns: Record<string, typeof members.firstName> = {
|
const sortableColumns: Record<string, Column> = {
|
||||||
first_name: members.firstName,
|
first_name: members.firstName,
|
||||||
last_name: members.lastName,
|
last_name: members.lastName,
|
||||||
email: members.email,
|
email: members.email,
|
||||||
@@ -268,14 +268,14 @@ export const MemberService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
async listByAccount(
|
async listByAccount(
|
||||||
db: PostgresJsDatabase,
|
db: PostgresJsDatabase<any>,
|
||||||
companyId: string,
|
companyId: string,
|
||||||
accountId: string,
|
accountId: string,
|
||||||
params: PaginationInput,
|
params: PaginationInput,
|
||||||
) {
|
) {
|
||||||
const where = and(eq(members.companyId, companyId), eq(members.accountId, accountId))
|
const where = and(eq(members.companyId, companyId), eq(members.accountId, accountId))
|
||||||
|
|
||||||
const sortableColumns: Record<string, typeof members.firstName> = {
|
const sortableColumns: Record<string, Column> = {
|
||||||
first_name: members.firstName,
|
first_name: members.firstName,
|
||||||
last_name: members.lastName,
|
last_name: members.lastName,
|
||||||
created_at: members.createdAt,
|
created_at: members.createdAt,
|
||||||
@@ -294,7 +294,7 @@ export const MemberService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
async update(
|
async update(
|
||||||
db: PostgresJsDatabase,
|
db: PostgresJsDatabase<any>,
|
||||||
companyId: string,
|
companyId: string,
|
||||||
id: string,
|
id: string,
|
||||||
input: {
|
input: {
|
||||||
@@ -325,7 +325,7 @@ export const MemberService = {
|
|||||||
return member ?? null
|
return member ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async move(db: PostgresJsDatabase, companyId: string, memberId: string, targetAccountId: string) {
|
async move(db: PostgresJsDatabase<any>, companyId: string, memberId: string, targetAccountId: string) {
|
||||||
const member = await this.getById(db, companyId, memberId)
|
const member = await this.getById(db, companyId, memberId)
|
||||||
if (!member) return null
|
if (!member) return null
|
||||||
|
|
||||||
@@ -351,7 +351,7 @@ export const MemberService = {
|
|||||||
return updated
|
return updated
|
||||||
},
|
},
|
||||||
|
|
||||||
async delete(db: PostgresJsDatabase, companyId: string, id: string) {
|
async delete(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [member] = await db
|
const [member] = await db
|
||||||
.delete(members)
|
.delete(members)
|
||||||
.where(and(eq(members.id, id), eq(members.companyId, companyId)))
|
.where(and(eq(members.id, id), eq(members.companyId, companyId)))
|
||||||
@@ -362,7 +362,7 @@ export const MemberService = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const ProcessorLinkService = {
|
export const ProcessorLinkService = {
|
||||||
async create(db: PostgresJsDatabase, companyId: string, input: ProcessorLinkCreateInput) {
|
async create(db: PostgresJsDatabase<any>, companyId: string, input: ProcessorLinkCreateInput) {
|
||||||
const [link] = await db
|
const [link] = await db
|
||||||
.insert(accountProcessorLinks)
|
.insert(accountProcessorLinks)
|
||||||
.values({
|
.values({
|
||||||
@@ -375,7 +375,7 @@ export const ProcessorLinkService = {
|
|||||||
return link
|
return link
|
||||||
},
|
},
|
||||||
|
|
||||||
async getById(db: PostgresJsDatabase, companyId: string, id: string) {
|
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [link] = await db
|
const [link] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(accountProcessorLinks)
|
.from(accountProcessorLinks)
|
||||||
@@ -384,19 +384,31 @@ export const ProcessorLinkService = {
|
|||||||
return link ?? null
|
return link ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async listByAccount(db: PostgresJsDatabase, companyId: string, accountId: string) {
|
async listByAccount(db: PostgresJsDatabase<any>, companyId: string, accountId: string, params: PaginationInput) {
|
||||||
return db
|
const baseWhere = and(eq(accountProcessorLinks.companyId, companyId), eq(accountProcessorLinks.accountId, accountId))
|
||||||
.select()
|
const searchCondition = params.q
|
||||||
.from(accountProcessorLinks)
|
? buildSearchCondition(params.q, [accountProcessorLinks.processorCustomerId, accountProcessorLinks.processor])
|
||||||
.where(
|
: undefined
|
||||||
and(
|
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
||||||
eq(accountProcessorLinks.companyId, companyId),
|
|
||||||
eq(accountProcessorLinks.accountId, accountId),
|
const sortableColumns: Record<string, Column> = {
|
||||||
),
|
processor: accountProcessorLinks.processor,
|
||||||
)
|
created_at: accountProcessorLinks.createdAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
let query = db.select().from(accountProcessorLinks).where(where).$dynamic()
|
||||||
|
query = withSort(query, params.sort, params.order, sortableColumns, accountProcessorLinks.createdAt)
|
||||||
|
query = withPagination(query, params.page, params.limit)
|
||||||
|
|
||||||
|
const [data, [{ total }]] = await Promise.all([
|
||||||
|
query,
|
||||||
|
db.select({ total: count() }).from(accountProcessorLinks).where(where),
|
||||||
|
])
|
||||||
|
|
||||||
|
return paginatedResponse(data, total, params.page, params.limit)
|
||||||
},
|
},
|
||||||
|
|
||||||
async update(db: PostgresJsDatabase, companyId: string, id: string, input: ProcessorLinkUpdateInput) {
|
async update(db: PostgresJsDatabase<any>, companyId: string, id: string, input: ProcessorLinkUpdateInput) {
|
||||||
const [link] = await db
|
const [link] = await db
|
||||||
.update(accountProcessorLinks)
|
.update(accountProcessorLinks)
|
||||||
.set(input)
|
.set(input)
|
||||||
@@ -405,7 +417,7 @@ export const ProcessorLinkService = {
|
|||||||
return link ?? null
|
return link ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async delete(db: PostgresJsDatabase, companyId: string, id: string) {
|
async delete(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [link] = await db
|
const [link] = await db
|
||||||
.delete(accountProcessorLinks)
|
.delete(accountProcessorLinks)
|
||||||
.where(and(eq(accountProcessorLinks.id, id), eq(accountProcessorLinks.companyId, companyId)))
|
.where(and(eq(accountProcessorLinks.id, id), eq(accountProcessorLinks.companyId, companyId)))
|
||||||
@@ -415,7 +427,7 @@ export const ProcessorLinkService = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const PaymentMethodService = {
|
export const PaymentMethodService = {
|
||||||
async create(db: PostgresJsDatabase, companyId: string, input: PaymentMethodCreateInput) {
|
async create(db: PostgresJsDatabase<any>, companyId: string, input: PaymentMethodCreateInput) {
|
||||||
// If this is the default, unset any existing default for this account
|
// If this is the default, unset any existing default for this account
|
||||||
if (input.isDefault) {
|
if (input.isDefault) {
|
||||||
await db
|
await db
|
||||||
@@ -447,7 +459,7 @@ export const PaymentMethodService = {
|
|||||||
return method
|
return method
|
||||||
},
|
},
|
||||||
|
|
||||||
async getById(db: PostgresJsDatabase, companyId: string, id: string) {
|
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [method] = await db
|
const [method] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(accountPaymentMethods)
|
.from(accountPaymentMethods)
|
||||||
@@ -456,19 +468,32 @@ export const PaymentMethodService = {
|
|||||||
return method ?? null
|
return method ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async listByAccount(db: PostgresJsDatabase, companyId: string, accountId: string) {
|
async listByAccount(db: PostgresJsDatabase<any>, companyId: string, accountId: string, params: PaginationInput) {
|
||||||
return db
|
const baseWhere = and(eq(accountPaymentMethods.companyId, companyId), eq(accountPaymentMethods.accountId, accountId))
|
||||||
.select()
|
const searchCondition = params.q
|
||||||
.from(accountPaymentMethods)
|
? buildSearchCondition(params.q, [accountPaymentMethods.cardBrand, accountPaymentMethods.lastFour])
|
||||||
.where(
|
: undefined
|
||||||
and(
|
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
||||||
eq(accountPaymentMethods.companyId, companyId),
|
|
||||||
eq(accountPaymentMethods.accountId, accountId),
|
const sortableColumns: Record<string, Column> = {
|
||||||
),
|
card_brand: accountPaymentMethods.cardBrand,
|
||||||
)
|
processor: accountPaymentMethods.processor,
|
||||||
|
created_at: accountPaymentMethods.createdAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
let query = db.select().from(accountPaymentMethods).where(where).$dynamic()
|
||||||
|
query = withSort(query, params.sort, params.order, sortableColumns, accountPaymentMethods.createdAt)
|
||||||
|
query = withPagination(query, params.page, params.limit)
|
||||||
|
|
||||||
|
const [data, [{ total }]] = await Promise.all([
|
||||||
|
query,
|
||||||
|
db.select({ total: count() }).from(accountPaymentMethods).where(where),
|
||||||
|
])
|
||||||
|
|
||||||
|
return paginatedResponse(data, total, params.page, params.limit)
|
||||||
},
|
},
|
||||||
|
|
||||||
async update(db: PostgresJsDatabase, companyId: string, id: string, input: PaymentMethodUpdateInput) {
|
async update(db: PostgresJsDatabase<any>, companyId: string, id: string, input: PaymentMethodUpdateInput) {
|
||||||
// If setting as default, unset existing default
|
// If setting as default, unset existing default
|
||||||
if (input.isDefault) {
|
if (input.isDefault) {
|
||||||
const existing = await this.getById(db, companyId, id)
|
const existing = await this.getById(db, companyId, id)
|
||||||
@@ -494,7 +519,7 @@ export const PaymentMethodService = {
|
|||||||
return method ?? null
|
return method ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async delete(db: PostgresJsDatabase, companyId: string, id: string) {
|
async delete(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [method] = await db
|
const [method] = await db
|
||||||
.delete(accountPaymentMethods)
|
.delete(accountPaymentMethods)
|
||||||
.where(and(eq(accountPaymentMethods.id, id), eq(accountPaymentMethods.companyId, companyId)))
|
.where(and(eq(accountPaymentMethods.id, id), eq(accountPaymentMethods.companyId, companyId)))
|
||||||
@@ -504,7 +529,7 @@ export const PaymentMethodService = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const TaxExemptionService = {
|
export const TaxExemptionService = {
|
||||||
async create(db: PostgresJsDatabase, companyId: string, input: TaxExemptionCreateInput) {
|
async create(db: PostgresJsDatabase<any>, companyId: string, input: TaxExemptionCreateInput) {
|
||||||
const [exemption] = await db
|
const [exemption] = await db
|
||||||
.insert(taxExemptions)
|
.insert(taxExemptions)
|
||||||
.values({
|
.values({
|
||||||
@@ -521,7 +546,7 @@ export const TaxExemptionService = {
|
|||||||
return exemption
|
return exemption
|
||||||
},
|
},
|
||||||
|
|
||||||
async getById(db: PostgresJsDatabase, companyId: string, id: string) {
|
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [exemption] = await db
|
const [exemption] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(taxExemptions)
|
.from(taxExemptions)
|
||||||
@@ -530,19 +555,33 @@ export const TaxExemptionService = {
|
|||||||
return exemption ?? null
|
return exemption ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async listByAccount(db: PostgresJsDatabase, companyId: string, accountId: string) {
|
async listByAccount(db: PostgresJsDatabase<any>, companyId: string, accountId: string, params: PaginationInput) {
|
||||||
return db
|
const baseWhere = and(eq(taxExemptions.companyId, companyId), eq(taxExemptions.accountId, accountId))
|
||||||
.select()
|
const searchCondition = params.q
|
||||||
.from(taxExemptions)
|
? buildSearchCondition(params.q, [taxExemptions.certificateNumber, taxExemptions.certificateType, taxExemptions.issuingState])
|
||||||
.where(
|
: undefined
|
||||||
and(
|
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
||||||
eq(taxExemptions.companyId, companyId),
|
|
||||||
eq(taxExemptions.accountId, accountId),
|
const sortableColumns: Record<string, Column> = {
|
||||||
),
|
certificate_number: taxExemptions.certificateNumber,
|
||||||
)
|
status: taxExemptions.status,
|
||||||
|
expires_at: taxExemptions.expiresAt,
|
||||||
|
created_at: taxExemptions.createdAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
let query = db.select().from(taxExemptions).where(where).$dynamic()
|
||||||
|
query = withSort(query, params.sort, params.order, sortableColumns, taxExemptions.createdAt)
|
||||||
|
query = withPagination(query, params.page, params.limit)
|
||||||
|
|
||||||
|
const [data, [{ total }]] = await Promise.all([
|
||||||
|
query,
|
||||||
|
db.select({ total: count() }).from(taxExemptions).where(where),
|
||||||
|
])
|
||||||
|
|
||||||
|
return paginatedResponse(data, total, params.page, params.limit)
|
||||||
},
|
},
|
||||||
|
|
||||||
async update(db: PostgresJsDatabase, companyId: string, id: string, input: TaxExemptionUpdateInput) {
|
async update(db: PostgresJsDatabase<any>, companyId: string, id: string, input: TaxExemptionUpdateInput) {
|
||||||
const [exemption] = await db
|
const [exemption] = await db
|
||||||
.update(taxExemptions)
|
.update(taxExemptions)
|
||||||
.set({ ...input, updatedAt: new Date() })
|
.set({ ...input, updatedAt: new Date() })
|
||||||
@@ -551,7 +590,7 @@ export const TaxExemptionService = {
|
|||||||
return exemption ?? null
|
return exemption ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async approve(db: PostgresJsDatabase, companyId: string, id: string, approvedBy: string) {
|
async approve(db: PostgresJsDatabase<any>, companyId: string, id: string, approvedBy: string) {
|
||||||
const [exemption] = await db
|
const [exemption] = await db
|
||||||
.update(taxExemptions)
|
.update(taxExemptions)
|
||||||
.set({
|
.set({
|
||||||
@@ -565,7 +604,7 @@ export const TaxExemptionService = {
|
|||||||
return exemption ?? null
|
return exemption ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async revoke(db: PostgresJsDatabase, companyId: string, id: string, revokedBy: string, reason: string) {
|
async revoke(db: PostgresJsDatabase<any>, companyId: string, id: string, revokedBy: string, reason: string) {
|
||||||
const [exemption] = await db
|
const [exemption] = await db
|
||||||
.update(taxExemptions)
|
.update(taxExemptions)
|
||||||
.set({
|
.set({
|
||||||
@@ -582,7 +621,7 @@ export const TaxExemptionService = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const MemberIdentifierService = {
|
export const MemberIdentifierService = {
|
||||||
async create(db: PostgresJsDatabase, companyId: string, input: MemberIdentifierCreateInput) {
|
async create(db: PostgresJsDatabase<any>, companyId: string, input: MemberIdentifierCreateInput) {
|
||||||
// If setting as primary, unset existing primary for this member
|
// If setting as primary, unset existing primary for this member
|
||||||
if (input.isPrimary) {
|
if (input.isPrimary) {
|
||||||
await db
|
await db
|
||||||
@@ -616,19 +655,31 @@ export const MemberIdentifierService = {
|
|||||||
return identifier
|
return identifier
|
||||||
},
|
},
|
||||||
|
|
||||||
async listByMember(db: PostgresJsDatabase, companyId: string, memberId: string) {
|
async listByMember(db: PostgresJsDatabase<any>, companyId: string, memberId: string, params: PaginationInput) {
|
||||||
return db
|
const baseWhere = and(eq(memberIdentifiers.companyId, companyId), eq(memberIdentifiers.memberId, memberId))
|
||||||
.select()
|
const searchCondition = params.q
|
||||||
.from(memberIdentifiers)
|
? buildSearchCondition(params.q, [memberIdentifiers.value, memberIdentifiers.label, memberIdentifiers.issuingAuthority])
|
||||||
.where(
|
: undefined
|
||||||
and(
|
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
||||||
eq(memberIdentifiers.companyId, companyId),
|
|
||||||
eq(memberIdentifiers.memberId, memberId),
|
const sortableColumns: Record<string, Column> = {
|
||||||
),
|
type: memberIdentifiers.type,
|
||||||
)
|
created_at: memberIdentifiers.createdAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
let query = db.select().from(memberIdentifiers).where(where).$dynamic()
|
||||||
|
query = withSort(query, params.sort, params.order, sortableColumns, memberIdentifiers.createdAt)
|
||||||
|
query = withPagination(query, params.page, params.limit)
|
||||||
|
|
||||||
|
const [data, [{ total }]] = await Promise.all([
|
||||||
|
query,
|
||||||
|
db.select({ total: count() }).from(memberIdentifiers).where(where),
|
||||||
|
])
|
||||||
|
|
||||||
|
return paginatedResponse(data, total, params.page, params.limit)
|
||||||
},
|
},
|
||||||
|
|
||||||
async getById(db: PostgresJsDatabase, companyId: string, id: string) {
|
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [identifier] = await db
|
const [identifier] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(memberIdentifiers)
|
.from(memberIdentifiers)
|
||||||
@@ -637,7 +688,7 @@ export const MemberIdentifierService = {
|
|||||||
return identifier ?? null
|
return identifier ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async update(db: PostgresJsDatabase, companyId: string, id: string, input: MemberIdentifierUpdateInput) {
|
async update(db: PostgresJsDatabase<any>, companyId: string, id: string, input: MemberIdentifierUpdateInput) {
|
||||||
if (input.isPrimary) {
|
if (input.isPrimary) {
|
||||||
const existing = await this.getById(db, companyId, id)
|
const existing = await this.getById(db, companyId, id)
|
||||||
if (existing) {
|
if (existing) {
|
||||||
@@ -661,7 +712,7 @@ export const MemberIdentifierService = {
|
|||||||
return identifier ?? null
|
return identifier ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async delete(db: PostgresJsDatabase, companyId: string, id: string) {
|
async delete(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [identifier] = await db
|
const [identifier] = await db
|
||||||
.delete(memberIdentifiers)
|
.delete(memberIdentifiers)
|
||||||
.where(and(eq(memberIdentifiers.id, id), eq(memberIdentifiers.companyId, companyId)))
|
.where(and(eq(memberIdentifiers.id, id), eq(memberIdentifiers.companyId, companyId)))
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ function getExtension(contentType: string): string {
|
|||||||
|
|
||||||
export const FileService = {
|
export const FileService = {
|
||||||
async upload(
|
async upload(
|
||||||
db: PostgresJsDatabase,
|
db: PostgresJsDatabase<any>,
|
||||||
storage: StorageProvider,
|
storage: StorageProvider,
|
||||||
companyId: string,
|
companyId: string,
|
||||||
input: {
|
input: {
|
||||||
@@ -91,7 +91,7 @@ export const FileService = {
|
|||||||
return file
|
return file
|
||||||
},
|
},
|
||||||
|
|
||||||
async getById(db: PostgresJsDatabase, companyId: string, id: string) {
|
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [file] = await db
|
const [file] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(files)
|
.from(files)
|
||||||
@@ -101,7 +101,7 @@ export const FileService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
async listByEntity(
|
async listByEntity(
|
||||||
db: PostgresJsDatabase,
|
db: PostgresJsDatabase<any>,
|
||||||
companyId: string,
|
companyId: string,
|
||||||
entityType: string,
|
entityType: string,
|
||||||
entityId: string,
|
entityId: string,
|
||||||
@@ -120,7 +120,7 @@ export const FileService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
async delete(
|
async delete(
|
||||||
db: PostgresJsDatabase,
|
db: PostgresJsDatabase<any>,
|
||||||
storage: StorageProvider,
|
storage: StorageProvider,
|
||||||
companyId: string,
|
companyId: string,
|
||||||
id: string,
|
id: string,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { eq, and, count } from 'drizzle-orm'
|
import { eq, and, count, type Column } from 'drizzle-orm'
|
||||||
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
|
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
|
||||||
import { categories, suppliers } from '../db/schema/inventory.js'
|
import { categories, suppliers } from '../db/schema/inventory.js'
|
||||||
import type {
|
import type {
|
||||||
@@ -16,7 +16,7 @@ import {
|
|||||||
} from '../utils/pagination.js'
|
} from '../utils/pagination.js'
|
||||||
|
|
||||||
export const CategoryService = {
|
export const CategoryService = {
|
||||||
async create(db: PostgresJsDatabase, companyId: string, input: CategoryCreateInput) {
|
async create(db: PostgresJsDatabase<any>, companyId: string, input: CategoryCreateInput) {
|
||||||
const [category] = await db
|
const [category] = await db
|
||||||
.insert(categories)
|
.insert(categories)
|
||||||
.values({ companyId, ...input })
|
.values({ companyId, ...input })
|
||||||
@@ -24,7 +24,7 @@ export const CategoryService = {
|
|||||||
return category
|
return category
|
||||||
},
|
},
|
||||||
|
|
||||||
async getById(db: PostgresJsDatabase, companyId: string, id: string) {
|
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [category] = await db
|
const [category] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(categories)
|
.from(categories)
|
||||||
@@ -33,7 +33,7 @@ export const CategoryService = {
|
|||||||
return category ?? null
|
return category ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async list(db: PostgresJsDatabase, companyId: string, params: PaginationInput) {
|
async list(db: PostgresJsDatabase<any>, companyId: string, params: PaginationInput) {
|
||||||
const baseWhere = and(eq(categories.companyId, companyId), eq(categories.isActive, true))
|
const baseWhere = and(eq(categories.companyId, companyId), eq(categories.isActive, true))
|
||||||
|
|
||||||
const searchCondition = params.q
|
const searchCondition = params.q
|
||||||
@@ -42,7 +42,7 @@ export const CategoryService = {
|
|||||||
|
|
||||||
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
||||||
|
|
||||||
const sortableColumns: Record<string, typeof categories.name> = {
|
const sortableColumns: Record<string, Column> = {
|
||||||
name: categories.name,
|
name: categories.name,
|
||||||
sort_order: categories.sortOrder,
|
sort_order: categories.sortOrder,
|
||||||
created_at: categories.createdAt,
|
created_at: categories.createdAt,
|
||||||
@@ -60,7 +60,7 @@ export const CategoryService = {
|
|||||||
return paginatedResponse(data, total, params.page, params.limit)
|
return paginatedResponse(data, total, params.page, params.limit)
|
||||||
},
|
},
|
||||||
|
|
||||||
async update(db: PostgresJsDatabase, companyId: string, id: string, input: CategoryUpdateInput) {
|
async update(db: PostgresJsDatabase<any>, companyId: string, id: string, input: CategoryUpdateInput) {
|
||||||
const [category] = await db
|
const [category] = await db
|
||||||
.update(categories)
|
.update(categories)
|
||||||
.set({ ...input, updatedAt: new Date() })
|
.set({ ...input, updatedAt: new Date() })
|
||||||
@@ -69,7 +69,7 @@ export const CategoryService = {
|
|||||||
return category ?? null
|
return category ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async softDelete(db: PostgresJsDatabase, companyId: string, id: string) {
|
async softDelete(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [category] = await db
|
const [category] = await db
|
||||||
.update(categories)
|
.update(categories)
|
||||||
.set({ isActive: false, updatedAt: new Date() })
|
.set({ isActive: false, updatedAt: new Date() })
|
||||||
@@ -80,7 +80,7 @@ export const CategoryService = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const SupplierService = {
|
export const SupplierService = {
|
||||||
async create(db: PostgresJsDatabase, companyId: string, input: SupplierCreateInput) {
|
async create(db: PostgresJsDatabase<any>, companyId: string, input: SupplierCreateInput) {
|
||||||
const [supplier] = await db
|
const [supplier] = await db
|
||||||
.insert(suppliers)
|
.insert(suppliers)
|
||||||
.values({ companyId, ...input })
|
.values({ companyId, ...input })
|
||||||
@@ -88,7 +88,7 @@ export const SupplierService = {
|
|||||||
return supplier
|
return supplier
|
||||||
},
|
},
|
||||||
|
|
||||||
async getById(db: PostgresJsDatabase, companyId: string, id: string) {
|
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [supplier] = await db
|
const [supplier] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(suppliers)
|
.from(suppliers)
|
||||||
@@ -97,7 +97,7 @@ export const SupplierService = {
|
|||||||
return supplier ?? null
|
return supplier ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async list(db: PostgresJsDatabase, companyId: string, params: PaginationInput) {
|
async list(db: PostgresJsDatabase<any>, companyId: string, params: PaginationInput) {
|
||||||
const baseWhere = and(eq(suppliers.companyId, companyId), eq(suppliers.isActive, true))
|
const baseWhere = and(eq(suppliers.companyId, companyId), eq(suppliers.isActive, true))
|
||||||
|
|
||||||
const searchCondition = params.q
|
const searchCondition = params.q
|
||||||
@@ -106,7 +106,7 @@ export const SupplierService = {
|
|||||||
|
|
||||||
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
||||||
|
|
||||||
const sortableColumns: Record<string, typeof suppliers.name> = {
|
const sortableColumns: Record<string, Column> = {
|
||||||
name: suppliers.name,
|
name: suppliers.name,
|
||||||
created_at: suppliers.createdAt,
|
created_at: suppliers.createdAt,
|
||||||
}
|
}
|
||||||
@@ -123,7 +123,7 @@ export const SupplierService = {
|
|||||||
return paginatedResponse(data, total, params.page, params.limit)
|
return paginatedResponse(data, total, params.page, params.limit)
|
||||||
},
|
},
|
||||||
|
|
||||||
async update(db: PostgresJsDatabase, companyId: string, id: string, input: SupplierUpdateInput) {
|
async update(db: PostgresJsDatabase<any>, companyId: string, id: string, input: SupplierUpdateInput) {
|
||||||
const [supplier] = await db
|
const [supplier] = await db
|
||||||
.update(suppliers)
|
.update(suppliers)
|
||||||
.set({ ...input, updatedAt: new Date() })
|
.set({ ...input, updatedAt: new Date() })
|
||||||
@@ -132,7 +132,7 @@ export const SupplierService = {
|
|||||||
return supplier ?? null
|
return supplier ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async softDelete(db: PostgresJsDatabase, companyId: string, id: string) {
|
async softDelete(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [supplier] = await db
|
const [supplier] = await db
|
||||||
.update(suppliers)
|
.update(suppliers)
|
||||||
.set({ isActive: false, updatedAt: new Date() })
|
.set({ isActive: false, updatedAt: new Date() })
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ function createLookupService(
|
|||||||
systemSeeds: ReadonlyArray<{ slug: string; name: string; description: string; sortOrder: number }>,
|
systemSeeds: ReadonlyArray<{ slug: string; name: string; description: string; sortOrder: number }>,
|
||||||
) {
|
) {
|
||||||
return {
|
return {
|
||||||
async seedForCompany(db: PostgresJsDatabase, companyId: string) {
|
async seedForCompany(db: PostgresJsDatabase<any>, companyId: string) {
|
||||||
const existing = await db
|
const existing = await db
|
||||||
.select()
|
.select()
|
||||||
.from(table)
|
.from(table)
|
||||||
@@ -32,7 +32,7 @@ function createLookupService(
|
|||||||
)
|
)
|
||||||
},
|
},
|
||||||
|
|
||||||
async list(db: PostgresJsDatabase, companyId: string) {
|
async list(db: PostgresJsDatabase<any>, companyId: string) {
|
||||||
return db
|
return db
|
||||||
.select()
|
.select()
|
||||||
.from(table)
|
.from(table)
|
||||||
@@ -40,7 +40,7 @@ function createLookupService(
|
|||||||
.orderBy(table.sortOrder)
|
.orderBy(table.sortOrder)
|
||||||
},
|
},
|
||||||
|
|
||||||
async getBySlug(db: PostgresJsDatabase, companyId: string, slug: string) {
|
async getBySlug(db: PostgresJsDatabase<any>, companyId: string, slug: string) {
|
||||||
const [row] = await db
|
const [row] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(table)
|
.from(table)
|
||||||
@@ -49,7 +49,7 @@ function createLookupService(
|
|||||||
return row ?? null
|
return row ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async create(db: PostgresJsDatabase, companyId: string, input: LookupCreateInput) {
|
async create(db: PostgresJsDatabase<any>, companyId: string, input: LookupCreateInput) {
|
||||||
const [row] = await db
|
const [row] = await db
|
||||||
.insert(table)
|
.insert(table)
|
||||||
.values({
|
.values({
|
||||||
@@ -64,7 +64,7 @@ function createLookupService(
|
|||||||
return row
|
return row
|
||||||
},
|
},
|
||||||
|
|
||||||
async update(db: PostgresJsDatabase, companyId: string, id: string, input: LookupUpdateInput) {
|
async update(db: PostgresJsDatabase<any>, companyId: string, id: string, input: LookupUpdateInput) {
|
||||||
// Prevent modifying system rows' slug or system flag
|
// Prevent modifying system rows' slug or system flag
|
||||||
const existing = await db
|
const existing = await db
|
||||||
.select()
|
.select()
|
||||||
@@ -85,7 +85,7 @@ function createLookupService(
|
|||||||
return row ?? null
|
return row ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async delete(db: PostgresJsDatabase, companyId: string, id: string) {
|
async delete(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const existing = await db
|
const existing = await db
|
||||||
.select()
|
.select()
|
||||||
.from(table)
|
.from(table)
|
||||||
@@ -104,7 +104,7 @@ function createLookupService(
|
|||||||
return row ?? null
|
return row ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async validateSlug(db: PostgresJsDatabase, companyId: string, slug: string): Promise<boolean> {
|
async validateSlug(db: PostgresJsDatabase<any>, companyId: string, slug: string): Promise<boolean> {
|
||||||
const row = await this.getBySlug(db, companyId, slug)
|
const row = await this.getBySlug(db, companyId, slug)
|
||||||
return row !== null && row.isActive
|
return row !== null && row.isActive
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { eq, and, count } from 'drizzle-orm'
|
import { eq, and, count, type Column } from 'drizzle-orm'
|
||||||
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
|
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
|
||||||
import { products, inventoryUnits, priceHistory } from '../db/schema/inventory.js'
|
import { products, inventoryUnits, priceHistory } from '../db/schema/inventory.js'
|
||||||
import { ValidationError } from '../lib/errors.js'
|
import { ValidationError } from '../lib/errors.js'
|
||||||
@@ -18,7 +18,7 @@ import {
|
|||||||
import { UnitStatusService, ItemConditionService } from './lookup.service.js'
|
import { UnitStatusService, ItemConditionService } from './lookup.service.js'
|
||||||
|
|
||||||
export const ProductService = {
|
export const ProductService = {
|
||||||
async create(db: PostgresJsDatabase, companyId: string, input: ProductCreateInput) {
|
async create(db: PostgresJsDatabase<any>, companyId: string, input: ProductCreateInput) {
|
||||||
const [product] = await db
|
const [product] = await db
|
||||||
.insert(products)
|
.insert(products)
|
||||||
.values({
|
.values({
|
||||||
@@ -32,7 +32,7 @@ export const ProductService = {
|
|||||||
return product
|
return product
|
||||||
},
|
},
|
||||||
|
|
||||||
async getById(db: PostgresJsDatabase, companyId: string, id: string) {
|
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [product] = await db
|
const [product] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(products)
|
.from(products)
|
||||||
@@ -41,7 +41,7 @@ export const ProductService = {
|
|||||||
return product ?? null
|
return product ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async list(db: PostgresJsDatabase, companyId: string, params: PaginationInput) {
|
async list(db: PostgresJsDatabase<any>, companyId: string, params: PaginationInput) {
|
||||||
const baseWhere = and(eq(products.companyId, companyId), eq(products.isActive, true))
|
const baseWhere = and(eq(products.companyId, companyId), eq(products.isActive, true))
|
||||||
|
|
||||||
const searchCondition = params.q
|
const searchCondition = params.q
|
||||||
@@ -50,7 +50,7 @@ export const ProductService = {
|
|||||||
|
|
||||||
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
||||||
|
|
||||||
const sortableColumns: Record<string, typeof products.name> = {
|
const sortableColumns: Record<string, Column> = {
|
||||||
name: products.name,
|
name: products.name,
|
||||||
sku: products.sku,
|
sku: products.sku,
|
||||||
brand: products.brand,
|
brand: products.brand,
|
||||||
@@ -71,7 +71,7 @@ export const ProductService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
async update(
|
async update(
|
||||||
db: PostgresJsDatabase,
|
db: PostgresJsDatabase<any>,
|
||||||
companyId: string,
|
companyId: string,
|
||||||
id: string,
|
id: string,
|
||||||
input: ProductUpdateInput,
|
input: ProductUpdateInput,
|
||||||
@@ -106,7 +106,7 @@ export const ProductService = {
|
|||||||
return product ?? null
|
return product ?? null
|
||||||
},
|
},
|
||||||
|
|
||||||
async softDelete(db: PostgresJsDatabase, companyId: string, id: string) {
|
async softDelete(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [product] = await db
|
const [product] = await db
|
||||||
.update(products)
|
.update(products)
|
||||||
.set({ isActive: false, updatedAt: new Date() })
|
.set({ isActive: false, updatedAt: new Date() })
|
||||||
@@ -117,7 +117,7 @@ export const ProductService = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const InventoryUnitService = {
|
export const InventoryUnitService = {
|
||||||
async create(db: PostgresJsDatabase, companyId: string, input: InventoryUnitCreateInput) {
|
async create(db: PostgresJsDatabase<any>, companyId: string, input: InventoryUnitCreateInput) {
|
||||||
if (input.condition) {
|
if (input.condition) {
|
||||||
const valid = await ItemConditionService.validateSlug(db, companyId, input.condition)
|
const valid = await ItemConditionService.validateSlug(db, companyId, input.condition)
|
||||||
if (!valid) throw new ValidationError(`Invalid condition: "${input.condition}"`)
|
if (!valid) throw new ValidationError(`Invalid condition: "${input.condition}"`)
|
||||||
@@ -144,7 +144,7 @@ export const InventoryUnitService = {
|
|||||||
return unit
|
return unit
|
||||||
},
|
},
|
||||||
|
|
||||||
async getById(db: PostgresJsDatabase, companyId: string, id: string) {
|
async getById(db: PostgresJsDatabase<any>, companyId: string, id: string) {
|
||||||
const [unit] = await db
|
const [unit] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(inventoryUnits)
|
.from(inventoryUnits)
|
||||||
@@ -154,7 +154,7 @@ export const InventoryUnitService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
async listByProduct(
|
async listByProduct(
|
||||||
db: PostgresJsDatabase,
|
db: PostgresJsDatabase<any>,
|
||||||
companyId: string,
|
companyId: string,
|
||||||
productId: string,
|
productId: string,
|
||||||
params: PaginationInput,
|
params: PaginationInput,
|
||||||
@@ -164,7 +164,7 @@ export const InventoryUnitService = {
|
|||||||
eq(inventoryUnits.productId, productId),
|
eq(inventoryUnits.productId, productId),
|
||||||
)
|
)
|
||||||
|
|
||||||
const sortableColumns: Record<string, typeof inventoryUnits.serialNumber> = {
|
const sortableColumns: Record<string, Column> = {
|
||||||
serial_number: inventoryUnits.serialNumber,
|
serial_number: inventoryUnits.serialNumber,
|
||||||
status: inventoryUnits.status,
|
status: inventoryUnits.status,
|
||||||
condition: inventoryUnits.condition,
|
condition: inventoryUnits.condition,
|
||||||
@@ -184,7 +184,7 @@ export const InventoryUnitService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
async update(
|
async update(
|
||||||
db: PostgresJsDatabase,
|
db: PostgresJsDatabase<any>,
|
||||||
companyId: string,
|
companyId: string,
|
||||||
id: string,
|
id: string,
|
||||||
input: InventoryUnitUpdateInput,
|
input: InventoryUnitUpdateInput,
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import { eq, and, inArray } from 'drizzle-orm'
|
import { eq, and, inArray, count, type Column } from 'drizzle-orm'
|
||||||
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
|
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
|
||||||
|
import type { PaginationInput } from '@forte/shared/schemas'
|
||||||
import { permissions, roles, rolePermissions, userRoles } from '../db/schema/rbac.js'
|
import { permissions, roles, rolePermissions, userRoles } from '../db/schema/rbac.js'
|
||||||
import { SYSTEM_PERMISSIONS, DEFAULT_ROLES } from '../db/seeds/rbac.js'
|
import { SYSTEM_PERMISSIONS, DEFAULT_ROLES } from '../db/seeds/rbac.js'
|
||||||
import { ForbiddenError } from '../lib/errors.js'
|
import { ForbiddenError } from '../lib/errors.js'
|
||||||
|
import { withPagination, withSort, buildSearchCondition, paginatedResponse } from '../utils/pagination.js'
|
||||||
|
|
||||||
export const RbacService = {
|
export const RbacService = {
|
||||||
/** Seed system permissions (global, run once) */
|
/** Seed system permissions (global, run once) */
|
||||||
async seedPermissions(db: PostgresJsDatabase) {
|
async seedPermissions(db: PostgresJsDatabase<any>) {
|
||||||
const existing = await db.select({ slug: permissions.slug }).from(permissions)
|
const existing = await db.select({ slug: permissions.slug }).from(permissions)
|
||||||
const existingSlugs = new Set(existing.map((p) => p.slug))
|
const existingSlugs = new Set(existing.map((p) => p.slug))
|
||||||
|
|
||||||
@@ -17,7 +19,7 @@ export const RbacService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/** Seed default roles for a company */
|
/** Seed default roles for a company */
|
||||||
async seedRolesForCompany(db: PostgresJsDatabase, companyId: string) {
|
async seedRolesForCompany(db: PostgresJsDatabase<any>, companyId: string) {
|
||||||
const existingRoles = await db
|
const existingRoles = await db
|
||||||
.select({ slug: roles.slug })
|
.select({ slug: roles.slug })
|
||||||
.from(roles)
|
.from(roles)
|
||||||
@@ -57,7 +59,7 @@ export const RbacService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/** Get all permissions for a user (union of all role permissions) */
|
/** Get all permissions for a user (union of all role permissions) */
|
||||||
async getUserPermissions(db: PostgresJsDatabase, userId: string): Promise<string[]> {
|
async getUserPermissions(db: PostgresJsDatabase<any>, userId: string): Promise<string[]> {
|
||||||
const userRoleRecords = await db
|
const userRoleRecords = await db
|
||||||
.select({ roleId: userRoles.roleId })
|
.select({ roleId: userRoles.roleId })
|
||||||
.from(userRoles)
|
.from(userRoles)
|
||||||
@@ -85,21 +87,40 @@ export const RbacService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/** List all permissions */
|
/** List all permissions */
|
||||||
async listPermissions(db: PostgresJsDatabase) {
|
async listPermissions(db: PostgresJsDatabase<any>) {
|
||||||
return db.select().from(permissions).orderBy(permissions.domain, permissions.action)
|
return db.select().from(permissions).orderBy(permissions.domain, permissions.action)
|
||||||
},
|
},
|
||||||
|
|
||||||
/** List roles for a company */
|
/** List roles for a company */
|
||||||
async listRoles(db: PostgresJsDatabase, companyId: string) {
|
async listRoles(db: PostgresJsDatabase<any>, companyId: string, params: PaginationInput) {
|
||||||
return db
|
const baseWhere = and(eq(roles.companyId, companyId), eq(roles.isActive, true))
|
||||||
.select()
|
|
||||||
.from(roles)
|
const searchCondition = params.q
|
||||||
.where(and(eq(roles.companyId, companyId), eq(roles.isActive, true)))
|
? buildSearchCondition(params.q, [roles.name, roles.slug])
|
||||||
.orderBy(roles.name)
|
: undefined
|
||||||
|
|
||||||
|
const where = searchCondition ? and(baseWhere, searchCondition) : baseWhere
|
||||||
|
|
||||||
|
const sortableColumns: Record<string, Column> = {
|
||||||
|
name: roles.name,
|
||||||
|
slug: roles.slug,
|
||||||
|
created_at: roles.createdAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
let query = db.select().from(roles).where(where).$dynamic()
|
||||||
|
query = withSort(query, params.sort, params.order, sortableColumns, roles.name)
|
||||||
|
query = withPagination(query, params.page, params.limit)
|
||||||
|
|
||||||
|
const [data, [{ total }]] = await Promise.all([
|
||||||
|
query,
|
||||||
|
db.select({ total: count() }).from(roles).where(where),
|
||||||
|
])
|
||||||
|
|
||||||
|
return paginatedResponse(data, total, params.page, params.limit)
|
||||||
},
|
},
|
||||||
|
|
||||||
/** Get role with its permissions */
|
/** Get role with its permissions */
|
||||||
async getRoleWithPermissions(db: PostgresJsDatabase, companyId: string, roleId: string) {
|
async getRoleWithPermissions(db: PostgresJsDatabase<any>, companyId: string, roleId: string) {
|
||||||
const [role] = await db
|
const [role] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(roles)
|
.from(roles)
|
||||||
@@ -119,7 +140,7 @@ export const RbacService = {
|
|||||||
|
|
||||||
/** Create a custom role */
|
/** Create a custom role */
|
||||||
async createRole(
|
async createRole(
|
||||||
db: PostgresJsDatabase,
|
db: PostgresJsDatabase<any>,
|
||||||
companyId: string,
|
companyId: string,
|
||||||
input: { name: string; slug: string; description?: string; permissionSlugs: string[] },
|
input: { name: string; slug: string; description?: string; permissionSlugs: string[] },
|
||||||
) {
|
) {
|
||||||
@@ -139,7 +160,7 @@ export const RbacService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/** Update role permissions (replace all) */
|
/** Update role permissions (replace all) */
|
||||||
async setRolePermissions(db: PostgresJsDatabase, roleId: string, permissionSlugs: string[]) {
|
async setRolePermissions(db: PostgresJsDatabase<any>, roleId: string, permissionSlugs: string[]) {
|
||||||
// Delete existing
|
// Delete existing
|
||||||
await db.delete(rolePermissions).where(eq(rolePermissions.roleId, roleId))
|
await db.delete(rolePermissions).where(eq(rolePermissions.roleId, roleId))
|
||||||
|
|
||||||
@@ -160,7 +181,7 @@ export const RbacService = {
|
|||||||
|
|
||||||
/** Update a role */
|
/** Update a role */
|
||||||
async updateRole(
|
async updateRole(
|
||||||
db: PostgresJsDatabase,
|
db: PostgresJsDatabase<any>,
|
||||||
companyId: string,
|
companyId: string,
|
||||||
roleId: string,
|
roleId: string,
|
||||||
input: { name?: string; description?: string; permissionSlugs?: string[] },
|
input: { name?: string; description?: string; permissionSlugs?: string[] },
|
||||||
@@ -184,7 +205,7 @@ export const RbacService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/** Delete a custom role */
|
/** Delete a custom role */
|
||||||
async deleteRole(db: PostgresJsDatabase, companyId: string, roleId: string) {
|
async deleteRole(db: PostgresJsDatabase<any>, companyId: string, roleId: string) {
|
||||||
const [role] = await db
|
const [role] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(roles)
|
.from(roles)
|
||||||
@@ -207,7 +228,7 @@ export const RbacService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/** Assign a role to a user */
|
/** Assign a role to a user */
|
||||||
async assignRole(db: PostgresJsDatabase, userId: string, roleId: string, assignedBy?: string) {
|
async assignRole(db: PostgresJsDatabase<any>, userId: string, roleId: string, assignedBy?: string) {
|
||||||
const [existing] = await db
|
const [existing] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(userRoles)
|
.from(userRoles)
|
||||||
@@ -225,7 +246,7 @@ export const RbacService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/** Remove a role from a user */
|
/** Remove a role from a user */
|
||||||
async removeRole(db: PostgresJsDatabase, userId: string, roleId: string) {
|
async removeRole(db: PostgresJsDatabase<any>, userId: string, roleId: string) {
|
||||||
const [removed] = await db
|
const [removed] = await db
|
||||||
.delete(userRoles)
|
.delete(userRoles)
|
||||||
.where(and(eq(userRoles.userId, userId), eq(userRoles.roleId, roleId)))
|
.where(and(eq(userRoles.userId, userId), eq(userRoles.roleId, roleId)))
|
||||||
@@ -235,7 +256,7 @@ export const RbacService = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/** Get roles assigned to a user */
|
/** Get roles assigned to a user */
|
||||||
async getUserRoles(db: PostgresJsDatabase, userId: string) {
|
async getUserRoles(db: PostgresJsDatabase<any>, userId: string) {
|
||||||
return db
|
return db
|
||||||
.select({
|
.select({
|
||||||
id: roles.id,
|
id: roles.id,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { z } from 'zod'
|
|||||||
|
|
||||||
/** Coerce empty strings to undefined — solves HTML form inputs sending '' for blank optional fields */
|
/** Coerce empty strings to undefined — solves HTML form inputs sending '' for blank optional fields */
|
||||||
function opt<T extends z.ZodTypeAny>(schema: T) {
|
function opt<T extends z.ZodTypeAny>(schema: T) {
|
||||||
return z.preprocess((v) => (v === '' ? undefined : v), schema.optional()) as z.ZodEffects<z.ZodOptional<T>>
|
return z.preprocess((v) => (v === '' ? undefined : v), schema.optional())
|
||||||
}
|
}
|
||||||
|
|
||||||
export const BillingMode = z.enum(['consolidated', 'split'])
|
export const BillingMode = z.enum(['consolidated', 'split'])
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { z } from 'zod'
|
|||||||
|
|
||||||
/** Coerce empty strings to undefined — solves HTML form inputs sending '' for blank optional fields */
|
/** Coerce empty strings to undefined — solves HTML form inputs sending '' for blank optional fields */
|
||||||
function opt<T extends z.ZodTypeAny>(schema: T) {
|
function opt<T extends z.ZodTypeAny>(schema: T) {
|
||||||
return z.preprocess((v) => (v === '' ? undefined : v), schema.optional()) as z.ZodEffects<z.ZodOptional<T>>
|
return z.preprocess((v) => (v === '' ? undefined : v), schema.optional())
|
||||||
}
|
}
|
||||||
|
|
||||||
export const CategoryCreateSchema = z.object({
|
export const CategoryCreateSchema = z.object({
|
||||||
|
|||||||
Reference in New Issue
Block a user