feat: connect kinerja divisi components to live database

New API Endpoints (src/api/division.ts):
- GET /api/division/discussions - Fetch recent discussions with sender info
- GET /api/division/documents/stats - Fetch document counts by type
- GET /api/division/activities/stats - Fetch activity status breakdown with percentages

Components Connected to Database:
- discussion-panel.tsx: Now fetches from /api/division/discussions
- document-chart.tsx: Now fetches from /api/division/documents/stats
- progress-chart.tsx: Now fetches from /api/division/activities/stats

Features Added:
- Loading states with Loader component
- Empty states with friendly messages
- Date formatting using date-fns with Indonesian locale
- Real-time data from database instead of hardcoded values
- Proper TypeScript typing for API responses

Files changed:
- src/api/division.ts: Added 3 new API endpoints
- src/components/kinerja-divisi/discussion-panel.tsx
- src/components/kinerja-divisi/document-chart.tsx
- src/components/kinerja-divisi/progress-chart.tsx

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
This commit is contained in:
2026-03-27 15:43:58 +08:00
parent b77822f2dd
commit 75c7bc249e
4 changed files with 390 additions and 141 deletions

View File

@@ -64,15 +64,36 @@ export const division = new Elysia({
},
)
.get(
"/metrics",
"/activities/stats",
async ({ set }) => {
try {
const metrics = await prisma.divisionMetric.findMany({
include: { division: true },
});
return { data: metrics };
// Get activity count by status
const [selesai, berjalan, tertunda, dibatalkan] = await Promise.all([
prisma.activity.count({ where: { status: "SELESAI" } }),
prisma.activity.count({ where: { status: "BERJALAN" } }),
prisma.activity.count({ where: { status: "TERTUNDA" } }),
prisma.activity.count({ where: { status: "DIBATALKAN" } }),
]);
const total = selesai + berjalan + tertunda + dibatalkan;
// Calculate percentages
const percentages = {
selesai: total > 0 ? (selesai / total) * 100 : 0,
berjalan: total > 0 ? (berjalan / total) * 100 : 0,
tertunda: total > 0 ? (tertunda / total) * 100 : 0,
dibatalkan: total > 0 ? (dibatalkan / total) * 100 : 0,
};
return {
data: {
total,
counts: { selesai, berjalan, tertunda, dibatalkan },
percentages,
},
};
} catch (error) {
logger.error({ error }, "Failed to fetch division metrics");
logger.error({ error }, "Failed to fetch activity stats");
set.status = 500;
return { error: "Internal Server Error" };
}
@@ -80,10 +101,117 @@ export const division = new Elysia({
{
response: {
200: t.Object({
data: t.Array(t.Any()),
data: t.Object({
total: t.Number(),
counts: t.Object({
selesai: t.Number(),
berjalan: t.Number(),
tertunda: t.Number(),
dibatalkan: t.Number(),
}),
percentages: t.Object({
selesai: t.Number(),
berjalan: t.Number(),
tertunda: t.Number(),
dibatalkan: t.Number(),
}),
}),
}),
500: t.Object({ error: t.String() }),
},
detail: { summary: "Get division performance metrics" },
detail: { summary: "Get activity statistics by status" },
},
)
.get(
"/documents/stats",
async ({ set }) => {
try {
// Group documents by type
const [gambarCount, dokumenCount] = await Promise.all([
prisma.document.count({ where: { type: "Gambar" } }),
prisma.document.count({ where: { type: "Dokumen" } }),
]);
return {
data: [
{ name: "Gambar", jumlah: gambarCount, color: "#FACC15" },
{ name: "Dokumen", jumlah: dokumenCount, color: "#22C55E" },
],
};
} catch (error) {
logger.error({ error }, "Failed to fetch document stats");
set.status = 500;
return { error: "Internal Server Error" };
}
},
{
response: {
200: t.Object({
data: t.Array(
t.Object({
name: t.String(),
jumlah: t.Number(),
color: t.String(),
}),
),
}),
500: t.Object({ error: t.String() }),
},
detail: { summary: "Get document statistics by type" },
},
)
.get(
"/discussions",
async ({ set }) => {
try {
// Get recent discussions with sender info
const discussions = await prisma.discussion.findMany({
where: { parentId: null }, // Only top-level discussions
include: {
sender: {
select: { name: true, email: true },
},
division: {
select: { name: true },
},
},
orderBy: { createdAt: "desc" },
take: 10,
});
// Format for frontend
const formattedDiscussions = discussions.map((d) => ({
id: d.id,
message: d.message,
sender: d.sender.name || d.sender.email,
date: d.createdAt.toISOString(),
division: d.division?.name || null,
isResolved: d.isResolved,
}));
return { data: formattedDiscussions };
} catch (error) {
logger.error({ error }, "Failed to fetch discussions");
set.status = 500;
return { error: "Internal Server Error" };
}
},
{
response: {
200: t.Object({
data: t.Array(
t.Object({
id: t.String(),
message: t.String(),
sender: t.String(),
date: t.String(),
division: t.Nullable(t.String()),
isResolved: t.Boolean(),
}),
),
}),
500: t.Object({ error: t.String() }),
},
detail: { summary: "Get recent discussions" },
},
);

View File

@@ -1,34 +1,51 @@
import { Card, Group, Stack, Text, useMantineColorScheme } from "@mantine/core";
import { Card, Group, Loader, Stack, Text, useMantineColorScheme } from "@mantine/core";
import { MessageCircle } from "lucide-react";
import { useEffect, useState } from "react";
import { apiClient } from "@/utils/api-client";
import { format } from "date-fns";
import { id } from "date-fns/locale";
interface DiscussionItem {
id: string;
message: string;
sender: string;
date: string;
division: string | null;
isResolved: boolean;
}
const discussions: DiscussionItem[] = [
{
message: "Kepada Pelayanan, mohon di cek...",
sender: "I.B Surya Prabhawa Manu",
date: "12 Apr 2025",
},
{
message: "Kepada staf perencanaan @suar...",
sender: "Ni Nyoman Yuliani",
date: "14 Jun 2025",
},
{
message: "ijin atau mohon kepada KBD sar...",
sender: "Ni Wayan Martini",
date: "12 Apr 2025",
},
];
export function DiscussionPanel() {
const { colorScheme } = useMantineColorScheme();
const dark = colorScheme === "dark";
const [discussions, setDiscussions] = useState<DiscussionItem[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchDiscussions() {
try {
const res = await apiClient.GET("/api/division/discussions");
if (res.data?.data) {
setDiscussions(res.data.data);
}
} catch (error) {
console.error("Failed to fetch discussions", error);
} finally {
setLoading(false);
}
}
fetchDiscussions();
}, []);
const formatDate = (dateString: string) => {
try {
return format(new Date(dateString), "dd MMM yyyy", { locale: id });
} catch {
return dateString;
}
};
return (
<Card
p="md"
@@ -50,36 +67,51 @@ export function DiscussionPanel() {
</Text>
</Group>
<Stack gap="sm">
{discussions.map((discussion) => (
<Card
key={`${discussion.sender}-${discussion.date}`}
p="sm"
radius="md"
withBorder
bg={dark ? "#334155" : "#F1F5F9"}
style={{
borderColor: dark ? "#334155" : "#F1F5F9",
}}
>
<Text
size="sm"
c={dark ? "white" : "#1E3A5F"}
fw={500}
mb="xs"
lineClamp={2}
{loading ? (
<Group justify="center" py="xl">
<Loader />
</Group>
) : discussions.length > 0 ? (
discussions.map((discussion) => (
<Card
key={discussion.id}
p="sm"
radius="md"
withBorder
bg={dark ? "#334155" : "#F1F5F9"}
style={{
borderColor: dark ? "#334155" : "#F1F5F9",
}}
>
{discussion.message}
</Text>
<Group justify="space-between">
<Text size="xs" c="dimmed">
{discussion.sender}
<Text
size="sm"
c={dark ? "white" : "#1E3A5F"}
fw={500}
mb="xs"
lineClamp={2}
>
{discussion.message}
</Text>
<Text size="xs" c="dimmed">
{discussion.date}
</Text>
</Group>
</Card>
))}
<Group justify="space-between">
<Text size="xs" c="dimmed">
{discussion.sender}
{discussion.division && (
<Text span size="xs" c="dimmed" ml="xs">
{discussion.division}
</Text>
)}
</Text>
<Text size="xs" c="dimmed">
{formatDate(discussion.date)}
</Text>
</Group>
</Card>
))
) : (
<Text size="sm" c="dimmed" ta="center" py="xl">
Tidak ada diskusi
</Text>
)}
</Stack>
</Card>
);

View File

@@ -1,4 +1,5 @@
import { Card, Text, useMantineColorScheme } from "@mantine/core";
import { Card, Group, Loader, Text, useMantineColorScheme } from "@mantine/core";
import { useEffect, useState } from "react";
import {
Bar,
BarChart,
@@ -9,16 +10,38 @@ import {
XAxis,
YAxis,
} from "recharts";
import { apiClient } from "@/utils/api-client";
const documentData = [
{ name: "Gambar", jumlah: 300, color: "#FACC15" },
{ name: "Dokumen", jumlah: 310, color: "#22C55E" },
];
interface DocumentData {
name: string;
jumlah: number;
color: string;
}
export function DocumentChart() {
const { colorScheme } = useMantineColorScheme();
const dark = colorScheme === "dark";
const [data, setData] = useState<DocumentData[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchDocumentStats() {
try {
const res = await apiClient.GET("/api/division/documents/stats");
if (res.data?.data) {
setData(res.data.data);
}
} catch (error) {
console.error("Failed to fetch document stats", error);
} finally {
setLoading(false);
}
}
fetchDocumentStats();
}, []);
return (
<Card
p="md"
@@ -36,39 +59,52 @@ export function DocumentChart() {
<Text size="sm" fw={600} c={dark ? "white" : "#1E3A5F"} mb="md">
Jumlah Dokumen
</Text>
<ResponsiveContainer width="100%" height={200}>
<BarChart data={documentData}>
<CartesianGrid
strokeDasharray="3 3"
vertical={false}
stroke={dark ? "#334155" : "#e5e7eb"}
/>
<XAxis
dataKey="name"
axisLine={false}
tickLine={false}
tick={{ fill: dark ? "#E2E8F0" : "#374151" }}
/>
<YAxis
axisLine={false}
tickLine={false}
tick={{ fill: dark ? "#E2E8F0" : "#374151" }}
/>
<Tooltip
contentStyle={{
backgroundColor: dark ? "#1E293B" : "white",
borderColor: dark ? "#334155" : "#e5e7eb",
borderRadius: "8px",
}}
labelStyle={{ color: dark ? "#E2E8F0" : "#374151" }}
/>
<Bar dataKey="jumlah" radius={[4, 4, 0, 0]}>
{documentData.map((entry) => (
<Cell key={`cell-${entry.name}`} fill={entry.color} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
{loading ? (
<Group justify="center" py="xl">
<Loader />
</Group>
) : data.length > 0 ? (
<ResponsiveContainer width="100%" height={200}>
<BarChart data={data}>
<CartesianGrid
strokeDasharray="3 3"
vertical={false}
stroke={dark ? "#334155" : "#e5e7eb"}
/>
<XAxis
dataKey="name"
axisLine={false}
tickLine={false}
tick={{ fill: dark ? "#E2E8F0" : "#374151" }}
/>
<YAxis
axisLine={false}
tickLine={false}
tick={{ fill: dark ? "#E2E8F0" : "#374151" }}
allowDecimals={false}
/>
<Tooltip
contentStyle={{
backgroundColor: dark ? "#1E293B" : "white",
borderColor: dark ? "#334155" : "#e5e7eb",
borderRadius: "8px",
}}
labelStyle={{ color: dark ? "#E2E8F0" : "#374151" }}
/>
<Bar dataKey="jumlah" radius={[4, 4, 0, 0]}>
{data.map((entry) => (
<Cell key={`cell-${entry.name}`} fill={entry.color} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
) : (
<Group justify="center" py="xl">
<Text size="sm" c="dimmed">
Tidak ada dokumen
</Text>
</Group>
)}
</Card>
);
}

View File

@@ -2,23 +2,68 @@ import {
Box,
Card,
Group,
Loader,
Stack,
Text,
useMantineColorScheme,
} from "@mantine/core";
import { useEffect, useState } from "react";
import { Cell, Pie, PieChart, ResponsiveContainer, Tooltip } from "recharts";
import { apiClient } from "@/utils/api-client";
const progressData = [
{ name: "Selesai", value: 83.33, color: "#22C55E" },
{ name: "Dikerjakan", value: 16.67, color: "#F59E0B" },
{ name: "Segera Dikerjakan", value: 0, color: "#3B82F6" },
{ name: "Dibatalkan", value: 0, color: "#EF4444" },
];
interface ProgressData {
name: string;
value: number;
color: string;
}
interface ActivityStats {
total: number;
counts: {
selesai: number;
berjalan: number;
tertunda: number;
dibatalkan: number;
};
percentages: {
selesai: number;
berjalan: number;
tertunda: number;
dibatalkan: number;
};
}
export function ProgressChart() {
const { colorScheme } = useMantineColorScheme();
const dark = colorScheme === "dark";
const [data, setData] = useState<ProgressData[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function fetchActivityStats() {
try {
const res = await apiClient.GET("/api/division/activities/stats");
if (res.data?.data) {
const stats = res.data.data as ActivityStats;
const chartData: ProgressData[] = [
{ name: "Selesai", value: stats.percentages.selesai, color: "#22C55E" },
{ name: "Dikerjakan", value: stats.percentages.berjalan, color: "#F59E0B" },
{ name: "Segera Dikerjakan", value: stats.percentages.tertunda, color: "#3B82F6" },
{ name: "Dibatalkan", value: stats.percentages.dibatalkan, color: "#EF4444" },
];
setData(chartData);
}
} catch (error) {
console.error("Failed to fetch activity stats", error);
} finally {
setLoading(false);
}
}
fetchActivityStats();
}, []);
return (
<Card
p="md"
@@ -36,49 +81,57 @@ export function ProgressChart() {
<Text size="sm" fw={600} c={dark ? "white" : "#1E3A5F"} mb="md">
Progres Kegiatan
</Text>
<ResponsiveContainer width="100%" height={200}>
<PieChart>
<Pie
data={progressData}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={80}
paddingAngle={2}
dataKey="value"
>
{progressData.map((entry) => (
<Cell key={`cell-${entry.name}`} fill={entry.color} />
))}
</Pie>
<Tooltip
contentStyle={{
backgroundColor: dark ? "#1E293B" : "white",
borderColor: dark ? "#334155" : "#e5e7eb",
borderRadius: "8px",
}}
/>
</PieChart>
</ResponsiveContainer>
<Stack gap="xs" mt="md">
{progressData.map((item) => (
<Group key={item.name} justify="space-between">
<Group gap="xs">
<Box
w={12}
h={12}
style={{ backgroundColor: item.color, borderRadius: 2 }}
{loading ? (
<Group justify="center" py="xl">
<Loader />
</Group>
) : (
<>
<ResponsiveContainer width="100%" height={200}>
<PieChart>
<Pie
data={data}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={80}
paddingAngle={2}
dataKey="value"
>
{data.map((entry) => (
<Cell key={`cell-${entry.name}`} fill={entry.color} />
))}
</Pie>
<Tooltip
contentStyle={{
backgroundColor: dark ? "#1E293B" : "white",
borderColor: dark ? "#334155" : "#e5e7eb",
borderRadius: "8px",
}}
/>
<Text size="sm" c={dark ? "white" : "gray.7"}>
{item.name}
</Text>
</Group>
<Text size="sm" fw={600} c={dark ? "white" : "gray.9"}>
{item.value.toFixed(2)}%
</Text>
</Group>
))}
</Stack>
</PieChart>
</ResponsiveContainer>
<Stack gap="xs" mt="md">
{data.map((item) => (
<Group key={item.name} justify="space-between">
<Group gap="xs">
<Box
w={12}
h={12}
style={{ backgroundColor: item.color, borderRadius: 2 }}
/>
<Text size="sm" c={dark ? "white" : "gray.7"}>
{item.name}
</Text>
</Group>
<Text size="sm" fw={600} c={dark ? "white" : "gray.9"}>
{item.value.toFixed(2)}%
</Text>
</Group>
))}
</Stack>
</>
)}
</Card>
);
}