Merge pull request 'amalia/22-mei-26' (#25) from amalia/22-mei-26 into main
Reviewed-on: #25
This commit is contained in:
30
CLAUDE.md
30
CLAUDE.md
@@ -13,31 +13,9 @@ Default to Bun instead of Node.js everywhere:
|
|||||||
- `bunx <pkg>` not `npx`
|
- `bunx <pkg>` not `npx`
|
||||||
- Bun auto-loads `.env` — never use dotenv.
|
- Bun auto-loads `.env` — never use dotenv.
|
||||||
|
|
||||||
## Common Commands
|
## Commands
|
||||||
|
|
||||||
```bash
|
See @docs/COMMANDS.md
|
||||||
bun run dev # dev server with hot reload (bun --watch src/serve.ts)
|
|
||||||
bun run build # Vite production build
|
|
||||||
bun run start # production server (NODE_ENV=production)
|
|
||||||
bun run typecheck # tsc --noEmit
|
|
||||||
bun run lint # biome check src/
|
|
||||||
bun run lint:fix # biome check --write src/
|
|
||||||
|
|
||||||
# Database
|
|
||||||
bun run db:migrate # prisma migrate dev
|
|
||||||
bun run db:seed # seed demo data
|
|
||||||
bun run db:generate # regenerate prisma client
|
|
||||||
bun run db:studio # Prisma Studio GUI
|
|
||||||
bun run db:push # push schema without migration
|
|
||||||
|
|
||||||
# Tests
|
|
||||||
bun run test # all tests
|
|
||||||
bun run test:unit # tests/unit/
|
|
||||||
bun run test:integration # tests/integration/ — no server needed
|
|
||||||
bun run test:e2e # tests/e2e/ — requires Lightpanda Docker
|
|
||||||
```
|
|
||||||
|
|
||||||
Run a single test file: `bun test tests/integration/auth.test.ts`
|
|
||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
@@ -50,3 +28,7 @@ See @docs/TESTING.md
|
|||||||
## Dev Tools
|
## Dev Tools
|
||||||
|
|
||||||
See @docs/DEV_TOOLS.md
|
See @docs/DEV_TOOLS.md
|
||||||
|
|
||||||
|
## Frontend Conventions
|
||||||
|
|
||||||
|
See @docs/CONVENTIONS.md
|
||||||
|
|||||||
25
docs/COMMANDS.md
Normal file
25
docs/COMMANDS.md
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
# Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bun run dev # dev server with hot reload (bun --watch src/serve.ts)
|
||||||
|
bun run build # Vite production build
|
||||||
|
bun run start # production server (NODE_ENV=production)
|
||||||
|
bun run typecheck # tsc --noEmit
|
||||||
|
bun run lint # biome check src/
|
||||||
|
bun run lint:fix # biome check --write src/
|
||||||
|
|
||||||
|
# Database
|
||||||
|
bun run db:migrate # prisma migrate dev
|
||||||
|
bun run db:seed # seed demo data
|
||||||
|
bun run db:generate # regenerate prisma client
|
||||||
|
bun run db:studio # Prisma Studio GUI
|
||||||
|
bun run db:push # push schema without migration
|
||||||
|
|
||||||
|
# Tests
|
||||||
|
bun run test # all tests
|
||||||
|
bun run test:unit # tests/unit/
|
||||||
|
bun run test:integration # tests/integration/ — no server needed
|
||||||
|
bun run test:e2e # tests/e2e/ — requires Lightpanda Docker
|
||||||
|
```
|
||||||
|
|
||||||
|
Run a single test file: `bun test tests/integration/auth.test.ts`
|
||||||
66
docs/CONVENTIONS.md
Normal file
66
docs/CONVENTIONS.md
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
# Frontend Conventions
|
||||||
|
|
||||||
|
## Data Fetching
|
||||||
|
|
||||||
|
- **SWR** for read-only data in route components (tables, lists, charts).
|
||||||
|
- **TanStack Query** (`useQuery`, `useMutation`) for auth state — see `src/frontend/hooks/useAuth.ts`.
|
||||||
|
- Never mix both in the same component/page.
|
||||||
|
- Debounce search inputs: `useDebouncedValue(search, 400)` + `useEffect` that only triggers when length >= 3 or === 0.
|
||||||
|
|
||||||
|
## API URL Builder
|
||||||
|
|
||||||
|
All URLs go through `src/frontend/config/api.ts` → `API_URLS`. Add new entries there, never inline URLs in components.
|
||||||
|
|
||||||
|
Desa+ endpoints are proxied via `/api/proxy/desa-plus` → `DESA_PLUS_PROXY` constant. The actual API source is at:
|
||||||
|
`/Users/wibu04/Documents/Projects/sistem-desa-mandiri/src/app/api/monitoring/[[...slug]]/route.ts`
|
||||||
|
|
||||||
|
## Filters & Pagination Pattern
|
||||||
|
|
||||||
|
Server-side filtering — always pass filter params to the API, never filter client-side on paginated data.
|
||||||
|
|
||||||
|
State pattern for a filtered table page:
|
||||||
|
```ts
|
||||||
|
const [page, setPage] = useState(1)
|
||||||
|
const [search, setSearch] = useState('') // raw input
|
||||||
|
const [searchQuery, setSearchQuery] = useState('') // debounced, sent to API
|
||||||
|
const [debouncedSearch] = useDebouncedValue(search, 400)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (debouncedSearch.length >= 3 || debouncedSearch.length === 0) {
|
||||||
|
setSearchQuery(debouncedSearch)
|
||||||
|
setPage(1)
|
||||||
|
}
|
||||||
|
}, [debouncedSearch])
|
||||||
|
|
||||||
|
useEffect(() => { setPage(1) }, [filterA, filterB]) // reset page on filter change
|
||||||
|
```
|
||||||
|
|
||||||
|
## Mantine Components
|
||||||
|
|
||||||
|
- Dark theme forced (`#242424`). Never add light-mode conditionals.
|
||||||
|
- `radius="md"` on inputs, `radius="2xl"` on container `Paper`.
|
||||||
|
- `className="glass"` on `Paper` cards for the frosted glass effect.
|
||||||
|
- `size="sm"` on table inputs and selects.
|
||||||
|
- Icons from `react-icons/tb` only — no other icon libraries.
|
||||||
|
- `DatePickerInput` from `@mantine/dates` with `type="range"` returns `[string | null, string | null]`, not Date objects.
|
||||||
|
|
||||||
|
## Route Files
|
||||||
|
|
||||||
|
File-based routing via TanStack Router Vite plugin. Files in `src/frontend/routes/`:
|
||||||
|
|
||||||
|
| Pattern | Route |
|
||||||
|
|---|---|
|
||||||
|
| `apps.$appId.tsx` | Layout wrapper for per-app pages |
|
||||||
|
| `apps.$appId.index.tsx` | Overview/dashboard for an app |
|
||||||
|
| `apps.$appId.users.index.tsx` | User management |
|
||||||
|
| `apps.$appId.logs.tsx` | Activity logs |
|
||||||
|
| `apps.$appId.villages.tsx` | Villages layout |
|
||||||
|
| `apps.$appId.villages.index.tsx` | Village list |
|
||||||
|
| `apps.$appId.villages.$villageId.tsx` | Village detail |
|
||||||
|
|
||||||
|
`routeTree.gen.ts` is auto-generated — never edit it manually.
|
||||||
|
|
||||||
|
## App Registration
|
||||||
|
|
||||||
|
App configs (ID, menu items) live in `src/frontend/config/appMenus.ts`. Add new apps there to register them.
|
||||||
|
Currently active app: `desa-plus`.
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "bun-react-template",
|
"name": "bun-react-template",
|
||||||
"version": "0.1.12",
|
"version": "0.1.15",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ async function triggerWorkflow(workflow: string, inputs: Record<string, string>)
|
|||||||
const res = await fetch(`${BASE_URL}/actions/workflows/${workflow}/dispatches`, {
|
const res = await fetch(`${BASE_URL}/actions/workflows/${workflow}/dispatches`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: ghHeaders,
|
headers: ghHeaders,
|
||||||
body: JSON.stringify({ ref: 'main', inputs }),
|
body: JSON.stringify({ ref: 'stg', inputs }),
|
||||||
})
|
})
|
||||||
if (!res.ok) throw new Error(`GitHub API error ${res.status}: ${await res.text()}`)
|
if (!res.ok) throw new Error(`GitHub API error ${res.status}: ${await res.text()}`)
|
||||||
}
|
}
|
||||||
@@ -150,7 +150,7 @@ server.tool(
|
|||||||
}
|
}
|
||||||
log.push('✅ Committed')
|
log.push('✅ Committed')
|
||||||
|
|
||||||
const push = await sh(['git', 'push', 'origin', 'HEAD:build/stg'])
|
const push = await sh(['git', 'push', 'build', 'HEAD:stg'])
|
||||||
if (!push.ok) {
|
if (!push.ok) {
|
||||||
return { content: [{ type: 'text', text: `❌ git push gagal:\n${push.err}` }] }
|
return { content: [{ type: 'text', text: `❌ git push gagal:\n${push.err}` }] }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -370,6 +370,8 @@ export function createApp() {
|
|||||||
errors: app.bugs.length,
|
errors: app.bugs.length,
|
||||||
active: app.active,
|
active: app.active,
|
||||||
urlApi: app.urlApi,
|
urlApi: app.urlApi,
|
||||||
|
apiKey: app.apiKey ?? '',
|
||||||
|
clientApiKey: app.clientApiKey ?? '',
|
||||||
hasClientApiKey: !!app.clientApiKey,
|
hasClientApiKey: !!app.clientApiKey,
|
||||||
}))
|
}))
|
||||||
}, {
|
}, {
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { BarChart, LineChart } from '@mantine/charts'
|
import { AreaChart, BarChart } from '@mantine/charts'
|
||||||
import {
|
import {
|
||||||
Badge,
|
Badge,
|
||||||
Box,
|
Box,
|
||||||
|
Button,
|
||||||
Group,
|
Group,
|
||||||
Paper,
|
Paper,
|
||||||
Stack,
|
Stack,
|
||||||
@@ -11,14 +12,29 @@ import {
|
|||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { TbArrowUpRight, TbChartBar, TbTimeline } from 'react-icons/tb'
|
import { TbArrowUpRight, TbChartBar, TbTimeline } from 'react-icons/tb'
|
||||||
|
|
||||||
|
type DailyRange = 7 | 30 | 90
|
||||||
|
|
||||||
interface ChartProps {
|
interface ChartProps {
|
||||||
data?: any[]
|
data?: any[]
|
||||||
isLoading?: boolean
|
isLoading?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export function VillageActivityLineChart({ data = [], isLoading }: ChartProps) {
|
interface ActivityChartProps extends ChartProps {
|
||||||
|
range?: DailyRange
|
||||||
|
onRangeChange?: (range: DailyRange) => void
|
||||||
|
}
|
||||||
|
|
||||||
|
const RANGE_OPTIONS: { value: DailyRange; label: string }[] = [
|
||||||
|
{ value: 7, label: '7D' },
|
||||||
|
{ value: 30, label: '30D' },
|
||||||
|
{ value: 90, label: '3M' },
|
||||||
|
]
|
||||||
|
|
||||||
|
export function VillageActivityLineChart({ data = [], isLoading, range = 7, onRangeChange }: ActivityChartProps) {
|
||||||
const theme = useMantineTheme()
|
const theme = useMantineTheme()
|
||||||
|
|
||||||
|
const rangeLabel = range === 7 ? 'last 7 days' : range === 30 ? 'last 30 days' : 'last 3 months'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Paper withBorder p="xl" radius="2xl" className="glass h-full">
|
<Paper withBorder p="xl" radius="2xl" className="glass h-full">
|
||||||
<Stack gap="md" h="100%">
|
<Stack gap="md" h="100%">
|
||||||
@@ -29,21 +45,28 @@ export function VillageActivityLineChart({ data = [], isLoading }: ChartProps) {
|
|||||||
</ThemeIcon>
|
</ThemeIcon>
|
||||||
<Box>
|
<Box>
|
||||||
<Text fw={700} size="sm">DAILY ACTIVITY - ALL VILLAGES</Text>
|
<Text fw={700} size="sm">DAILY ACTIVITY - ALL VILLAGES</Text>
|
||||||
<Text size="xs" c="dimmed">Trend over the last 7 days</Text>
|
<Text size="xs" c="dimmed">Trend over the {rangeLabel}</Text>
|
||||||
</Box>
|
</Box>
|
||||||
</Group>
|
</Group>
|
||||||
{
|
<Group gap={4}>
|
||||||
isLoading && (
|
{RANGE_OPTIONS.map((opt) => (
|
||||||
<Badge variant="light" color="blue" size="sm" rightSection={<TbArrowUpRight size={12} />}>
|
<Button
|
||||||
...
|
key={opt.value}
|
||||||
</Badge>
|
size="compact-xs"
|
||||||
)
|
variant={range === opt.value ? 'filled' : 'subtle'}
|
||||||
}
|
color="blue"
|
||||||
|
radius="md"
|
||||||
|
onClick={() => onRangeChange?.(opt.value)}
|
||||||
|
loading={isLoading && range === opt.value}
|
||||||
|
>
|
||||||
|
{opt.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<Box h={300} mt="lg">
|
<Box h={300} mt="lg">
|
||||||
<LineChart
|
<AreaChart
|
||||||
h={300}
|
h={300}
|
||||||
data={data}
|
data={data}
|
||||||
dataKey="date"
|
dataKey="date"
|
||||||
@@ -53,12 +76,33 @@ export function VillageActivityLineChart({ data = [], isLoading }: ChartProps) {
|
|||||||
gridAxis="x"
|
gridAxis="x"
|
||||||
withTooltip
|
withTooltip
|
||||||
tooltipAnimationDuration={200}
|
tooltipAnimationDuration={200}
|
||||||
|
fillOpacity={0.4}
|
||||||
tooltipProps={{
|
tooltipProps={{
|
||||||
allowEscapeViewBox: { x: true, y: false },
|
content: ({ active, payload, label }: any) => {
|
||||||
|
if (!active || !payload?.length) return null
|
||||||
|
return (
|
||||||
|
<div style={{
|
||||||
|
backgroundColor: '#1A1B1E',
|
||||||
|
padding: '8px 12px',
|
||||||
|
borderRadius: '6px',
|
||||||
|
border: '1px solid #373A40',
|
||||||
|
boxShadow: '0 4px 12px rgba(0,0,0,0.5)',
|
||||||
|
pointerEvents: 'none',
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
|
}}>
|
||||||
|
<div style={{ fontSize: '12px', fontWeight: 600, color: '#C1C2C5', marginBottom: '4px' }}>
|
||||||
|
{label}
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: '11px', color: '#2563EB' }}>
|
||||||
|
Activity: <span style={{ fontWeight: 700 }}>{payload[0].value}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
styles={{
|
styles={{
|
||||||
root: {
|
root: {
|
||||||
'.recharts-line-curve': {
|
'.recharts-area-curve': {
|
||||||
strokeWidth: 3,
|
strokeWidth: 3,
|
||||||
filter: 'drop-shadow(0 4px 8px rgba(37, 99, 235, 0.3))'
|
filter: 'drop-shadow(0 4px 8px rgba(37, 99, 235, 0.3))'
|
||||||
}
|
}
|
||||||
@@ -71,9 +115,11 @@ export function VillageActivityLineChart({ data = [], isLoading }: ChartProps) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function VillageComparisonBarChart({ data = [], isLoading }: ChartProps) {
|
export function VillageComparisonBarChart({ data = [], isLoading, range = 7, onRangeChange }: ActivityChartProps) {
|
||||||
const theme = useMantineTheme()
|
const theme = useMantineTheme()
|
||||||
|
|
||||||
|
const rangeLabel = range === 7 ? 'last 7 days' : range === 30 ? 'last 30 days' : 'last 3 months'
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Paper withBorder p="xl" radius="2xl" className="glass h-full">
|
<Paper withBorder p="xl" radius="2xl" className="glass h-full">
|
||||||
<Stack gap="md" h="100%">
|
<Stack gap="md" h="100%">
|
||||||
@@ -84,9 +130,24 @@ export function VillageComparisonBarChart({ data = [], isLoading }: ChartProps)
|
|||||||
</ThemeIcon>
|
</ThemeIcon>
|
||||||
<Box>
|
<Box>
|
||||||
<Text fw={700} size="sm">USAGE COMPARISON BETWEEN VILLAGES</Text>
|
<Text fw={700} size="sm">USAGE COMPARISON BETWEEN VILLAGES</Text>
|
||||||
<Text size="xs" c="dimmed">Most active village deployments</Text>
|
<Text size="xs" c="dimmed">Most active village deployments — {rangeLabel}</Text>
|
||||||
</Box>
|
</Box>
|
||||||
</Group>
|
</Group>
|
||||||
|
<Group gap={4}>
|
||||||
|
{RANGE_OPTIONS.map((opt) => (
|
||||||
|
<Button
|
||||||
|
key={opt.value}
|
||||||
|
size="compact-xs"
|
||||||
|
variant={range === opt.value ? 'filled' : 'subtle'}
|
||||||
|
color="violet"
|
||||||
|
radius="md"
|
||||||
|
onClick={() => onRangeChange?.(opt.value)}
|
||||||
|
loading={isLoading && range === opt.value}
|
||||||
|
>
|
||||||
|
{opt.label}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<Box h={300} mt="lg">
|
<Box h={300} mt="lg">
|
||||||
|
|||||||
@@ -18,11 +18,15 @@ import {
|
|||||||
Tooltip,
|
Tooltip,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { useDisclosure } from '@mantine/hooks'
|
import { useDisclosure } from '@mantine/hooks'
|
||||||
import { useQuery } from '@tanstack/react-query'
|
|
||||||
import { Link } from '@tanstack/react-router'
|
import { Link } from '@tanstack/react-router'
|
||||||
import dayjs from 'dayjs'
|
import dayjs from 'dayjs'
|
||||||
import { useState } from 'react'
|
import { forwardRef, useImperativeHandle, useState } from 'react'
|
||||||
import { TbBug, TbExternalLink, TbHistory, TbMessageReport } from 'react-icons/tb'
|
import { TbBug, TbExternalLink, TbHistory, TbMessageReport } from 'react-icons/tb'
|
||||||
|
import useSWR from 'swr'
|
||||||
|
|
||||||
|
export interface ErrorDataTableHandle {
|
||||||
|
refresh: () => void
|
||||||
|
}
|
||||||
|
|
||||||
export interface ErrorDataTableProps {
|
export interface ErrorDataTableProps {
|
||||||
appId?: string
|
appId?: string
|
||||||
@@ -45,15 +49,20 @@ const STATUS_LABEL: Record<string, string> = {
|
|||||||
CLOSED: 'Closed',
|
CLOSED: 'Closed',
|
||||||
}
|
}
|
||||||
|
|
||||||
export function ErrorDataTable({ appId }: ErrorDataTableProps) {
|
const fetcher = (url: string) => fetch(url).then((r) => r.json())
|
||||||
|
|
||||||
|
export const ErrorDataTable = forwardRef<ErrorDataTableHandle, ErrorDataTableProps>(
|
||||||
|
function ErrorDataTable({ appId }, ref) {
|
||||||
const [opened, { open, close }] = useDisclosure(false)
|
const [opened, { open, close }] = useDisclosure(false)
|
||||||
const [selectedError, setSelectedError] = useState<any>(null)
|
const [selectedError, setSelectedError] = useState<any>(null)
|
||||||
const [showStackTrace, setShowStackTrace] = useState(false)
|
const [showStackTrace, setShowStackTrace] = useState(false)
|
||||||
|
|
||||||
const { data: bugsData, isLoading } = useQuery({
|
const { data: bugsData, isLoading, mutate } = useSWR(
|
||||||
queryKey: ['bugs', appId],
|
`/api/bugs?app=${appId || 'all'}&limit=10`,
|
||||||
queryFn: () => fetch(`/api/bugs?app=${appId || 'all'}&limit=10`).then((r) => r.json()),
|
fetcher
|
||||||
})
|
)
|
||||||
|
|
||||||
|
useImperativeHandle(ref, () => ({ refresh: mutate }))
|
||||||
|
|
||||||
const bugs = bugsData?.data || []
|
const bugs = bugsData?.data || []
|
||||||
|
|
||||||
@@ -257,4 +266,4 @@ export function ErrorDataTable({ appId }: ErrorDataTableProps) {
|
|||||||
</Drawer>
|
</Drawer>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
}
|
})
|
||||||
|
|||||||
@@ -9,13 +9,26 @@ export const API_URLS = {
|
|||||||
`${DESA_PLUS_PROXY}/api/monitoring/grid-villages?id=${id}`,
|
`${DESA_PLUS_PROXY}/api/monitoring/grid-villages?id=${id}`,
|
||||||
graphLogVillages: (id: string, time: string) =>
|
graphLogVillages: (id: string, time: string) =>
|
||||||
`${DESA_PLUS_PROXY}/api/monitoring/graph-log-villages?id=${id}&time=${time}`,
|
`${DESA_PLUS_PROXY}/api/monitoring/graph-log-villages?id=${id}&time=${time}`,
|
||||||
getUsers: (page: number, search: string) =>
|
getUsers: (page: number, search: string, isActive?: string, idUserRole?: string, idVillage?: string, orderBy?: string, orderDir?: string) => {
|
||||||
`${DESA_PLUS_PROXY}/api/monitoring/user?page=${page}&search=${encodeURIComponent(search)}`,
|
const params = new URLSearchParams({ page: String(page), search })
|
||||||
getLogsAllVillages: (page: number, search: string) =>
|
if (isActive !== undefined) params.set('isActive', isActive)
|
||||||
`${DESA_PLUS_PROXY}/api/monitoring/log-all-villages?page=${page}&search=${encodeURIComponent(search)}`,
|
if (idUserRole) params.set('idUserRole', idUserRole)
|
||||||
|
if (idVillage) params.set('idVillage', idVillage)
|
||||||
|
if (orderBy) params.set('orderBy', orderBy)
|
||||||
|
if (orderDir) params.set('orderDir', orderDir)
|
||||||
|
return `${DESA_PLUS_PROXY}/api/monitoring/user?${params}`
|
||||||
|
},
|
||||||
|
getLogsAllVillages: (page: number, search: string, action?: string, idVillage?: string, dateFrom?: string, dateTo?: string) => {
|
||||||
|
const params = new URLSearchParams({ page: String(page), search })
|
||||||
|
if (action) params.set('action', action)
|
||||||
|
if (idVillage) params.set('idVillage', idVillage)
|
||||||
|
if (dateFrom) params.set('dateFrom', dateFrom)
|
||||||
|
if (dateTo) params.set('dateTo', dateTo)
|
||||||
|
return `${DESA_PLUS_PROXY}/api/monitoring/log-all-villages?${params}`
|
||||||
|
},
|
||||||
getGridOverview: () => `${DESA_PLUS_PROXY}/api/monitoring/grid-overview`,
|
getGridOverview: () => `${DESA_PLUS_PROXY}/api/monitoring/grid-overview`,
|
||||||
getDailyActivity: () => `${DESA_PLUS_PROXY}/api/monitoring/daily-activity`,
|
getDailyActivity: (range: 7 | 30 | 90 = 7) => `${DESA_PLUS_PROXY}/api/monitoring/daily-activity?range=${range}`,
|
||||||
getComparisonActivity: () => `${DESA_PLUS_PROXY}/api/monitoring/comparison-activity`,
|
getComparisonActivity: (range: 7 | 30 | 90 = 7) => `${DESA_PLUS_PROXY}/api/monitoring/comparison-activity?range=${range}`,
|
||||||
postVersionUpdate: () => `${DESA_PLUS_PROXY}/api/monitoring/version-update`,
|
postVersionUpdate: () => `${DESA_PLUS_PROXY}/api/monitoring/version-update`,
|
||||||
createVillages: () => `${DESA_PLUS_PROXY}/api/monitoring/create-villages`,
|
createVillages: () => `${DESA_PLUS_PROXY}/api/monitoring/create-villages`,
|
||||||
createUser: () => `${DESA_PLUS_PROXY}/api/monitoring/create-user`,
|
createUser: () => `${DESA_PLUS_PROXY}/api/monitoring/create-user`,
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { useQuery } from '@tanstack/react-query'
|
|
||||||
import { VillageActivityLineChart, VillageComparisonBarChart } from '@/frontend/components/DashboardCharts'
|
import { VillageActivityLineChart, VillageComparisonBarChart } from '@/frontend/components/DashboardCharts'
|
||||||
import { ErrorDataTable } from '@/frontend/components/ErrorDataTable'
|
import { ErrorDataTable, type ErrorDataTableHandle } from '@/frontend/components/ErrorDataTable'
|
||||||
import { SummaryCard } from '@/frontend/components/SummaryCard'
|
import { SummaryCard } from '@/frontend/components/SummaryCard'
|
||||||
import { useSession } from '@/frontend/hooks/useAuth'
|
import { useSession } from '@/frontend/hooks/useAuth'
|
||||||
import {
|
import {
|
||||||
@@ -21,7 +20,7 @@ import {
|
|||||||
import { useDisclosure } from '@mantine/hooks'
|
import { useDisclosure } from '@mantine/hooks'
|
||||||
import { notifications } from '@mantine/notifications'
|
import { notifications } from '@mantine/notifications'
|
||||||
import { createFileRoute, useNavigate, useParams } from '@tanstack/react-router'
|
import { createFileRoute, useNavigate, useParams } from '@tanstack/react-router'
|
||||||
import { useEffect, useState } from 'react'
|
import { useEffect, useRef, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
TbActivity,
|
TbActivity,
|
||||||
TbAlertTriangle,
|
TbAlertTriangle,
|
||||||
@@ -45,6 +44,7 @@ function AppOverviewPage() {
|
|||||||
const [versionModalOpened, { open: openVersionModal, close: closeVersionModal }] = useDisclosure(false)
|
const [versionModalOpened, { open: openVersionModal, close: closeVersionModal }] = useDisclosure(false)
|
||||||
const { data: session } = useSession()
|
const { data: session } = useSession()
|
||||||
const isDeveloper = session?.user?.role === 'DEVELOPER'
|
const isDeveloper = session?.user?.role === 'DEVELOPER'
|
||||||
|
const errorTableRef = useRef<ErrorDataTableHandle>(null)
|
||||||
|
|
||||||
const [latestVersion, setLatestVersion] = useState('')
|
const [latestVersion, setLatestVersion] = useState('')
|
||||||
const [minVersion, setMinVersion] = useState('')
|
const [minVersion, setMinVersion] = useState('')
|
||||||
@@ -52,32 +52,38 @@ function AppOverviewPage() {
|
|||||||
const [maintenance, setMaintenance] = useState(false)
|
const [maintenance, setMaintenance] = useState(false)
|
||||||
const [isSaving, setIsSaving] = useState(false)
|
const [isSaving, setIsSaving] = useState(false)
|
||||||
|
|
||||||
const { data: gridRes, isLoading: gridLoading, mutate: mutateGrid } = useSWR(isDesaPlus ? API_URLS.getGridOverview() : null, fetcher)
|
const [dailyRange, setDailyRange] = useState<7 | 30 | 90>(7)
|
||||||
const { data: dailyRes, isLoading: dailyLoading, mutate: mutateDaily } = useSWR(isDesaPlus ? API_URLS.getDailyActivity() : null, fetcher)
|
const [comparisonRange, setComparisonRange] = useState<7 | 30 | 90>(7)
|
||||||
const { data: comparisonRes, isLoading: comparisonLoading, mutate: mutateComparison } = useSWR(isDesaPlus ? API_URLS.getComparisonActivity() : null, fetcher)
|
|
||||||
|
|
||||||
const { data: appData, isLoading: appLoading } = useQuery({
|
const { data: gridRes, isLoading: gridLoading, mutate: mutateGrid } = useSWR(isDesaPlus ? API_URLS.getGridOverview() : null, fetcher)
|
||||||
queryKey: ['apps', appId],
|
const { data: dailyRes, isLoading: dailyLoading, mutate: mutateDaily } = useSWR(isDesaPlus ? API_URLS.getDailyActivity(dailyRange) : null, fetcher)
|
||||||
queryFn: () => fetch(`/api/apps/${appId}`).then((r) => r.json()),
|
const { data: comparisonRes, isLoading: comparisonLoading, mutate: mutateComparison } = useSWR(isDesaPlus ? API_URLS.getComparisonActivity(comparisonRange) : null, fetcher)
|
||||||
})
|
|
||||||
|
const { data: appData, isLoading: appLoading } = useSWR(`/api/apps/${appId}`, fetcher)
|
||||||
|
|
||||||
const grid = gridRes?.data
|
const grid = gridRes?.data
|
||||||
const dailyData = dailyRes?.data || []
|
const dailyData = dailyRes?.data || []
|
||||||
const comparisonData = comparisonRes?.data || []
|
const comparisonData = comparisonRes?.data || []
|
||||||
|
|
||||||
|
// Ref so the modal-sync effect always reads current grid without re-running on every background refetch
|
||||||
|
const gridRef = useRef(grid)
|
||||||
|
gridRef.current = grid
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (grid?.version && versionModalOpened) {
|
if (versionModalOpened && gridRef.current?.version) {
|
||||||
setLatestVersion(grid.version.mobile_latest_version || '')
|
const v = gridRef.current.version
|
||||||
setMinVersion(grid.version.mobile_minimum_version || '')
|
setLatestVersion(v.mobile_latest_version || '')
|
||||||
setMessageUpdate(grid.version.mobile_message_update || '')
|
setMinVersion(v.mobile_minimum_version || '')
|
||||||
setMaintenance(grid.version.mobile_maintenance === 'true')
|
setMessageUpdate(v.mobile_message_update || '')
|
||||||
|
setMaintenance(v.mobile_maintenance === 'true')
|
||||||
}
|
}
|
||||||
}, [grid, versionModalOpened])
|
}, [versionModalOpened])
|
||||||
|
|
||||||
const handleRefresh = () => {
|
const handleRefresh = () => {
|
||||||
mutateGrid()
|
mutateGrid()
|
||||||
mutateDaily()
|
mutateDaily()
|
||||||
mutateComparison()
|
mutateComparison()
|
||||||
|
errorTableRef.current?.refresh()
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleSaveVersion = async () => {
|
const handleSaveVersion = async () => {
|
||||||
@@ -214,8 +220,8 @@ function AppOverviewPage() {
|
|||||||
value={gridLoading ? '...' : (grid?.activity?.today?.toLocaleString() ?? '0')}
|
value={gridLoading ? '...' : (grid?.activity?.today?.toLocaleString() ?? '0')}
|
||||||
icon={TbActivity}
|
icon={TbActivity}
|
||||||
color="teal"
|
color="teal"
|
||||||
trend={grid?.activity?.increase
|
trend={grid?.activity?.increase != null && Number(grid.activity.increase) !== 0
|
||||||
? { value: `${grid.activity.increase}%`, positive: grid.activity.increase > 0 }
|
? { value: `${grid.activity.increase}%`, positive: Number(grid.activity.increase) > 0 }
|
||||||
: undefined}
|
: undefined}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
@@ -250,11 +256,11 @@ function AppOverviewPage() {
|
|||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="lg">
|
<SimpleGrid cols={{ base: 1, lg: 2 }} spacing="lg">
|
||||||
<VillageActivityLineChart data={dailyData} isLoading={dailyLoading} />
|
<VillageActivityLineChart data={dailyData} isLoading={dailyLoading} range={dailyRange} onRangeChange={setDailyRange} />
|
||||||
<VillageComparisonBarChart data={comparisonData} isLoading={comparisonLoading} />
|
<VillageComparisonBarChart data={comparisonData} isLoading={comparisonLoading} range={comparisonRange} onRangeChange={setComparisonRange} />
|
||||||
</SimpleGrid>
|
</SimpleGrid>
|
||||||
|
|
||||||
<ErrorDataTable appId={appId} />
|
<ErrorDataTable ref={errorTableRef} appId={appId} />
|
||||||
</Stack>
|
</Stack>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import useSWR from 'swr'
|
import useSWR from 'swr'
|
||||||
import {
|
import {
|
||||||
ActionIcon,
|
ActionIcon,
|
||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
Pagination,
|
Pagination,
|
||||||
Paper,
|
Paper,
|
||||||
ScrollArea,
|
ScrollArea,
|
||||||
|
Select,
|
||||||
Stack,
|
Stack,
|
||||||
Table,
|
Table,
|
||||||
Text,
|
Text,
|
||||||
@@ -17,10 +18,12 @@ import {
|
|||||||
Title,
|
Title,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { useMediaQuery } from '@mantine/hooks'
|
import { useDebouncedValue, useMediaQuery } from '@mantine/hooks'
|
||||||
|
import { DatePickerInput } from '@mantine/dates'
|
||||||
import { createFileRoute, useParams } from '@tanstack/react-router'
|
import { createFileRoute, useParams } from '@tanstack/react-router'
|
||||||
import {
|
import {
|
||||||
TbAlertCircle,
|
TbAlertCircle,
|
||||||
|
TbCalendar,
|
||||||
TbHistory,
|
TbHistory,
|
||||||
TbHome2,
|
TbHome2,
|
||||||
TbSearch,
|
TbSearch,
|
||||||
@@ -51,30 +54,75 @@ const ACTION_COLOR: Record<string, string> = {
|
|||||||
DELETE: 'red',
|
DELETE: 'red',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ACTION_OPTIONS = [
|
||||||
|
{ value: 'LOGIN', label: 'Login' },
|
||||||
|
{ value: 'LOGOUT', label: 'Logout' },
|
||||||
|
{ value: 'CREATE', label: 'Create' },
|
||||||
|
{ value: 'UPDATE', label: 'Update' },
|
||||||
|
{ value: 'DELETE', label: 'Delete' },
|
||||||
|
]
|
||||||
|
|
||||||
function getActionColor(action: string) {
|
function getActionColor(action: string) {
|
||||||
return ACTION_COLOR[action.toUpperCase()] ?? 'brand-blue'
|
return ACTION_COLOR[action.toUpperCase()] ?? 'brand-blue'
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function LogTimestamp({ value }: { value: string }) {
|
||||||
|
if (value.endsWith('lalu')) {
|
||||||
|
return <Text size="xs" fw={600}>{value}</Text>
|
||||||
|
}
|
||||||
|
const [time, ...dateParts] = value.split(' ')
|
||||||
|
return (
|
||||||
|
<Stack gap={0}>
|
||||||
|
<Text size="xs" fw={600}>{dateParts.join(' ')}</Text>
|
||||||
|
<Text size="xs" c="dimmed">{time}</Text>
|
||||||
|
</Stack>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function AppLogsPage() {
|
function AppLogsPage() {
|
||||||
const { appId } = useParams({ from: '/apps/$appId/logs' })
|
const { appId } = useParams({ from: '/apps/$appId/logs' })
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
const [search, setSearch] = useState('')
|
const [search, setSearch] = useState('')
|
||||||
const [searchQuery, setSearchQuery] = useState('')
|
const [searchQuery, setSearchQuery] = useState('')
|
||||||
|
const [debouncedSearch] = useDebouncedValue(search, 400)
|
||||||
|
const [filterAction, setFilterAction] = useState<string | null>(null)
|
||||||
|
const [filterVillageSearch, setFilterVillageSearch] = useState('')
|
||||||
|
const [filterVillageId, setFilterVillageId] = useState<string | null>(null)
|
||||||
|
const [dateRange, setDateRange] = useState<[string | null, string | null]>([null, null])
|
||||||
|
|
||||||
const isDesaPlus = appId === 'desa-plus'
|
const isDesaPlus = appId === 'desa-plus'
|
||||||
const isMobile = useMediaQuery('(max-width: 768px)')
|
const isMobile = useMediaQuery('(max-width: 768px)')
|
||||||
|
|
||||||
const apiUrl = isDesaPlus ? API_URLS.getLogsAllVillages(page, searchQuery) : null
|
const [dateFrom, dateTo] = dateRange
|
||||||
|
const apiUrl = isDesaPlus
|
||||||
|
? API_URLS.getLogsAllVillages(
|
||||||
|
page,
|
||||||
|
searchQuery,
|
||||||
|
filterAction ?? undefined,
|
||||||
|
filterVillageId ?? undefined,
|
||||||
|
dateFrom ?? undefined,
|
||||||
|
dateTo ?? undefined,
|
||||||
|
)
|
||||||
|
: null
|
||||||
const { data: response, error, isLoading } = useSWR(apiUrl, fetcher)
|
const { data: response, error, isLoading } = useSWR(apiUrl, fetcher)
|
||||||
const logs: LogEntry[] = response?.data?.log || []
|
const logs: LogEntry[] = response?.data?.log || []
|
||||||
|
|
||||||
const handleSearchChange = (val: string) => {
|
const { data: filterVillagesResp } = useSWR(
|
||||||
setSearch(val)
|
isDesaPlus && filterVillageSearch.length >= 1 ? API_URLS.getVillages(1, filterVillageSearch) : null,
|
||||||
if (val.length >= 3 || val.length === 0) {
|
fetcher
|
||||||
setSearchQuery(val)
|
)
|
||||||
|
const filterVillagesOptions = (filterVillagesResp?.data || []).map((v: any) => ({ value: v.id, label: v.name }))
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (debouncedSearch.length >= 3 || debouncedSearch.length === 0) {
|
||||||
|
setSearchQuery(debouncedSearch)
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}
|
}
|
||||||
}
|
}, [debouncedSearch])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setPage(1)
|
||||||
|
}, [filterAction, filterVillageId, dateFrom, dateTo])
|
||||||
|
|
||||||
const handleClearSearch = () => {
|
const handleClearSearch = () => {
|
||||||
setSearch('')
|
setSearch('')
|
||||||
@@ -108,23 +156,61 @@ function AppLogsPage() {
|
|||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<Paper withBorder p="md" className="glass">
|
<Paper withBorder p="md" className="glass">
|
||||||
<TextInput
|
<Stack gap="sm">
|
||||||
placeholder="Search by action or village... (min. 3 characters)"
|
<TextInput
|
||||||
leftSection={<TbSearch size={16} />}
|
placeholder="Search by user name or village..."
|
||||||
size="sm"
|
leftSection={<TbSearch size={16} />}
|
||||||
rightSection={
|
size="sm"
|
||||||
search ? (
|
rightSection={
|
||||||
<Tooltip label="Clear search" withArrow>
|
search ? (
|
||||||
<ActionIcon variant="transparent" color="gray" onClick={handleClearSearch} size="sm">
|
<Tooltip label="Clear search" withArrow>
|
||||||
<TbX size={16} />
|
<ActionIcon variant="transparent" color="gray" onClick={handleClearSearch} size="sm">
|
||||||
</ActionIcon>
|
<TbX size={16} />
|
||||||
</Tooltip>
|
</ActionIcon>
|
||||||
) : null
|
</Tooltip>
|
||||||
}
|
) : null
|
||||||
value={search}
|
}
|
||||||
onChange={(e) => handleSearchChange(e.currentTarget.value)}
|
value={search}
|
||||||
radius="md"
|
onChange={(e) => setSearch(e.currentTarget.value)}
|
||||||
/>
|
radius="md"
|
||||||
|
/>
|
||||||
|
<Group gap="sm" wrap="nowrap">
|
||||||
|
<Select
|
||||||
|
size="sm"
|
||||||
|
placeholder="All actions"
|
||||||
|
data={ACTION_OPTIONS}
|
||||||
|
value={filterAction}
|
||||||
|
onChange={setFilterAction}
|
||||||
|
radius="md"
|
||||||
|
clearable
|
||||||
|
style={{ flex: 1 }}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
size="sm"
|
||||||
|
placeholder="Search village..."
|
||||||
|
searchable
|
||||||
|
onSearchChange={setFilterVillageSearch}
|
||||||
|
data={filterVillagesOptions}
|
||||||
|
value={filterVillageId}
|
||||||
|
onChange={setFilterVillageId}
|
||||||
|
radius="md"
|
||||||
|
clearable
|
||||||
|
style={{ flex: 1 }}
|
||||||
|
/>
|
||||||
|
<DatePickerInput
|
||||||
|
type="range"
|
||||||
|
size="sm"
|
||||||
|
placeholder="Date range"
|
||||||
|
leftSection={<TbCalendar size={16} />}
|
||||||
|
value={dateRange}
|
||||||
|
onChange={setDateRange}
|
||||||
|
radius="md"
|
||||||
|
clearable
|
||||||
|
style={{ flex: 1 }}
|
||||||
|
maxDate={new Date()}
|
||||||
|
/>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
@@ -143,7 +229,7 @@ function AppLogsPage() {
|
|||||||
<Stack align="center" gap="xs" py="xl">
|
<Stack align="center" gap="xs" py="xl">
|
||||||
<TbHistory size={32} style={{ opacity: 0.25 }} />
|
<TbHistory size={32} style={{ opacity: 0.25 }} />
|
||||||
<Text size="sm" c="dimmed">
|
<Text size="sm" c="dimmed">
|
||||||
{searchQuery ? 'No activity found for this search.' : 'No activity logs yet.'}
|
{searchQuery || filterAction || filterVillageId || dateFrom ? 'No activity found for this filter.' : 'No activity logs yet.'}
|
||||||
</Text>
|
</Text>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Paper>
|
</Paper>
|
||||||
@@ -174,18 +260,7 @@ function AppLogsPage() {
|
|||||||
{logs.map((log) => (
|
{logs.map((log) => (
|
||||||
<Table.Tr key={log.id}>
|
<Table.Tr key={log.id}>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
{log.createdAt.endsWith('lalu') ? (
|
<LogTimestamp value={log.createdAt} />
|
||||||
<Text size="xs" fw={600}>{log.createdAt}</Text>
|
|
||||||
) : (
|
|
||||||
<Stack gap={0}>
|
|
||||||
<Text size="xs" fw={600}>
|
|
||||||
{log.createdAt.split(' ').slice(1).join(' ')}
|
|
||||||
</Text>
|
|
||||||
<Text size="xs" c="dimmed">
|
|
||||||
{log.createdAt.split(' ')[0]}
|
|
||||||
</Text>
|
|
||||||
</Stack>
|
|
||||||
)}
|
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Stack gap={4} style={{ overflow: 'hidden' }}>
|
<Stack gap={4} style={{ overflow: 'hidden' }}>
|
||||||
@@ -229,7 +304,7 @@ function AppLogsPage() {
|
|||||||
</Paper>
|
</Paper>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!isLoading && !error && response?.data?.totalPage > 0 && (
|
{!isLoading && !error && response?.data?.totalPage > 1 && (
|
||||||
<Group justify="center">
|
<Group justify="center">
|
||||||
<Pagination
|
<Pagination
|
||||||
value={page}
|
value={page}
|
||||||
|
|||||||
@@ -22,16 +22,18 @@ import {
|
|||||||
Title,
|
Title,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
} from '@mantine/core'
|
} from '@mantine/core'
|
||||||
import { useDisclosure, useMediaQuery } from '@mantine/hooks'
|
import { useDisclosure, useDebouncedValue, useMediaQuery } from '@mantine/hooks'
|
||||||
import { notifications } from '@mantine/notifications'
|
import { notifications } from '@mantine/notifications'
|
||||||
import { createFileRoute, useParams } from '@tanstack/react-router'
|
import { createFileRoute, useParams } from '@tanstack/react-router'
|
||||||
import { useState } from 'react'
|
import { useEffect, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
TbAlertCircle,
|
TbAlertCircle,
|
||||||
|
TbArrowDown,
|
||||||
|
TbArrowsSort,
|
||||||
|
TbArrowUp,
|
||||||
TbBriefcase,
|
TbBriefcase,
|
||||||
TbCircleCheck,
|
TbCircleCheck,
|
||||||
TbCircleX,
|
TbCircleX,
|
||||||
TbEdit,
|
|
||||||
TbHome2,
|
TbHome2,
|
||||||
TbId,
|
TbId,
|
||||||
TbMail,
|
TbMail,
|
||||||
@@ -68,33 +70,218 @@ interface APIUser {
|
|||||||
idPosition: string
|
idPosition: string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface BaseUserForm {
|
||||||
|
name: string
|
||||||
|
nik: string
|
||||||
|
phone: string
|
||||||
|
email: string
|
||||||
|
gender: string
|
||||||
|
idUserRole: string
|
||||||
|
idVillage: string
|
||||||
|
idGroup: string
|
||||||
|
idPosition: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const FIELD_LABELS: Record<string, string> = {
|
||||||
|
name: 'Full Name',
|
||||||
|
nik: 'NIK',
|
||||||
|
phone: 'Phone Number',
|
||||||
|
email: 'Email Address',
|
||||||
|
gender: 'Gender',
|
||||||
|
idUserRole: 'User Role',
|
||||||
|
idVillage: 'Village',
|
||||||
|
idGroup: 'Group',
|
||||||
|
}
|
||||||
|
|
||||||
|
const REQUIRED_FIELDS = ['name', 'nik', 'phone', 'email', 'gender', 'idUserRole', 'idVillage', 'idGroup']
|
||||||
|
|
||||||
const fetcher = (url: string) => fetch(url).then((res) => res.json())
|
const fetcher = (url: string) => fetch(url).then((res) => res.json())
|
||||||
|
|
||||||
|
interface UserFormFieldsProps {
|
||||||
|
values: BaseUserForm
|
||||||
|
onChange: (updates: Partial<BaseUserForm>) => void
|
||||||
|
villageSearch: string
|
||||||
|
onVillageSearchChange: (v: string) => void
|
||||||
|
rolesOptions: { value: string; label: string }[]
|
||||||
|
villagesOptions: { value: string; label: string }[]
|
||||||
|
groupsOptions: { value: string; label: string }[]
|
||||||
|
positionsOptions: { value: string; label: string }[]
|
||||||
|
}
|
||||||
|
|
||||||
|
function UserFormFields({
|
||||||
|
values,
|
||||||
|
onChange,
|
||||||
|
onVillageSearchChange,
|
||||||
|
rolesOptions,
|
||||||
|
villagesOptions,
|
||||||
|
groupsOptions,
|
||||||
|
positionsOptions,
|
||||||
|
}: UserFormFieldsProps) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Box>
|
||||||
|
<Text size="xs" fw={700} c="dimmed" mb={8} tt="uppercase" style={{ letterSpacing: '0.05em' }}>
|
||||||
|
Personal Information
|
||||||
|
</Text>
|
||||||
|
<SimpleGrid cols={2} spacing="md">
|
||||||
|
<TextInput
|
||||||
|
label="Full Name"
|
||||||
|
placeholder="Enter full name"
|
||||||
|
required
|
||||||
|
value={values.name}
|
||||||
|
onChange={(e) => onChange({ name: e.target.value })}
|
||||||
|
/>
|
||||||
|
<TextInput
|
||||||
|
label="NIK"
|
||||||
|
placeholder="16-digit identity number"
|
||||||
|
required
|
||||||
|
value={values.nik}
|
||||||
|
onChange={(e) => onChange({ nik: e.target.value })}
|
||||||
|
/>
|
||||||
|
</SimpleGrid>
|
||||||
|
|
||||||
|
<SimpleGrid cols={2} spacing="md" mt="sm">
|
||||||
|
<TextInput
|
||||||
|
label="Email Address"
|
||||||
|
placeholder="email@example.com"
|
||||||
|
required
|
||||||
|
value={values.email}
|
||||||
|
onChange={(e) => onChange({ email: e.target.value })}
|
||||||
|
/>
|
||||||
|
<TextInput
|
||||||
|
label="Phone Number"
|
||||||
|
placeholder="628xxxxxxxxxx"
|
||||||
|
required
|
||||||
|
value={values.phone}
|
||||||
|
onChange={(e) => onChange({ phone: e.target.value })}
|
||||||
|
/>
|
||||||
|
</SimpleGrid>
|
||||||
|
|
||||||
|
<Select
|
||||||
|
label="Gender"
|
||||||
|
placeholder="Select gender"
|
||||||
|
data={[
|
||||||
|
{ value: 'M', label: 'Male' },
|
||||||
|
{ value: 'F', label: 'Female' },
|
||||||
|
]}
|
||||||
|
mt="sm"
|
||||||
|
required
|
||||||
|
value={values.gender}
|
||||||
|
onChange={(v) => onChange({ gender: v || '' })}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
<Divider label="Role & Organization" labelPosition="center" my="sm" />
|
||||||
|
|
||||||
|
<Box>
|
||||||
|
<Select
|
||||||
|
label="User Role"
|
||||||
|
placeholder="Select user role"
|
||||||
|
data={rolesOptions}
|
||||||
|
required
|
||||||
|
value={values.idUserRole}
|
||||||
|
onChange={(v) => onChange({ idUserRole: v || '' })}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Select
|
||||||
|
label="Village"
|
||||||
|
placeholder="Type to search village..."
|
||||||
|
searchable
|
||||||
|
onSearchChange={onVillageSearchChange}
|
||||||
|
data={villagesOptions}
|
||||||
|
mt="sm"
|
||||||
|
required
|
||||||
|
value={values.idVillage}
|
||||||
|
onChange={(v) => onChange({ idVillage: v || '', idGroup: '', idPosition: '' })}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<SimpleGrid cols={2} spacing="md" mt="sm">
|
||||||
|
<Select
|
||||||
|
label="Group"
|
||||||
|
placeholder={values.idVillage ? 'Select group' : 'Select village first'}
|
||||||
|
data={groupsOptions}
|
||||||
|
disabled={!values.idVillage}
|
||||||
|
required
|
||||||
|
value={values.idGroup}
|
||||||
|
onChange={(v) => onChange({ idGroup: v || '', idPosition: '' })}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
label="Position"
|
||||||
|
placeholder={values.idGroup ? 'Select position' : 'Select group first'}
|
||||||
|
data={positionsOptions}
|
||||||
|
disabled={!values.idGroup}
|
||||||
|
value={values.idPosition || ''}
|
||||||
|
onChange={(v) => onChange({ idPosition: v || '' })}
|
||||||
|
/>
|
||||||
|
</SimpleGrid>
|
||||||
|
</Box>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
function UsersIndexPage() {
|
function UsersIndexPage() {
|
||||||
const { appId } = useParams({ from: '/apps/$appId/users/' })
|
const { appId } = useParams({ from: '/apps/$appId/users/' })
|
||||||
const [page, setPage] = useState(1)
|
const [page, setPage] = useState(1)
|
||||||
const [search, setSearch] = useState('')
|
const [search, setSearch] = useState('')
|
||||||
const [searchQuery, setSearchQuery] = useState('')
|
const [searchQuery, setSearchQuery] = useState('')
|
||||||
|
const [debouncedSearch] = useDebouncedValue(search, 400)
|
||||||
|
const [filterStatus, setFilterStatus] = useState<string | null>(null)
|
||||||
|
const [filterRole, setFilterRole] = useState<string | null>(null)
|
||||||
|
const [filterVillageSearch, setFilterVillageSearch] = useState('')
|
||||||
|
const [filterVillageId, setFilterVillageId] = useState<string | null>(null)
|
||||||
|
const [sortBy, setSortBy] = useState<string | null>(null)
|
||||||
|
const [sortDir, setSortDir] = useState<'asc' | 'desc'>('asc')
|
||||||
|
|
||||||
|
const handleSort = (col: string) => {
|
||||||
|
if (sortBy === col) {
|
||||||
|
setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'))
|
||||||
|
} else {
|
||||||
|
setSortBy(col)
|
||||||
|
setSortDir('asc')
|
||||||
|
}
|
||||||
|
setPage(1)
|
||||||
|
}
|
||||||
|
|
||||||
const isDesaPlus = appId === 'desa-plus'
|
const isDesaPlus = appId === 'desa-plus'
|
||||||
const apiUrl = isDesaPlus ? API_URLS.getUsers(page, searchQuery) : null
|
|
||||||
|
const filterStatusParam = filterStatus === 'active' ? 'true' : filterStatus === 'inactive' ? 'false' : undefined
|
||||||
|
const apiUrl = isDesaPlus
|
||||||
|
? API_URLS.getUsers(
|
||||||
|
page,
|
||||||
|
searchQuery,
|
||||||
|
filterStatusParam,
|
||||||
|
filterRole ?? undefined,
|
||||||
|
filterVillageId ?? undefined,
|
||||||
|
sortBy ?? undefined,
|
||||||
|
sortBy ? sortDir : undefined,
|
||||||
|
)
|
||||||
|
: null
|
||||||
|
|
||||||
const { data: response, error, isLoading, mutate } = useSWR(apiUrl, fetcher)
|
const { data: response, error, isLoading, mutate } = useSWR(apiUrl, fetcher)
|
||||||
const users: APIUser[] = response?.data?.user || []
|
const users: APIUser[] = response?.data?.user || []
|
||||||
|
|
||||||
const handleSearchChange = (val: string) => {
|
useEffect(() => {
|
||||||
setSearch(val)
|
if (debouncedSearch.length >= 3 || debouncedSearch.length === 0) {
|
||||||
if (val.length >= 3 || val.length === 0) {
|
setSearchQuery(debouncedSearch)
|
||||||
setSearchQuery(val)
|
|
||||||
setPage(1)
|
setPage(1)
|
||||||
}
|
}
|
||||||
|
}, [debouncedSearch])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setPage(1)
|
||||||
|
}, [filterStatus, filterRole, filterVillageId])
|
||||||
|
|
||||||
|
const handleClearSearch = () => {
|
||||||
|
setSearch('')
|
||||||
|
setSearchQuery('')
|
||||||
|
setPage(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- ADD USER LOGIC ---
|
// --- ADD USER LOGIC ---
|
||||||
const [opened, { open, close }] = useDisclosure(false)
|
const [opened, { open, close }] = useDisclosure(false)
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||||
const [villageSearch, setVillageSearch] = useState('')
|
const [villageSearch, setVillageSearch] = useState('')
|
||||||
const [form, setForm] = useState({
|
const [form, setForm] = useState<BaseUserForm>({
|
||||||
name: '',
|
name: '',
|
||||||
nik: '',
|
nik: '',
|
||||||
phone: '',
|
phone: '',
|
||||||
@@ -103,7 +290,7 @@ function UsersIndexPage() {
|
|||||||
idUserRole: '',
|
idUserRole: '',
|
||||||
idVillage: '',
|
idVillage: '',
|
||||||
idGroup: '',
|
idGroup: '',
|
||||||
idPosition: ''
|
idPosition: '',
|
||||||
})
|
})
|
||||||
|
|
||||||
const [editOpened, { open: openEdit, close: closeEdit }] = useDisclosure(false)
|
const [editOpened, { open: openEdit, close: closeEdit }] = useDisclosure(false)
|
||||||
@@ -120,7 +307,7 @@ function UsersIndexPage() {
|
|||||||
idPosition: '',
|
idPosition: '',
|
||||||
isActive: true,
|
isActive: true,
|
||||||
isWithoutOTP: false,
|
isWithoutOTP: false,
|
||||||
isApprover: false
|
isApprover: false,
|
||||||
})
|
})
|
||||||
|
|
||||||
// Options Data (Shared for both Add and Edit modals)
|
// Options Data (Shared for both Add and Edit modals)
|
||||||
@@ -128,7 +315,11 @@ function UsersIndexPage() {
|
|||||||
const targetVillageId = opened ? form.idVillage : editForm.idVillage
|
const targetVillageId = opened ? form.idVillage : editForm.idVillage
|
||||||
const targetGroupId = opened ? form.idGroup : editForm.idGroup
|
const targetGroupId = opened ? form.idGroup : editForm.idGroup
|
||||||
|
|
||||||
const { data: rolesResp } = useSWR(isAnyModalOpened ? API_URLS.listRole() : null, fetcher)
|
const { data: rolesResp } = useSWR(isDesaPlus ? API_URLS.listRole() : null, fetcher)
|
||||||
|
const { data: filterVillagesResp } = useSWR(
|
||||||
|
isDesaPlus && filterVillageSearch.length >= 1 ? API_URLS.getVillages(1, filterVillageSearch) : null,
|
||||||
|
fetcher
|
||||||
|
)
|
||||||
const { data: villagesResp } = useSWR(
|
const { data: villagesResp } = useSWR(
|
||||||
isAnyModalOpened && villageSearch.length >= 1 ? API_URLS.getVillages(1, villageSearch) : null,
|
isAnyModalOpened && villageSearch.length >= 1 ? API_URLS.getVillages(1, villageSearch) : null,
|
||||||
fetcher
|
fetcher
|
||||||
@@ -143,19 +334,21 @@ function UsersIndexPage() {
|
|||||||
)
|
)
|
||||||
|
|
||||||
const rolesOptions = (rolesResp?.data || []).map((r: any) => ({ value: r.id, label: r.name }))
|
const rolesOptions = (rolesResp?.data || []).map((r: any) => ({ value: r.id, label: r.name }))
|
||||||
|
const filterVillagesOptions = (filterVillagesResp?.data || []).map((v: any) => ({ value: v.id, label: v.name }))
|
||||||
const villagesOptions = (villagesResp?.data || []).map((v: any) => ({ value: v.id, label: v.name }))
|
const villagesOptions = (villagesResp?.data || []).map((v: any) => ({ value: v.id, label: v.name }))
|
||||||
const groupsOptions = (groupsResp?.data || []).map((g: any) => ({ value: g.id, label: g.name }))
|
const groupsOptions = (groupsResp?.data || []).map((g: any) => ({ value: g.id, label: g.name }))
|
||||||
const positionsOptions = (positionsResp?.data || []).map((p: any) => ({ value: p.id, label: p.name }))
|
const positionsOptions = (positionsResp?.data || []).map((p: any) => ({ value: p.id, label: p.name }))
|
||||||
|
|
||||||
const handleCreateUser = async () => {
|
const getMissingFields = (data: BaseUserForm) =>
|
||||||
const requiredFields = ['name', 'nik', 'phone', 'email', 'gender', 'idUserRole', 'idVillage', 'idGroup']
|
REQUIRED_FIELDS.filter((f) => !data[f as keyof BaseUserForm]).map((f) => FIELD_LABELS[f] ?? f)
|
||||||
const missing = requiredFields.filter(f => !form[f as keyof typeof form])
|
|
||||||
|
|
||||||
|
const handleCreateUser = async () => {
|
||||||
|
const missing = getMissingFields(form)
|
||||||
if (missing.length > 0) {
|
if (missing.length > 0) {
|
||||||
notifications.show({
|
notifications.show({
|
||||||
title: 'Validation Error',
|
title: 'Validation Error',
|
||||||
message: `Please fill in all required fields: ${missing.join(', ')}`,
|
message: `Please fill in: ${missing.join(', ')}`,
|
||||||
color: 'red'
|
color: 'red',
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -165,7 +358,7 @@ function UsersIndexPage() {
|
|||||||
const res = await fetch(API_URLS.createUser(), {
|
const res = await fetch(API_URLS.createUser(), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(form)
|
body: JSON.stringify(form),
|
||||||
})
|
})
|
||||||
|
|
||||||
const result = await res.json()
|
const result = await res.json()
|
||||||
@@ -174,14 +367,14 @@ function UsersIndexPage() {
|
|||||||
await fetch(API_URLS.createLog(), {
|
await fetch(API_URLS.createLog(), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ type: 'CREATE', message: `New user registered (${appId}): ${form.name} - ${form.nik}` })
|
body: JSON.stringify({ type: 'CREATE', message: `New user registered (${appId}): ${form.name} - ${form.nik}` }),
|
||||||
}).catch(console.error)
|
}).catch(console.error)
|
||||||
|
|
||||||
notifications.show({
|
notifications.show({
|
||||||
title: 'Success',
|
title: 'Success',
|
||||||
message: 'User has been created successfully.',
|
message: 'User has been created successfully.',
|
||||||
color: 'teal',
|
color: 'teal',
|
||||||
icon: <TbCircleCheck size={18} />
|
icon: <TbCircleCheck size={18} />,
|
||||||
})
|
})
|
||||||
mutate()
|
mutate()
|
||||||
close()
|
close()
|
||||||
@@ -191,7 +384,7 @@ function UsersIndexPage() {
|
|||||||
title: 'Error',
|
title: 'Error',
|
||||||
message: result.message || 'Failed to create user.',
|
message: result.message || 'Failed to create user.',
|
||||||
color: 'red',
|
color: 'red',
|
||||||
icon: <TbCircleX size={18} />
|
icon: <TbCircleX size={18} />,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
@@ -215,21 +408,19 @@ function UsersIndexPage() {
|
|||||||
idPosition: user.idPosition,
|
idPosition: user.idPosition,
|
||||||
isActive: user.isActive,
|
isActive: user.isActive,
|
||||||
isWithoutOTP: user.isWithoutOTP,
|
isWithoutOTP: user.isWithoutOTP,
|
||||||
isApprover: user.isApprover
|
isApprover: user.isApprover,
|
||||||
})
|
})
|
||||||
setVillageSearch(user.village)
|
setVillageSearch(user.village)
|
||||||
openEdit()
|
openEdit()
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleUpdateUser = async () => {
|
const handleUpdateUser = async () => {
|
||||||
const requiredFields = ['name', 'nik', 'phone', 'email', 'gender', 'idUserRole', 'idVillage', 'idGroup']
|
const missing = getMissingFields(editForm)
|
||||||
const missing = requiredFields.filter(f => !editForm[f as keyof typeof editForm])
|
|
||||||
|
|
||||||
if (missing.length > 0) {
|
if (missing.length > 0) {
|
||||||
notifications.show({
|
notifications.show({
|
||||||
title: 'Validation Error',
|
title: 'Validation Error',
|
||||||
message: `Please fill in all required fields: ${missing.join(', ')}`,
|
message: `Please fill in: ${missing.join(', ')}`,
|
||||||
color: 'red'
|
color: 'red',
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -239,7 +430,7 @@ function UsersIndexPage() {
|
|||||||
const res = await fetch(API_URLS.editUser(), {
|
const res = await fetch(API_URLS.editUser(), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(editForm)
|
body: JSON.stringify(editForm),
|
||||||
})
|
})
|
||||||
|
|
||||||
const result = await res.json()
|
const result = await res.json()
|
||||||
@@ -248,14 +439,14 @@ function UsersIndexPage() {
|
|||||||
await fetch(API_URLS.createLog(), {
|
await fetch(API_URLS.createLog(), {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ type: 'UPDATE', message: `User updated (${appId}): ${editForm.name} - ${editForm.id}` })
|
body: JSON.stringify({ type: 'UPDATE', message: `User updated (${appId}): ${editForm.name} - ${editForm.id}` }),
|
||||||
}).catch(console.error)
|
}).catch(console.error)
|
||||||
|
|
||||||
notifications.show({
|
notifications.show({
|
||||||
title: 'Success',
|
title: 'Success',
|
||||||
message: 'User has been updated successfully.',
|
message: 'User has been updated successfully.',
|
||||||
color: 'teal',
|
color: 'teal',
|
||||||
icon: <TbCircleCheck size={18} />
|
icon: <TbCircleCheck size={18} />,
|
||||||
})
|
})
|
||||||
mutate()
|
mutate()
|
||||||
closeEdit()
|
closeEdit()
|
||||||
@@ -264,7 +455,7 @@ function UsersIndexPage() {
|
|||||||
title: 'Error',
|
title: 'Error',
|
||||||
message: result.message || 'Failed to update user.',
|
message: result.message || 'Failed to update user.',
|
||||||
color: 'red',
|
color: 'red',
|
||||||
icon: <TbCircleX size={18} />
|
icon: <TbCircleX size={18} />,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
@@ -274,12 +465,6 @@ function UsersIndexPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleClearSearch = () => {
|
|
||||||
setSearch('')
|
|
||||||
setSearchQuery('')
|
|
||||||
setPage(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
const getRoleColor = (role: string) => {
|
const getRoleColor = (role: string) => {
|
||||||
const r = role.toLowerCase()
|
const r = role.toLowerCase()
|
||||||
if (r.includes('super')) return 'red'
|
if (r.includes('super')) return 'red'
|
||||||
@@ -290,6 +475,15 @@ function UsersIndexPage() {
|
|||||||
|
|
||||||
const isMobile = useMediaQuery('(max-width: 768px)')
|
const isMobile = useMediaQuery('(max-width: 768px)')
|
||||||
|
|
||||||
|
const sharedFormProps = {
|
||||||
|
villageSearch,
|
||||||
|
onVillageSearchChange: setVillageSearch,
|
||||||
|
rolesOptions,
|
||||||
|
villagesOptions,
|
||||||
|
groupsOptions,
|
||||||
|
positionsOptions,
|
||||||
|
}
|
||||||
|
|
||||||
if (!isDesaPlus) {
|
if (!isDesaPlus) {
|
||||||
return (
|
return (
|
||||||
<Paper withBorder radius="2xl" className="glass" p="xl">
|
<Paper withBorder radius="2xl" className="glass" p="xl">
|
||||||
@@ -314,102 +508,11 @@ function UsersIndexPage() {
|
|||||||
overlayProps={{ backgroundOpacity: 0.55, blur: 3 }}
|
overlayProps={{ backgroundOpacity: 0.55, blur: 3 }}
|
||||||
>
|
>
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
<Box>
|
<UserFormFields
|
||||||
<Text size="xs" fw={700} c="dimmed" mb={8} tt="uppercase" style={{ letterSpacing: '0.05em' }}>
|
values={form}
|
||||||
Personal Information
|
onChange={(updates) => setForm((f) => ({ ...f, ...updates }))}
|
||||||
</Text>
|
{...sharedFormProps}
|
||||||
<SimpleGrid cols={2} spacing="md">
|
/>
|
||||||
<TextInput
|
|
||||||
label="Full Name"
|
|
||||||
placeholder="Enter full name"
|
|
||||||
required
|
|
||||||
value={form.name}
|
|
||||||
onChange={(e) => setForm(f => ({ ...f, name: e.target.value }))}
|
|
||||||
/>
|
|
||||||
<TextInput
|
|
||||||
label="NIK"
|
|
||||||
placeholder="16-digit identity number"
|
|
||||||
required
|
|
||||||
value={form.nik}
|
|
||||||
onChange={(e) => setForm(f => ({ ...f, nik: e.target.value }))}
|
|
||||||
/>
|
|
||||||
</SimpleGrid>
|
|
||||||
|
|
||||||
<SimpleGrid cols={2} spacing="md" mt="sm">
|
|
||||||
<TextInput
|
|
||||||
label="Email Address"
|
|
||||||
placeholder="email@example.com"
|
|
||||||
required
|
|
||||||
value={form.email}
|
|
||||||
onChange={(e) => setForm(f => ({ ...f, email: e.target.value }))}
|
|
||||||
/>
|
|
||||||
<TextInput
|
|
||||||
label="Phone Number"
|
|
||||||
placeholder="628xxxxxxxxxx"
|
|
||||||
required
|
|
||||||
value={form.phone}
|
|
||||||
onChange={(e) => setForm(f => ({ ...f, phone: e.target.value }))}
|
|
||||||
/>
|
|
||||||
</SimpleGrid>
|
|
||||||
|
|
||||||
<Select
|
|
||||||
label="Gender"
|
|
||||||
placeholder="Select gender"
|
|
||||||
data={[
|
|
||||||
{ value: 'M', label: 'Male' },
|
|
||||||
{ value: 'F', label: 'Female' },
|
|
||||||
]}
|
|
||||||
mt="sm"
|
|
||||||
required
|
|
||||||
value={form.gender}
|
|
||||||
onChange={(v) => setForm(f => ({ ...f, gender: v || '' }))}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Divider label="Role & Organization" labelPosition="center" my="sm" />
|
|
||||||
|
|
||||||
<Box>
|
|
||||||
<Select
|
|
||||||
label="User Role"
|
|
||||||
placeholder="Select user role"
|
|
||||||
data={rolesOptions}
|
|
||||||
required
|
|
||||||
value={form.idUserRole}
|
|
||||||
onChange={(v) => setForm(f => ({ ...f, idUserRole: v || '' }))}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Select
|
|
||||||
label="Village"
|
|
||||||
placeholder="Type to search village..."
|
|
||||||
searchable
|
|
||||||
onSearchChange={setVillageSearch}
|
|
||||||
data={villagesOptions}
|
|
||||||
mt="sm"
|
|
||||||
required
|
|
||||||
value={form.idVillage}
|
|
||||||
onChange={(v) => setForm(f => ({ ...f, idVillage: v || '', idGroup: '', idPosition: '' }))}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<SimpleGrid cols={2} spacing="md" mt="sm">
|
|
||||||
<Select
|
|
||||||
label="Group"
|
|
||||||
placeholder={form.idVillage ? 'Select group' : 'Select village first'}
|
|
||||||
data={groupsOptions}
|
|
||||||
disabled={!form.idVillage}
|
|
||||||
required
|
|
||||||
value={form.idGroup}
|
|
||||||
onChange={(v) => setForm(f => ({ ...f, idGroup: v || '', idPosition: '' }))}
|
|
||||||
/>
|
|
||||||
<Select
|
|
||||||
label="Position"
|
|
||||||
placeholder={form.idGroup ? 'Select position' : 'Select group first'}
|
|
||||||
data={positionsOptions}
|
|
||||||
disabled={!form.idGroup}
|
|
||||||
value={form.idPosition || ''}
|
|
||||||
onChange={(v) => setForm(f => ({ ...f, idPosition: v || '' }))}
|
|
||||||
/>
|
|
||||||
</SimpleGrid>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
fullWidth
|
fullWidth
|
||||||
@@ -435,102 +538,11 @@ function UsersIndexPage() {
|
|||||||
overlayProps={{ backgroundOpacity: 0.55, blur: 3 }}
|
overlayProps={{ backgroundOpacity: 0.55, blur: 3 }}
|
||||||
>
|
>
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
<Box>
|
<UserFormFields
|
||||||
<Text size="xs" fw={700} c="dimmed" mb={8} tt="uppercase" style={{ letterSpacing: '0.05em' }}>
|
values={editForm}
|
||||||
Personal Information
|
onChange={(updates) => setEditForm((f) => ({ ...f, ...updates }))}
|
||||||
</Text>
|
{...sharedFormProps}
|
||||||
<SimpleGrid cols={2} spacing="md">
|
/>
|
||||||
<TextInput
|
|
||||||
label="Full Name"
|
|
||||||
placeholder="Enter full name"
|
|
||||||
required
|
|
||||||
value={editForm.name}
|
|
||||||
onChange={(e) => setEditForm(f => ({ ...f, name: e.target.value }))}
|
|
||||||
/>
|
|
||||||
<TextInput
|
|
||||||
label="NIK"
|
|
||||||
placeholder="16-digit identity number"
|
|
||||||
required
|
|
||||||
value={editForm.nik}
|
|
||||||
onChange={(e) => setEditForm(f => ({ ...f, nik: e.target.value }))}
|
|
||||||
/>
|
|
||||||
</SimpleGrid>
|
|
||||||
|
|
||||||
<SimpleGrid cols={2} spacing="md" mt="sm">
|
|
||||||
<TextInput
|
|
||||||
label="Email Address"
|
|
||||||
placeholder="email@example.com"
|
|
||||||
required
|
|
||||||
value={editForm.email}
|
|
||||||
onChange={(e) => setEditForm(f => ({ ...f, email: e.target.value }))}
|
|
||||||
/>
|
|
||||||
<TextInput
|
|
||||||
label="Phone Number"
|
|
||||||
placeholder="628xxxxxxxxxx"
|
|
||||||
required
|
|
||||||
value={editForm.phone}
|
|
||||||
onChange={(e) => setEditForm(f => ({ ...f, phone: e.target.value }))}
|
|
||||||
/>
|
|
||||||
</SimpleGrid>
|
|
||||||
|
|
||||||
<Select
|
|
||||||
label="Gender"
|
|
||||||
placeholder="Select gender"
|
|
||||||
data={[
|
|
||||||
{ value: 'M', label: 'Male' },
|
|
||||||
{ value: 'F', label: 'Female' },
|
|
||||||
]}
|
|
||||||
mt="sm"
|
|
||||||
required
|
|
||||||
value={editForm.gender}
|
|
||||||
onChange={(v) => setEditForm(f => ({ ...f, gender: v || '' }))}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Divider label="Role & Organization" labelPosition="center" my="sm" />
|
|
||||||
|
|
||||||
<Box>
|
|
||||||
<Select
|
|
||||||
label="User Role"
|
|
||||||
placeholder="Select user role"
|
|
||||||
data={rolesOptions}
|
|
||||||
required
|
|
||||||
value={editForm.idUserRole}
|
|
||||||
onChange={(v) => setEditForm(f => ({ ...f, idUserRole: v || '' }))}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Select
|
|
||||||
label="Village"
|
|
||||||
placeholder="Type to search village..."
|
|
||||||
searchable
|
|
||||||
onSearchChange={setVillageSearch}
|
|
||||||
data={villagesOptions}
|
|
||||||
mt="sm"
|
|
||||||
required
|
|
||||||
value={editForm.idVillage}
|
|
||||||
onChange={(v) => setEditForm(f => ({ ...f, idVillage: v || '', idGroup: '', idPosition: '' }))}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<SimpleGrid cols={2} spacing="md" mt="sm">
|
|
||||||
<Select
|
|
||||||
label="Group"
|
|
||||||
placeholder={editForm.idVillage ? 'Select group' : 'Select village first'}
|
|
||||||
data={groupsOptions}
|
|
||||||
disabled={!editForm.idVillage}
|
|
||||||
required
|
|
||||||
value={editForm.idGroup}
|
|
||||||
onChange={(v) => setEditForm(f => ({ ...f, idGroup: v || '', idPosition: '' }))}
|
|
||||||
/>
|
|
||||||
<Select
|
|
||||||
label="Position"
|
|
||||||
placeholder={editForm.idGroup ? 'Select position' : 'Select group first'}
|
|
||||||
data={positionsOptions}
|
|
||||||
disabled={!editForm.idGroup}
|
|
||||||
value={editForm.idPosition || ''}
|
|
||||||
onChange={(v) => setEditForm(f => ({ ...f, idPosition: v || '' }))}
|
|
||||||
/>
|
|
||||||
</SimpleGrid>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Divider label="System Access" labelPosition="center" my="sm" />
|
<Divider label="System Access" labelPosition="center" my="sm" />
|
||||||
|
|
||||||
@@ -539,19 +551,19 @@ function UsersIndexPage() {
|
|||||||
label="Account Active"
|
label="Account Active"
|
||||||
description="Enable or disable user access"
|
description="Enable or disable user access"
|
||||||
checked={editForm.isActive}
|
checked={editForm.isActive}
|
||||||
onChange={(event) => setEditForm(f => ({ ...f, isActive: event.currentTarget.checked }))}
|
onChange={(event) => setEditForm((f) => ({ ...f, isActive: event.currentTarget.checked }))}
|
||||||
/>
|
/>
|
||||||
<Switch
|
<Switch
|
||||||
label="Without OTP"
|
label="Without OTP"
|
||||||
description="Bypass login OTP verification"
|
description="Bypass login OTP verification"
|
||||||
checked={editForm.isWithoutOTP}
|
checked={editForm.isWithoutOTP}
|
||||||
onChange={(event) => setEditForm(f => ({ ...f, isWithoutOTP: event.currentTarget.checked }))}
|
onChange={(event) => setEditForm((f) => ({ ...f, isWithoutOTP: event.currentTarget.checked }))}
|
||||||
/>
|
/>
|
||||||
<Switch
|
<Switch
|
||||||
label="Approver"
|
label="Approver"
|
||||||
description="Grant approver privileges to this user"
|
description="Grant approver privileges to this user"
|
||||||
checked={editForm.isApprover}
|
checked={editForm.isApprover}
|
||||||
onChange={(event) => setEditForm(f => ({ ...f, isApprover: event.currentTarget.checked }))}
|
onChange={(event) => setEditForm((f) => ({ ...f, isApprover: event.currentTarget.checked }))}
|
||||||
/>
|
/>
|
||||||
</SimpleGrid>
|
</SimpleGrid>
|
||||||
|
|
||||||
@@ -590,23 +602,62 @@ function UsersIndexPage() {
|
|||||||
|
|
||||||
{/* Search / Filter */}
|
{/* Search / Filter */}
|
||||||
<Paper withBorder p="md" className="glass">
|
<Paper withBorder p="md" className="glass">
|
||||||
<TextInput
|
<Stack gap="sm">
|
||||||
placeholder="Search name, NIK, or email... (min. 3 characters)"
|
<TextInput
|
||||||
leftSection={<TbSearch size={16} />}
|
placeholder="Search name, NIK, or email... (min. 3 characters)"
|
||||||
size="sm"
|
leftSection={<TbSearch size={16} />}
|
||||||
rightSection={
|
size="sm"
|
||||||
search ? (
|
rightSection={
|
||||||
<Tooltip label="Clear search" withArrow>
|
search ? (
|
||||||
<ActionIcon variant="transparent" color="gray" onClick={handleClearSearch} size="sm">
|
<Tooltip label="Clear search" withArrow>
|
||||||
<TbX size={16} />
|
<ActionIcon variant="transparent" color="gray" onClick={handleClearSearch} size="sm">
|
||||||
</ActionIcon>
|
<TbX size={16} />
|
||||||
</Tooltip>
|
</ActionIcon>
|
||||||
) : null
|
</Tooltip>
|
||||||
}
|
) : null
|
||||||
value={search}
|
}
|
||||||
onChange={(e) => handleSearchChange(e.currentTarget.value)}
|
value={search}
|
||||||
radius="md"
|
onChange={(e) => setSearch(e.currentTarget.value)}
|
||||||
/>
|
radius="md"
|
||||||
|
/>
|
||||||
|
<Group gap="sm" wrap="nowrap">
|
||||||
|
<Select
|
||||||
|
size="sm"
|
||||||
|
placeholder="Status"
|
||||||
|
data={[
|
||||||
|
{ value: 'active', label: 'Active' },
|
||||||
|
{ value: 'inactive', label: 'Inactive' },
|
||||||
|
]}
|
||||||
|
value={filterStatus}
|
||||||
|
onChange={setFilterStatus}
|
||||||
|
radius="md"
|
||||||
|
clearable
|
||||||
|
style={{ flex: 1 }}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
size="sm"
|
||||||
|
placeholder="Role"
|
||||||
|
data={rolesOptions}
|
||||||
|
value={filterRole}
|
||||||
|
onChange={setFilterRole}
|
||||||
|
radius="md"
|
||||||
|
clearable
|
||||||
|
style={{ flex: 1 }}
|
||||||
|
/>
|
||||||
|
<Select
|
||||||
|
size="sm"
|
||||||
|
placeholder="Search village..."
|
||||||
|
searchable
|
||||||
|
onSearchChange={setFilterVillageSearch}
|
||||||
|
data={filterVillagesOptions}
|
||||||
|
value={filterVillageId}
|
||||||
|
onChange={setFilterVillageId}
|
||||||
|
radius="md"
|
||||||
|
clearable
|
||||||
|
style={{ flex: 1 }}
|
||||||
|
/>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
@@ -625,7 +676,7 @@ function UsersIndexPage() {
|
|||||||
<Stack align="center" gap="xs" py="xl">
|
<Stack align="center" gap="xs" py="xl">
|
||||||
<TbUsers size={32} style={{ opacity: 0.25 }} />
|
<TbUsers size={32} style={{ opacity: 0.25 }} />
|
||||||
<Text size="sm" c="dimmed">
|
<Text size="sm" c="dimmed">
|
||||||
{searchQuery ? 'No users match your search.' : 'No users found.'}
|
{searchQuery || filterStatus || filterRole || filterVillageId ? 'No users match your filters.' : 'No users found.'}
|
||||||
</Text>
|
</Text>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Paper>
|
</Paper>
|
||||||
@@ -646,11 +697,30 @@ function UsersIndexPage() {
|
|||||||
>
|
>
|
||||||
<Table.Thead>
|
<Table.Thead>
|
||||||
<Table.Tr>
|
<Table.Tr>
|
||||||
<Table.Th style={{ width: isMobile ? undefined : '28%' }}>User & ID</Table.Th>
|
{[
|
||||||
<Table.Th style={{ width: isMobile ? undefined : '25%' }}>Contact</Table.Th>
|
{ label: 'User & ID', col: 'name', width: '28%' },
|
||||||
<Table.Th style={{ width: isMobile ? undefined : '22%' }}>Organization</Table.Th>
|
{ label: 'Contact', col: null, width: '25%' },
|
||||||
<Table.Th style={{ width: isMobile ? undefined : '15%' }}>Role</Table.Th>
|
{ label: 'Organization', col: null, width: '22%' },
|
||||||
<Table.Th style={{ width: isMobile ? undefined : '10%' }}>Status</Table.Th>
|
{ label: 'Role', col: 'idUserRole', width: '15%' },
|
||||||
|
{ label: 'Status', col: 'isActive', width: '10%' },
|
||||||
|
].map(({ label, col, width }) => (
|
||||||
|
<Table.Th
|
||||||
|
key={label}
|
||||||
|
style={{ width: isMobile ? undefined : width, cursor: col ? 'pointer' : undefined, userSelect: 'none' }}
|
||||||
|
onClick={col ? () => handleSort(col) : undefined}
|
||||||
|
>
|
||||||
|
<Group gap={4} wrap="nowrap">
|
||||||
|
<span>{label}</span>
|
||||||
|
{col && (
|
||||||
|
sortBy === col
|
||||||
|
? sortDir === 'asc'
|
||||||
|
? <TbArrowUp size={13} />
|
||||||
|
: <TbArrowDown size={13} />
|
||||||
|
: <TbArrowsSort size={13} style={{ opacity: 0.35 }} />
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
</Table.Th>
|
||||||
|
))}
|
||||||
</Table.Tr>
|
</Table.Tr>
|
||||||
</Table.Thead>
|
</Table.Thead>
|
||||||
<Table.Tbody>
|
<Table.Tbody>
|
||||||
@@ -754,7 +824,7 @@ function UsersIndexPage() {
|
|||||||
</Paper>
|
</Paper>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{!isLoading && !error && response?.data?.totalPage > 0 && (
|
{!isLoading && !error && response?.data?.totalPage > 1 && (
|
||||||
<Group justify="center">
|
<Group justify="center">
|
||||||
<Pagination
|
<Pagination
|
||||||
value={page}
|
value={page}
|
||||||
|
|||||||
@@ -123,16 +123,44 @@ function ActivityChart({ villageId }: { villageId: string }) {
|
|||||||
dataKey="label"
|
dataKey="label"
|
||||||
series={[{ name: 'activity', color: '#2563EB' }]}
|
series={[{ name: 'activity', color: '#2563EB' }]}
|
||||||
curveType="monotone"
|
curveType="monotone"
|
||||||
withTooltip={true}
|
withTooltip
|
||||||
withDots={true}
|
withDots
|
||||||
withPointLabels={false}
|
withPointLabels={false}
|
||||||
|
tickLine="none"
|
||||||
|
gridAxis="x"
|
||||||
|
fillOpacity={0.4}
|
||||||
tooltipAnimationDuration={150}
|
tooltipAnimationDuration={150}
|
||||||
tooltipProps={{
|
tooltipProps={{
|
||||||
allowEscapeViewBox: { x: true, y: false },
|
content: ({ active, payload, label }: any) => {
|
||||||
|
if (!active || !payload?.length) return null
|
||||||
|
return (
|
||||||
|
<div style={{
|
||||||
|
backgroundColor: '#1A1B1E',
|
||||||
|
padding: '8px 12px',
|
||||||
|
borderRadius: '6px',
|
||||||
|
border: '1px solid #373A40',
|
||||||
|
boxShadow: '0 4px 12px rgba(0,0,0,0.5)',
|
||||||
|
pointerEvents: 'none',
|
||||||
|
whiteSpace: 'nowrap',
|
||||||
|
}}>
|
||||||
|
<div style={{ fontSize: '12px', fontWeight: 600, color: '#C1C2C5', marginBottom: '4px' }}>
|
||||||
|
{label}
|
||||||
|
</div>
|
||||||
|
<div style={{ fontSize: '11px', color: '#2563EB' }}>
|
||||||
|
Activity: <span style={{ fontWeight: 700 }}>{payload[0].value}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
activeDotProps={{
|
activeDotProps={{ r: 6, strokeWidth: 2 }}
|
||||||
r: 6,
|
styles={{
|
||||||
strokeWidth: 2,
|
root: {
|
||||||
|
'.recharts-area-curve': {
|
||||||
|
strokeWidth: 3,
|
||||||
|
filter: 'drop-shadow(0 4px 8px rgba(37, 99, 235, 0.3))',
|
||||||
|
},
|
||||||
|
},
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
Button,
|
Button,
|
||||||
Card,
|
Card,
|
||||||
Center,
|
Center,
|
||||||
|
CopyButton,
|
||||||
Container,
|
Container,
|
||||||
Divider,
|
Divider,
|
||||||
Group,
|
Group,
|
||||||
@@ -59,6 +60,8 @@ import {
|
|||||||
TbCode,
|
TbCode,
|
||||||
TbDatabase,
|
TbDatabase,
|
||||||
TbDots,
|
TbDots,
|
||||||
|
TbEye,
|
||||||
|
TbEyeOff,
|
||||||
TbFileText,
|
TbFileText,
|
||||||
TbKey,
|
TbKey,
|
||||||
TbLayoutDashboard,
|
TbLayoutDashboard,
|
||||||
@@ -1474,6 +1477,8 @@ interface AppEntry {
|
|||||||
id: string
|
id: string
|
||||||
name: string
|
name: string
|
||||||
urlApi: string | null
|
urlApi: string | null
|
||||||
|
apiKey: string
|
||||||
|
clientApiKey: string
|
||||||
status: string
|
status: string
|
||||||
active: boolean
|
active: boolean
|
||||||
hasClientApiKey: boolean
|
hasClientApiKey: boolean
|
||||||
@@ -1501,10 +1506,24 @@ function SettingsPanel() {
|
|||||||
const [keyOpened, { open: openKey, close: closeKey }] = useDisclosure(false)
|
const [keyOpened, { open: openKey, close: closeKey }] = useDisclosure(false)
|
||||||
const [generatedKey, setGeneratedKey] = useState('')
|
const [generatedKey, setGeneratedKey] = useState('')
|
||||||
const [keyCopied, setKeyCopied] = useState(false)
|
const [keyCopied, setKeyCopied] = useState(false)
|
||||||
|
const [generatedKeyVisible, setGeneratedKeyVisible] = useState(false)
|
||||||
|
const [addKeyVisible, setAddKeyVisible] = useState(false)
|
||||||
|
const [apiConfigKeyVisible, setApiConfigKeyVisible] = useState(false)
|
||||||
|
const [visibleAppKeys, setVisibleAppKeys] = useState<Set<string>>(new Set())
|
||||||
|
|
||||||
|
const toggleAppKeyVisibility = (appId: string) => {
|
||||||
|
setVisibleAppKeys((prev) => {
|
||||||
|
const next = new Set(prev)
|
||||||
|
if (next.has(appId)) next.delete(appId)
|
||||||
|
else next.add(appId)
|
||||||
|
return next
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const openApiModal = (app: AppEntry) => {
|
const openApiModal = (app: AppEntry) => {
|
||||||
setApiTarget(app)
|
setApiTarget(app)
|
||||||
setApiForm({ urlApi: app.urlApi ?? '', apiKey: '' })
|
setApiForm({ urlApi: app.urlApi ?? '', apiKey: '' })
|
||||||
|
setApiConfigKeyVisible(false)
|
||||||
openApi()
|
openApi()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1562,6 +1581,7 @@ function SettingsPanel() {
|
|||||||
qc.invalidateQueries({ queryKey: ['apps'] })
|
qc.invalidateQueries({ queryKey: ['apps'] })
|
||||||
setGeneratedKey(res.clientApiKey)
|
setGeneratedKey(res.clientApiKey)
|
||||||
setKeyCopied(false)
|
setKeyCopied(false)
|
||||||
|
setGeneratedKeyVisible(false)
|
||||||
openKey()
|
openKey()
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -1626,6 +1646,54 @@ function SettingsPanel() {
|
|||||||
: <Badge color="red" variant="dot" size="xs">No client key</Badge>
|
: <Badge color="red" variant="dot" size="xs">No client key</Badge>
|
||||||
}
|
}
|
||||||
</Group>
|
</Group>
|
||||||
|
{app.clientApiKey && (
|
||||||
|
<>
|
||||||
|
<Text size="xs" fw={500} c="gray" mt={4}>Client Key (untuk mobile app mengakses monitoring):</Text>
|
||||||
|
<Group gap={4} wrap="nowrap">
|
||||||
|
<Text size="xs" ff="monospace" c="dimmed" style={{ userSelect: visibleAppKeys.has(app.id) ? 'text' : 'none' }}>
|
||||||
|
{visibleAppKeys.has(app.id) ? app.clientApiKey : '•'.repeat(32)}
|
||||||
|
</Text>
|
||||||
|
<Tooltip label={visibleAppKeys.has(app.id) ? 'Sembunyikan' : 'Tampilkan'}>
|
||||||
|
<ActionIcon variant="subtle" size="xs" color="gray" onClick={() => toggleAppKeyVisibility(app.id)}>
|
||||||
|
{visibleAppKeys.has(app.id) ? <TbEyeOff size={12} /> : <TbEye size={12} />}
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
<CopyButton value={app.clientApiKey}>
|
||||||
|
{({ copy }) => (
|
||||||
|
<Tooltip label="Salin">
|
||||||
|
<ActionIcon variant="subtle" size="xs" color="gray" onClick={copy}>
|
||||||
|
<TbCopy size={12} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</CopyButton>
|
||||||
|
</Group>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{app.apiKey && (
|
||||||
|
<>
|
||||||
|
<Text size="xs" fw={500} c="gray" mt={4}>Server Key (untuk monitoring mengakses API external):</Text>
|
||||||
|
<Group gap={4} wrap="nowrap">
|
||||||
|
<Text size="xs" ff="monospace" c="dimmed" style={{ userSelect: visibleAppKeys.has(`server-${app.id}`) ? 'text' : 'none' }}>
|
||||||
|
{visibleAppKeys.has(`server-${app.id}`) ? app.apiKey : '•'.repeat(32)}
|
||||||
|
</Text>
|
||||||
|
<Tooltip label={visibleAppKeys.has(`server-${app.id}`) ? 'Sembunyikan' : 'Tampilkan'}>
|
||||||
|
<ActionIcon variant="subtle" size="xs" color="gray" onClick={() => toggleAppKeyVisibility(`server-${app.id}`)}>
|
||||||
|
{visibleAppKeys.has(`server-${app.id}`) ? <TbEyeOff size={12} /> : <TbEye size={12} />}
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
<CopyButton value={app.apiKey}>
|
||||||
|
{({ copy }) => (
|
||||||
|
<Tooltip label="Salin">
|
||||||
|
<ActionIcon variant="subtle" size="xs" color="gray" onClick={copy}>
|
||||||
|
<TbCopy size={12} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</CopyButton>
|
||||||
|
</Group>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</Box>
|
</Box>
|
||||||
</Group>
|
</Group>
|
||||||
<Group gap="xs" wrap="nowrap">
|
<Group gap="xs" wrap="nowrap">
|
||||||
@@ -1659,7 +1727,19 @@ function SettingsPanel() {
|
|||||||
<TextInput label="App ID" description="Unique slug used as identifier (e.g. desa-plus)" placeholder="my-app" value={newApp.id} onChange={(e) => setNewApp((p) => ({ ...p, id: e.target.value }))} required />
|
<TextInput label="App ID" description="Unique slug used as identifier (e.g. desa-plus)" placeholder="my-app" value={newApp.id} onChange={(e) => setNewApp((p) => ({ ...p, id: e.target.value }))} required />
|
||||||
<TextInput label="Name" placeholder="My Application" value={newApp.name} onChange={(e) => setNewApp((p) => ({ ...p, name: e.target.value }))} required />
|
<TextInput label="Name" placeholder="My Application" value={newApp.name} onChange={(e) => setNewApp((p) => ({ ...p, name: e.target.value }))} required />
|
||||||
<TextInput label="URL API" placeholder="https://api.example.com" value={newApp.urlApi} onChange={(e) => setNewApp((p) => ({ ...p, urlApi: e.target.value }))} />
|
<TextInput label="URL API" placeholder="https://api.example.com" value={newApp.urlApi} onChange={(e) => setNewApp((p) => ({ ...p, urlApi: e.target.value }))} />
|
||||||
<TextInput label="API Key" placeholder="secret-key" type="password" value={newApp.apiKey} onChange={(e) => setNewApp((p) => ({ ...p, apiKey: e.target.value }))} />
|
<TextInput
|
||||||
|
label="Server Key (API External)"
|
||||||
|
description="Key untuk monitoring mengakses API external app ini."
|
||||||
|
placeholder="secret-key"
|
||||||
|
type={addKeyVisible ? 'text' : 'password'}
|
||||||
|
value={newApp.apiKey}
|
||||||
|
onChange={(e) => setNewApp((p) => ({ ...p, apiKey: e.target.value }))}
|
||||||
|
rightSection={
|
||||||
|
<ActionIcon variant="subtle" size="sm" color="gray" onClick={() => setAddKeyVisible((v) => !v)}>
|
||||||
|
{addKeyVisible ? <TbEyeOff size={14} /> : <TbEye size={14} />}
|
||||||
|
</ActionIcon>
|
||||||
|
}
|
||||||
|
/>
|
||||||
<Group justify="flex-end" mt="xs">
|
<Group justify="flex-end" mt="xs">
|
||||||
<Button variant="subtle" color="gray" onClick={closeAdd}>Cancel</Button>
|
<Button variant="subtle" color="gray" onClick={closeAdd}>Cancel</Button>
|
||||||
<Button loading={createMutation.isPending} disabled={!newApp.id || !newApp.name} onClick={() => createMutation.mutate(newApp)}>Add</Button>
|
<Button loading={createMutation.isPending} disabled={!newApp.id || !newApp.name} onClick={() => createMutation.mutate(newApp)}>Add</Button>
|
||||||
@@ -1671,21 +1751,28 @@ function SettingsPanel() {
|
|||||||
<Modal opened={keyOpened} onClose={closeKey} title="Client API Key Generated" radius="md">
|
<Modal opened={keyOpened} onClose={closeKey} title="Client API Key Generated" radius="md">
|
||||||
<Stack gap="sm">
|
<Stack gap="sm">
|
||||||
<Text size="sm" c="dimmed">Copy this key now — it will not be shown again after you close this dialog.</Text>
|
<Text size="sm" c="dimmed">Copy this key now — it will not be shown again after you close this dialog.</Text>
|
||||||
<Box
|
<Group gap={4} wrap="nowrap" align="center">
|
||||||
p="sm"
|
<Box
|
||||||
style={{ background: 'var(--mantine-color-dark-6)', borderRadius: 6, fontFamily: 'monospace', fontSize: 13, wordBreak: 'break-all' }}
|
p="sm"
|
||||||
>
|
flex={1}
|
||||||
{generatedKey}
|
style={{ background: 'var(--mantine-color-dark-6)', borderRadius: 6, fontFamily: 'monospace', fontSize: 13, wordBreak: 'break-all', userSelect: generatedKeyVisible ? 'text' : 'none' }}
|
||||||
</Box>
|
|
||||||
<Group justify="flex-end">
|
|
||||||
<Button
|
|
||||||
variant="light"
|
|
||||||
color={keyCopied ? 'green' : 'blue'}
|
|
||||||
leftSection={<TbCopy size={14} />}
|
|
||||||
onClick={() => { navigator.clipboard.writeText(generatedKey); setKeyCopied(true) }}
|
|
||||||
>
|
>
|
||||||
{keyCopied ? 'Copied!' : 'Copy to Clipboard'}
|
{generatedKeyVisible ? generatedKey : '•'.repeat(48)}
|
||||||
</Button>
|
</Box>
|
||||||
|
<Tooltip label={generatedKeyVisible ? 'Sembunyikan' : 'Tampilkan'}>
|
||||||
|
<ActionIcon variant="subtle" color="gray" onClick={() => setGeneratedKeyVisible((v) => !v)}>
|
||||||
|
{generatedKeyVisible ? <TbEyeOff size={16} /> : <TbEye size={16} />}
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
</Group>
|
||||||
|
<Group justify="flex-end">
|
||||||
|
<CopyButton value={generatedKey}>
|
||||||
|
{({ copy }) => (
|
||||||
|
<Button variant="light" color={keyCopied ? 'green' : 'blue'} leftSection={<TbCopy size={14} />} onClick={() => { copy(); setKeyCopied(true) }}>
|
||||||
|
{keyCopied ? 'Copied!' : 'Copy to Clipboard'}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</CopyButton>
|
||||||
<Button variant="subtle" color="gray" onClick={closeKey}>Close</Button>
|
<Button variant="subtle" color="gray" onClick={closeKey}>Close</Button>
|
||||||
</Group>
|
</Group>
|
||||||
</Stack>
|
</Stack>
|
||||||
@@ -1695,14 +1782,26 @@ function SettingsPanel() {
|
|||||||
<Modal opened={apiOpened} onClose={closeApi} title={`API Config — ${apiTarget?.name}`} radius="md">
|
<Modal opened={apiOpened} onClose={closeApi} title={`API Config — ${apiTarget?.name}`} radius="md">
|
||||||
<Stack gap="sm">
|
<Stack gap="sm">
|
||||||
<TextInput label="URL API" description="Base URL for proxying requests to the external API." placeholder="https://api.example.com" value={apiForm.urlApi} onChange={(e) => setApiForm((p) => ({ ...p, urlApi: e.target.value }))} />
|
<TextInput label="URL API" description="Base URL for proxying requests to the external API." placeholder="https://api.example.com" value={apiForm.urlApi} onChange={(e) => setApiForm((p) => ({ ...p, urlApi: e.target.value }))} />
|
||||||
<TextInput label="API Key" description="Leave blank to keep the existing key unchanged." placeholder="Leave blank to keep unchanged" type="password" value={apiForm.apiKey} onChange={(e) => setApiForm((p) => ({ ...p, apiKey: e.target.value }))} />
|
<TextInput
|
||||||
|
label="Server Key (API External)"
|
||||||
|
description="Key untuk monitoring mengakses API external. Kosongkan untuk tetap menggunakan key yang ada."
|
||||||
|
placeholder="Kosongkan untuk tetap menggunakan key yang ada"
|
||||||
|
type={apiConfigKeyVisible ? 'text' : 'password'}
|
||||||
|
value={apiForm.apiKey}
|
||||||
|
onChange={(e) => setApiForm((p) => ({ ...p, apiKey: e.target.value }))}
|
||||||
|
rightSection={
|
||||||
|
<ActionIcon variant="subtle" size="sm" color="gray" onClick={() => setApiConfigKeyVisible((v) => !v)}>
|
||||||
|
{apiConfigKeyVisible ? <TbEyeOff size={14} /> : <TbEye size={14} />}
|
||||||
|
</ActionIcon>
|
||||||
|
}
|
||||||
|
/>
|
||||||
<Group justify="flex-end" mt="xs">
|
<Group justify="flex-end" mt="xs">
|
||||||
<Button variant="subtle" color="gray" onClick={closeApi}>Cancel</Button>
|
<Button variant="subtle" color="gray" onClick={closeApi}>Cancel</Button>
|
||||||
<Button
|
<Button
|
||||||
loading={apiMutation.isPending}
|
loading={apiMutation.isPending}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (!apiTarget) return
|
if (!apiTarget) return
|
||||||
const body: any = { urlApi: apiForm.urlApi }
|
const body: { urlApi: string; apiKey?: string } = { urlApi: apiForm.urlApi }
|
||||||
if (apiForm.apiKey) body.apiKey = apiForm.apiKey
|
if (apiForm.apiKey) body.apiKey = apiForm.apiKey
|
||||||
apiMutation.mutate({ id: apiTarget.id, body })
|
apiMutation.mutate({ id: apiTarget.id, body })
|
||||||
}}
|
}}
|
||||||
@@ -1734,6 +1833,16 @@ function ApiKeysPanel() {
|
|||||||
const [createdKey, setCreatedKey] = useState<string | null>(null)
|
const [createdKey, setCreatedKey] = useState<string | null>(null)
|
||||||
const [keyCopied, setKeyCopied] = useState(false)
|
const [keyCopied, setKeyCopied] = useState(false)
|
||||||
const [revealedOpened, { open: openRevealed, close: closeRevealed }] = useDisclosure(false)
|
const [revealedOpened, { open: openRevealed, close: closeRevealed }] = useDisclosure(false)
|
||||||
|
const [visibleKeys, setVisibleKeys] = useState<Set<string>>(new Set())
|
||||||
|
|
||||||
|
const toggleKeyVisibility = (keyId: string) => {
|
||||||
|
setVisibleKeys((prev) => {
|
||||||
|
const next = new Set(prev)
|
||||||
|
if (next.has(keyId)) next.delete(keyId)
|
||||||
|
else next.add(keyId)
|
||||||
|
return next
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
const { data, isLoading } = useQuery({
|
const { data, isLoading } = useQuery({
|
||||||
queryKey: ['admin', 'api-keys'],
|
queryKey: ['admin', 'api-keys'],
|
||||||
@@ -1837,7 +1946,30 @@ function ApiKeysPanel() {
|
|||||||
<Table.Tr key={k.id}>
|
<Table.Tr key={k.id}>
|
||||||
<Table.Td fw={500}>{k.name}</Table.Td>
|
<Table.Td fw={500}>{k.name}</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Text size="xs" ff="monospace" c="dimmed">{k.key}</Text>
|
<Group gap={4} wrap="nowrap">
|
||||||
|
<Text size="xs" ff="monospace" c="dimmed" style={{ userSelect: visibleKeys.has(k.id) ? 'text' : 'none' }}>
|
||||||
|
{visibleKeys.has(k.id) ? k.key : '•'.repeat(32)}
|
||||||
|
</Text>
|
||||||
|
<Tooltip label={visibleKeys.has(k.id) ? 'Sembunyikan' : 'Tampilkan'}>
|
||||||
|
<ActionIcon
|
||||||
|
variant="subtle"
|
||||||
|
size="xs"
|
||||||
|
color="gray"
|
||||||
|
onClick={() => toggleKeyVisibility(k.id)}
|
||||||
|
>
|
||||||
|
{visibleKeys.has(k.id) ? <TbEyeOff size={12} /> : <TbEye size={12} />}
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
<CopyButton value={k.key}>
|
||||||
|
{({ copy }) => (
|
||||||
|
<Tooltip label="Salin">
|
||||||
|
<ActionIcon variant="subtle" size="xs" color="gray" onClick={copy}>
|
||||||
|
<TbCopy size={12} />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
</CopyButton>
|
||||||
|
</Group>
|
||||||
</Table.Td>
|
</Table.Td>
|
||||||
<Table.Td>
|
<Table.Td>
|
||||||
<Badge color={k.isActive ? 'green' : 'gray'} variant="light">
|
<Badge color={k.isActive ? 'green' : 'gray'} variant="light">
|
||||||
|
|||||||
Reference in New Issue
Block a user