260507_01_ENH: SafetyInspectionTotal, SafetyInspectionDivDetail 페이지 구현
This commit is contained in:
@@ -1,12 +1,14 @@
|
||||
'use client'
|
||||
|
||||
import {useLayoutFilter} from "@/components/layout/LayoutCategoryContext";
|
||||
import SafetyInspectionTotal from "./sub/SafetyInspectionTotal";
|
||||
import SafetyInspectionDivDetail from "./sub/SafetyInspectionDivDetail";
|
||||
|
||||
const SafetyInspectionPage = () => {
|
||||
const { selectedDiv } = useLayoutFilter();
|
||||
|
||||
return (
|
||||
<div>SafetyInspectionPage {selectedDiv}</div>
|
||||
selectedDiv === "-1" ? <SafetyInspectionTotal /> : <SafetyInspectionDivDetail selectedDiv={selectedDiv} />
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import DataTable from "@/components/table/DataTable";
|
||||
import type { DataColumn } from "@/components/table/types";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DIV_KEY_MAP } from "@/config/kfpaConfig";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { formatKoreanBaseDate } from "@/lib/utils";
|
||||
import { useWriteDivCommentMutation } from "@/query/admin";
|
||||
import { statisticsQueryKeys } from "@/query/key/keys";
|
||||
import { useDivDetailDataQuery } from "@/query/statistics";
|
||||
import type { CommentValue, DivDetailData } from "@/types/kfpa";
|
||||
import { Pencil, Save, X } from 'lucide-react';
|
||||
import SectionTitle from "@/components/common/SectionTitle";
|
||||
|
||||
export type SafetyInspectionDivDetailProps = {
|
||||
selectedDiv: string;
|
||||
};
|
||||
|
||||
type RankRow = {
|
||||
type: string;
|
||||
csi: number | null;
|
||||
rank: string;
|
||||
};
|
||||
|
||||
type CommentField = keyof CommentValue;
|
||||
|
||||
type CommentRow = {
|
||||
label: string;
|
||||
importance: string;
|
||||
field: CommentField;
|
||||
};
|
||||
|
||||
type CommentTableRow = CommentRow & Record<string, unknown>;
|
||||
|
||||
const DEFAULT_COMMENT_COLUMNS = [
|
||||
{ key: "performance25", label: "25년 성과" },
|
||||
{ key: "plan26", label: "26년 업무계획" },
|
||||
{ key: "performance26", label: "26년 업무계획 진행률 및 성과" },
|
||||
];
|
||||
|
||||
const COMMENT_ROWS: CommentRow[] = [
|
||||
{ label: "고객 직접 체감", importance: "★★★", field: "directExperience" },
|
||||
{ label: "고객 간접 체감", importance: "★★", field: "indirectExperience" },
|
||||
{ label: "내부역량 강화 등", importance: "★", field: "capability" },
|
||||
];
|
||||
|
||||
const RANK_ROWS = [
|
||||
{ key: "90", label: "일반" },
|
||||
{ key: "4", label: "공장" },
|
||||
{ key: "12", label: "아파트" },
|
||||
];
|
||||
|
||||
const getSelectedDetail = (data: Record<string, DivDetailData> | undefined, selectedDiv: string) => {
|
||||
if (!data) return undefined;
|
||||
return data[selectedDiv] ?? Object.values(data)[0];
|
||||
};
|
||||
|
||||
const getCommentColumns = (commentValues?: Record<string, CommentValue>) => {
|
||||
const keys = Object.keys(commentValues ?? {});
|
||||
const selectedKeys = keys.length > 0 ? keys : DEFAULT_COMMENT_COLUMNS.map((column) => column.key);
|
||||
|
||||
return selectedKeys.map((key, index) => ({
|
||||
key,
|
||||
label: DEFAULT_COMMENT_COLUMNS[index]?.label ?? key,
|
||||
}));
|
||||
};
|
||||
|
||||
const createEmptyCommentValue = (): CommentValue => ({
|
||||
directExperience: "",
|
||||
indirectExperience: "",
|
||||
capability: "",
|
||||
});
|
||||
|
||||
const createDraft = (columns: Array<{ key: string }>, source?: Record<string, CommentValue>) =>
|
||||
columns.reduce<Record<string, CommentValue>>((acc, column) => {
|
||||
acc[column.key] = {
|
||||
...createEmptyCommentValue(),
|
||||
...(source?.[column.key] ?? {}),
|
||||
};
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
const SafetyInspectionDivDetail = ({ selectedDiv }: SafetyInspectionDivDetailProps) => {
|
||||
const { auth } = useAuth();
|
||||
const queryClient = useQueryClient();
|
||||
const { data, isLoading, isError } = useDivDetailDataQuery(selectedDiv, selectedDiv !== "-1");
|
||||
const writeMutation = useWriteDivCommentMutation();
|
||||
|
||||
const detail = useMemo(() => getSelectedDetail(data, selectedDiv), [data, selectedDiv]);
|
||||
const commentColumns = useMemo(() => getCommentColumns(detail?.commentValues), [detail?.commentValues]);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [draft, setDraft] = useState<Record<string, CommentValue>>(() =>
|
||||
createDraft(commentColumns, detail?.commentValues)
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setIsEditing(false);
|
||||
setDraft(createDraft(commentColumns, detail?.commentValues));
|
||||
}, [commentColumns, detail?.commentValues, selectedDiv]);
|
||||
|
||||
const baseDateLabel = useMemo(() => formatKoreanBaseDate(), []);
|
||||
const isAuthenticated = auth.user != null;
|
||||
|
||||
const rankRows: RankRow[] = useMemo(() => {
|
||||
const ranks = detail?.csiRanks ?? {};
|
||||
return RANK_ROWS.map(({ key, label }) => ({
|
||||
type: label,
|
||||
csi: ranks[key]?.csi ?? 0,
|
||||
rank: `${ranks[key]?.divRank ?? 0}/6`,
|
||||
}));
|
||||
}, [detail?.csiRanks]);
|
||||
|
||||
const rankColumns: DataColumn<RankRow>[] = useMemo(
|
||||
() => [
|
||||
{ key: "type", header: "물건 유형", align: "center" },
|
||||
{
|
||||
key: "csi",
|
||||
header: "고객만족지수",
|
||||
align: "center",
|
||||
render: (row) => (typeof row.csi === "number" ? row.csi.toFixed(2) : "-"),
|
||||
},
|
||||
{ key: "rank", header: "지역본부순위", align: "center" },
|
||||
],
|
||||
[]
|
||||
);
|
||||
|
||||
const updateDraft = (columnKey: string, field: CommentField, value: string) => {
|
||||
setDraft((prev) => ({
|
||||
...prev,
|
||||
[columnKey]: {
|
||||
...createEmptyCommentValue(),
|
||||
...(prev[columnKey] ?? {}),
|
||||
[field]: value,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const commentRows: CommentTableRow[] = useMemo(
|
||||
() =>
|
||||
COMMENT_ROWS.map((row) => ({
|
||||
...row,
|
||||
...Object.fromEntries(commentColumns.map((column) => [column.key, draft[column.key]?.[row.field] ?? ""])),
|
||||
})),
|
||||
[commentColumns, draft]
|
||||
);
|
||||
|
||||
const commentTableColumns: DataColumn<CommentTableRow>[] = useMemo(
|
||||
() => [
|
||||
{
|
||||
key: "label",
|
||||
header: "",
|
||||
rowHead: true,
|
||||
width: 170,
|
||||
align: "center",
|
||||
cellClassName: "bg-red-50 text-center font-bold",
|
||||
},
|
||||
{
|
||||
key: "importance",
|
||||
header: "중요도(난이도)",
|
||||
width: 110,
|
||||
align: "center",
|
||||
cellClassName: "font-bold",
|
||||
},
|
||||
...commentColumns.map<DataColumn<CommentTableRow>>((column) => ({
|
||||
key: column.key,
|
||||
header: column.label,
|
||||
align: "left",
|
||||
cellClassName: "align-top",
|
||||
render: (row) => {
|
||||
const value = String(draft[column.key]?.[row.field] ?? "");
|
||||
|
||||
if (!isEditing) {
|
||||
return <div className="min-h-24 whitespace-pre-wrap text-left">{value || "-"}</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<textarea
|
||||
className="min-h-28 w-full resize-y border border-gray-300 bg-background p-2 text-sm outline-none focus:border-primary"
|
||||
value={value}
|
||||
onChange={(event) => updateDraft(column.key, row.field, event.target.value)}
|
||||
/>
|
||||
);
|
||||
},
|
||||
})),
|
||||
],
|
||||
[commentColumns, draft, isEditing]
|
||||
);
|
||||
|
||||
const handleSave = () => {
|
||||
writeMutation.mutate(
|
||||
{
|
||||
divId: Number(selectedDiv),
|
||||
commentValues: draft,
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
setIsEditing(false);
|
||||
queryClient.invalidateQueries({ queryKey: statisticsQueryKeys.divDetail(selectedDiv) });
|
||||
toast.success("저장되었습니다.");
|
||||
},
|
||||
onError: () => {
|
||||
toast.error("저장하지 못했습니다.");
|
||||
},
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
const handleEditToggle = () => {
|
||||
if (!isAuthenticated) return;
|
||||
if (isEditing) {
|
||||
handleSave();
|
||||
return;
|
||||
}
|
||||
setIsEditing(true);
|
||||
};
|
||||
|
||||
const handleCancelEdit = () => {
|
||||
setDraft(createDraft(commentColumns, detail?.commentValues));
|
||||
setIsEditing(false);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="content-text-sm text-muted-foreground">데이터를 불러오는 중입니다.</div>;
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return <div className="content-text-sm text-destructive">지역본부 상세 데이터를 불러오지 못했습니다.</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-8">
|
||||
<div>
|
||||
<SectionTitle title={DIV_KEY_MAP[selectedDiv] ?? ""} />
|
||||
|
||||
<div className="mt-6 mb-2 max-w-[360px]">
|
||||
<div className="mb-2 text-right content-text-base">{baseDateLabel}</div>
|
||||
<DataTable
|
||||
columns={rankColumns}
|
||||
rows={rankRows}
|
||||
tableClassName="kfpa-table"
|
||||
wrapperClassName="w-full"
|
||||
minWidth={360}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{isAuthenticated && (
|
||||
<div className="mb-2 flex justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
className={
|
||||
isEditing
|
||||
? "gap-2 border border-transparent bg-red-600 text-white w-25 shadow-sm hover:bg-red-500 hover:text-white"
|
||||
: "gap-2 border border-transparent bg-green-600 text-white w-25 shadow-sm hover:bg-green-500 hover:text-white"
|
||||
}
|
||||
disabled={writeMutation.isPending}
|
||||
onClick={handleEditToggle}
|
||||
>
|
||||
{isEditing ? (
|
||||
<>
|
||||
<Save className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">{"저장"}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Pencil className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">{"수정"}</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{isEditing && (
|
||||
<Button
|
||||
type="button"
|
||||
className="gap-2 border border-transparent bg-black-400 text-white w-25 shadow-sm hover:bg-black-200 hover:text-white"
|
||||
disabled={writeMutation.isPending}
|
||||
onClick={handleCancelEdit}
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
<span className="hidden sm:inline">{"취소"}</span>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DataTable
|
||||
columns={commentTableColumns}
|
||||
rows={commentRows}
|
||||
tableClassName="kfpa-table"
|
||||
subheadRowClassName="bg-red-50"
|
||||
wrapperClassName="w-full"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SafetyInspectionDivDetail;
|
||||
@@ -0,0 +1,262 @@
|
||||
"use client";
|
||||
|
||||
import { type ReactNode, useMemo } from "react";
|
||||
import type { ChartData } from "@/components/chart/types";
|
||||
import TopChartTable from "@/components/combo/TopChartTable";
|
||||
import type { TopChartTableRow } from "@/components/combo/types";
|
||||
import { formatKoreanBaseDate } from "@/lib/utils";
|
||||
import { useCsiDataQuery } from "@/query/statistics";
|
||||
import type { CsiData, CsiDataMap } from "@/types/kfpa";
|
||||
import VerticalBar from "@/components/chart/VerticalBar";
|
||||
import {SignStyle} from "@/components/table/types";
|
||||
import {GAP_WORDING} from "@/const/kfpa.const";
|
||||
|
||||
export const signStyleGapRow: SignStyle<TopChartTableRow> = {
|
||||
rowSelector: (row) => row.label === GAP_WORDING,
|
||||
display: "arrow",
|
||||
arrowWithNumber: true,
|
||||
paint: "text",
|
||||
};
|
||||
|
||||
const DIV_COLUMNS = [
|
||||
{ key: "-1", label: "전체" },
|
||||
{ key: "1", label: "서울" },
|
||||
{ key: "2", label: "경기" },
|
||||
{ key: "3", label: "부산" },
|
||||
{ key: "4", label: "대구" },
|
||||
{ key: "5", label: "대전" },
|
||||
{ key: "6", label: "광주" },
|
||||
] as const;
|
||||
|
||||
const METRICS: Array<{
|
||||
key: keyof Omit<CsiData, "wave">;
|
||||
label: ReactNode;
|
||||
group?: "direct" | "indirect";
|
||||
}> = [
|
||||
{ key: "csi", label: "고객만족지수(CSI)" },
|
||||
{
|
||||
key: "safeHelp",
|
||||
label: (
|
||||
<>
|
||||
① 현장 안전점검이
|
||||
<br />
|
||||
도움되는 정도
|
||||
</>
|
||||
),
|
||||
group: "direct",
|
||||
},
|
||||
{
|
||||
key: "recHelp",
|
||||
label: (
|
||||
<>
|
||||
② 위험 개선 권고사항이
|
||||
<br />
|
||||
도움되는 정도
|
||||
</>
|
||||
),
|
||||
group: "direct",
|
||||
},
|
||||
{ key: "staffProf", label: "③ 점검직원 전문성", group: "indirect" },
|
||||
{ key: "staffAtt", label: "④ 점검직원 태도", group: "indirect" },
|
||||
];
|
||||
|
||||
const getWaveLabel = (wave: number) => {
|
||||
const text = String(wave);
|
||||
return `${wave >= 100 ? text.slice(-2) : text}년`;
|
||||
};
|
||||
|
||||
const getDataByWave = (dataMap: CsiDataMap | undefined, divKey: string, wave: number) =>
|
||||
dataMap?.[divKey]?.find((item) => item.wave === wave);
|
||||
|
||||
const getMetricValue = (
|
||||
dataMap: CsiDataMap | undefined,
|
||||
divKey: string,
|
||||
wave: number,
|
||||
metricKey: keyof Omit<CsiData, "wave">
|
||||
) => getDataByWave(dataMap, divKey, wave)?.[metricKey] ?? null;
|
||||
|
||||
const getGapValue = (
|
||||
dataMap: CsiDataMap | undefined,
|
||||
divKey: string,
|
||||
previousWave: number,
|
||||
currentWave: number,
|
||||
metricKey: keyof Omit<CsiData, "wave">
|
||||
) => {
|
||||
const previousValue = getMetricValue(dataMap, divKey, previousWave, metricKey);
|
||||
const currentValue = getMetricValue(dataMap, divKey, currentWave, metricKey);
|
||||
|
||||
if (previousValue == null || currentValue == null) return null;
|
||||
return currentValue - previousValue;
|
||||
};
|
||||
|
||||
const getPreAppendCells = (
|
||||
metric: (typeof METRICS)[number],
|
||||
metricIndex: number,
|
||||
waveIndex: number,
|
||||
rowCountPerMetric: number
|
||||
): TopChartTableRow["preAppendCells"] => {
|
||||
if (waveIndex !== 0) return undefined;
|
||||
|
||||
if (metric.key === "csi") {
|
||||
return [
|
||||
{
|
||||
content: "고객만족지수(CSI)",
|
||||
colSpan: 2,
|
||||
rowSpan: rowCountPerMetric,
|
||||
width: 240,
|
||||
className: "bg-red-100 text-center align-middle font-bold content-text-base",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const cells: TopChartTableRow["preAppendCells"] = [];
|
||||
|
||||
if (metric.group === "direct" && metricIndex === 1) {
|
||||
cells.push({
|
||||
content: "직접 요소",
|
||||
rowSpan: rowCountPerMetric * 2,
|
||||
width: 60,
|
||||
className: "bg-red-50 text-center align-middle font-bold content-text-base",
|
||||
});
|
||||
}
|
||||
|
||||
if (metric.group === "indirect" && metricIndex === 3) {
|
||||
cells.push({
|
||||
content: "간접 요소",
|
||||
rowSpan: rowCountPerMetric * 2,
|
||||
width: 60,
|
||||
className: "bg-green-200 text-center align-middle font-bold content-text-base",
|
||||
});
|
||||
}
|
||||
|
||||
cells.push({
|
||||
content: metric.label,
|
||||
rowSpan: rowCountPerMetric,
|
||||
width: 170,
|
||||
className:
|
||||
metric.group === "indirect"
|
||||
? "bg-green-200 text-left align-middle font-bold content-text-base"
|
||||
: "bg-red-50 text-left align-middle font-bold content-text-base",
|
||||
});
|
||||
|
||||
return cells;
|
||||
};
|
||||
|
||||
const SafetyInspectionTotal = () => {
|
||||
const { data, isLoading, isError } = useCsiDataQuery();
|
||||
const baseDateLabel = useMemo(() => formatKoreanBaseDate(), []);
|
||||
|
||||
const { categories, rows, verticalChartData } = useMemo(() => {
|
||||
const waves = Array.from(
|
||||
new Set(
|
||||
Object.values(data ?? {})
|
||||
.flat()
|
||||
.map((item) => item.wave)
|
||||
.filter((wave) => Number.isFinite(wave))
|
||||
)
|
||||
).sort((a, b) => a - b);
|
||||
|
||||
const latestWave = waves[waves.length - 1];
|
||||
const selectedWaves = latestWave == null ? [] : [latestWave - 1, latestWave];
|
||||
const categories = DIV_COLUMNS.map((div) => div.label);
|
||||
|
||||
const rows: TopChartTableRow[] =
|
||||
selectedWaves.length === 0
|
||||
? []
|
||||
: METRICS.flatMap((metric, metricIndex) =>
|
||||
[
|
||||
{
|
||||
label: GAP_WORDING,
|
||||
values: DIV_COLUMNS.map((div) =>
|
||||
getGapValue(data, div.key, selectedWaves[0], selectedWaves[1], metric.key)
|
||||
),
|
||||
},
|
||||
...selectedWaves.map((wave) => ({
|
||||
label: getWaveLabel(wave),
|
||||
values: DIV_COLUMNS.map((div) => getMetricValue(data, div.key, wave, metric.key)),
|
||||
})),
|
||||
].map((row, rowIndex) => ({
|
||||
...row,
|
||||
preAppendCells: getPreAppendCells(metric, metricIndex, rowIndex, selectedWaves.length + 1),
|
||||
labelClassName:
|
||||
metric.key === "csi"
|
||||
? "bg-red-100 text-center font-bold"
|
||||
: metric.group === "indirect"
|
||||
? "bg-green-200 text-center font-bold"
|
||||
: metric.group === "direct"
|
||||
? "bg-red-50 text-center font-bold"
|
||||
: "text-center font-bold",
|
||||
labelWidth: 90,
|
||||
}))
|
||||
);
|
||||
|
||||
const verticalChartData: ChartData = {
|
||||
categories,
|
||||
series: selectedWaves.map((wave) => ({
|
||||
name: getWaveLabel(wave),
|
||||
data: DIV_COLUMNS.map((div) => getDataByWave(data, div.key, wave)?.csi ?? null),
|
||||
})),
|
||||
};
|
||||
|
||||
return {
|
||||
categories,
|
||||
rows,
|
||||
verticalChartData,
|
||||
};
|
||||
}, [data]);
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="content-text-sm text-muted-foreground">데이터를 불러오는 중입니다.</div>;
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return <div className="content-text-sm text-destructive">고객만족도 데이터를 불러오지 못했습니다.</div>;
|
||||
}
|
||||
|
||||
if (rows.length === 0) {
|
||||
return <div className="content-text-sm text-muted-foreground">표시할 고객만족도 데이터가 없습니다.</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<TopChartTable
|
||||
title="안전점검 특관관계자 만족도조사"
|
||||
categories={categories}
|
||||
rows={rows}
|
||||
subLabelHeader={baseDateLabel}
|
||||
minWidth={1120}
|
||||
chartHeight={260}
|
||||
chart={
|
||||
<VerticalBar
|
||||
data={verticalChartData}
|
||||
height="100%"
|
||||
paletteVarNames={["--chart-5", "--chart-7"]}
|
||||
valueFormatter={(value) => value.toFixed(2)}
|
||||
barMaxWidth={30}
|
||||
showFocusLabel="all"
|
||||
labelOptions={{ position: "top", distance: 4 }}
|
||||
grid={{ left: 0, right: 0, top: 40, bottom: 5 }}
|
||||
xAxis={{
|
||||
type: "category",
|
||||
data: categories,
|
||||
axisLabel: { show: false },
|
||||
axisTick: { show: false },
|
||||
axisLine: { show: false },
|
||||
}}
|
||||
yAxis={{
|
||||
type: "value",
|
||||
min: 0,
|
||||
max: 5,
|
||||
axisLabel: { show: false },
|
||||
axisTick: { show: false },
|
||||
axisLine: { show: false },
|
||||
splitLine: { show: false },
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SafetyInspectionTotal;
|
||||
35
src/app/api/admin/[[...slug]]/route.ts
Normal file
35
src/app/api/admin/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {createBackApi} from "@/lib/server-api";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {RequestWriteDivComment} from "@/types/kfpa";
|
||||
import {RouteContext} from "@/types/common";
|
||||
|
||||
export const PATCH = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if(action === "div-comment") {
|
||||
const body = (await req.json().catch(() => null)) as RequestWriteDivComment;
|
||||
if (!body) {
|
||||
return NextResponse.json(
|
||||
{ message: "요청 바디가 없습니다." },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const result = await backApi.patch<boolean>("/admin/div-comment", body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
|
||||
} catch (error : unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
}
|
||||
30
src/app/api/statistics/[[...slug]]/route.ts
Normal file
30
src/app/api/statistics/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {createBackApi} from "@/lib/server-api";
|
||||
import {CsiDataMap, DivDetailDataMap} from "@/types/kfpa";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if(action === "csi") {
|
||||
const result = await backApi.get<CsiDataMap>("/statistics/csi");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
else if(action === "div-detail" && slug.length === 2) {
|
||||
const result = await backApi.get<DivDetailDataMap>(`/statistics/div-detail/${slug[1]}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
|
||||
} catch (error : unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,12 @@
|
||||
/* =============================
|
||||
Brand Core
|
||||
============================= */
|
||||
--kfpa-black: #231f20;
|
||||
--kfpa-black-600: #231f20;
|
||||
--kfpa-black-500: #3c3839;
|
||||
--kfpa-black-400: #555152;
|
||||
--kfpa-black-300: #7b7879;
|
||||
--kfpa-black-200: #a7a4a5;
|
||||
--kfpa-black-100: #d4d2d3;
|
||||
|
||||
--kfpa-gray-600: #d1d2d2;
|
||||
--kfpa-gray-500: #dcdddd;
|
||||
@@ -345,7 +350,12 @@
|
||||
.border-border { border-color: var(--border); }
|
||||
|
||||
/* KFPA neutral scale */
|
||||
.bg-black { background-color: var(--kfpa-black) !important; }
|
||||
.bg-black-600 { background-color: var(--kfpa-black-600) !important; }
|
||||
.bg-black-500 { background-color: var(--kfpa-black-500) !important; }
|
||||
.bg-black-400 { background-color: var(--kfpa-black-400) !important; }
|
||||
.bg-black-300 { background-color: var(--kfpa-black-300) !important; }
|
||||
.bg-black-200 { background-color: var(--kfpa-black-200) !important; }
|
||||
.bg-black-100 { background-color: var(--kfpa-black-100) !important; }
|
||||
|
||||
.bg-gray-600 { background-color: var(--kfpa-gray-600) !important; }
|
||||
.bg-gray-500 { background-color: var(--kfpa-gray-500) !important; }
|
||||
@@ -361,6 +371,13 @@
|
||||
.border-gray-200 { border-color: var(--kfpa-gray-200) !important; }
|
||||
.border-gray-100 { border-color: var(--kfpa-gray-100) !important; }
|
||||
|
||||
.border-black-600 { border-color: var(--kfpa-black-600) !important; }
|
||||
.border-black-500 { border-color: var(--kfpa-black-500) !important; }
|
||||
.border-black-400 { border-color: var(--kfpa-black-400) !important; }
|
||||
.border-black-300 { border-color: var(--kfpa-black-300) !important; }
|
||||
.border-black-200 { border-color: var(--kfpa-black-200) !important; }
|
||||
.border-black-100 { border-color: var(--kfpa-black-100) !important; }
|
||||
|
||||
/* KFPA Red scale */
|
||||
.bg-red-600 { background-color: var(--kfpa-red-600) !important; }
|
||||
.bg-red-500 { background-color: var(--kfpa-red-500) !important; }
|
||||
@@ -405,10 +422,10 @@
|
||||
background-color: var(--background);
|
||||
background-image: linear-gradient(
|
||||
135deg,
|
||||
color-mix(in srgb, var(--kfpa-black) 12%, transparent) 0%,
|
||||
color-mix(in srgb, var(--kfpa-black-600) 12%, transparent) 0%,
|
||||
var(--background) 30%,
|
||||
var(--background) 70%,
|
||||
color-mix(in srgb, var(--kfpa-black) 12%, transparent) 100%
|
||||
color-mix(in srgb, var(--kfpa-black-600) 12%, transparent) 100%
|
||||
);
|
||||
}
|
||||
|
||||
@@ -424,10 +441,10 @@
|
||||
box-shadow: 4px 0 14px rgba(35, 31, 32, 0.06);
|
||||
}
|
||||
|
||||
.text-header-color { color: var(--kfpa-black); }
|
||||
.text-header-color { color: var(--kfpa-black-600); }
|
||||
|
||||
.text-header-primary {
|
||||
color: var(--kfpa-black);
|
||||
color: var(--kfpa-black-600);
|
||||
font-weight: 600;
|
||||
position: relative;
|
||||
padding-bottom: 4px;
|
||||
@@ -451,17 +468,17 @@
|
||||
}
|
||||
|
||||
.text-header-secondary-hover:hover {
|
||||
color: var(--kfpa-black) !important;
|
||||
color: var(--kfpa-black-600) !important;
|
||||
}
|
||||
|
||||
.bg-kfpa-main-body {
|
||||
background-color: var(--background);
|
||||
background-image: linear-gradient(
|
||||
135deg,
|
||||
color-mix(in srgb, var(--kfpa-black) 5%, transparent) 0%,
|
||||
color-mix(in srgb, var(--kfpa-black-600) 5%, transparent) 0%,
|
||||
var(--background) 30%,
|
||||
var(--background) 70%,
|
||||
color-mix(in srgb, var(--kfpa-black) 5%, transparent) 100%
|
||||
color-mix(in srgb, var(--kfpa-black-600) 5%, transparent) 100%
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -478,11 +495,18 @@
|
||||
table-layout: fixed;
|
||||
border: 0px !important;
|
||||
border-bottom: 3px solid var(--kfpa-gray-200) !important;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
.kfpa-table tbody,
|
||||
.kfpa-table tr {
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
.kfpa-table th,
|
||||
.kfpa-table td {
|
||||
border: 1px solid var(--kfpa-gray-200) !important;
|
||||
background-color: inherit;
|
||||
padding: 10px 12px;
|
||||
font-size: 13px;
|
||||
line-height: 1.15;
|
||||
@@ -491,15 +515,17 @@
|
||||
word-break: auto-phrase;
|
||||
}
|
||||
|
||||
.kfpa-table thead tr.kfpa-table__group th {
|
||||
background: var(--kfpa-gray-400);
|
||||
color: var(--kfpa-black);
|
||||
.kfpa-table thead tr.kfpa-table__group th,
|
||||
.kfpa-table thead tr.lg-table__group th {
|
||||
background-color: var(--kfpa-gray-400);
|
||||
color: var(--kfpa-black-600);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.kfpa-table thead tr.kfpa-table__subhead th {
|
||||
background: var(--kfpa-gray-600);
|
||||
color: var(--kfpa-black);
|
||||
.kfpa-table thead tr.kfpa-table__subhead th,
|
||||
.kfpa-table thead tr.lg-table__subhead th {
|
||||
background-color: var(--kfpa-gray-600);
|
||||
color: var(--kfpa-black-600);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
@@ -507,7 +533,7 @@
|
||||
text-align: left;
|
||||
font-weight: 700;
|
||||
color: var(--foreground);
|
||||
background: var(--background);
|
||||
background-color: inherit;
|
||||
word-wrap: break-word;
|
||||
word-break: auto-phrase;
|
||||
}
|
||||
@@ -556,7 +582,7 @@
|
||||
position: absolute;
|
||||
top: -16px;
|
||||
left: 16px;
|
||||
background: var(--kfpa-black);
|
||||
background: var(--kfpa-black-600);
|
||||
color: #fff;
|
||||
padding: 6px 16px;
|
||||
border-radius: 9999px;
|
||||
|
||||
99
src/components/chart/BaseEChart.tsx
Normal file
99
src/components/chart/BaseEChart.tsx
Normal file
@@ -0,0 +1,99 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import type { EChartsOption } from "echarts";
|
||||
|
||||
import {useResizeKey} from "@/hooks/useResize";
|
||||
import { useMemo } from "react";
|
||||
import {roundNumber} from "@/lib/utils";
|
||||
import {CHART_HEIGHTS} from "./chart.config";
|
||||
|
||||
|
||||
const ReactECharts = dynamic(() => import("echarts-for-react"), { ssr: false });
|
||||
|
||||
type BaseEChartProps = {
|
||||
option: EChartsOption;
|
||||
height?: number | string;
|
||||
className?: string; // wrapper용
|
||||
contentClassName?: string; // 안쪽 wrapper
|
||||
chartClassName?: string; // ReactECharts용
|
||||
/** echarts-for-react의 notMerge/lazyUpdate 옵션 필요 시 */
|
||||
notMerge?: boolean;
|
||||
lazyUpdate?: boolean;
|
||||
/** echarts-for-react 이벤트 바인딩(예: legendselectchanged) */
|
||||
onEvents?: Record<string, (params: unknown) => void>;
|
||||
};
|
||||
|
||||
const normalizeDataValue = (value: unknown): unknown => {
|
||||
if (typeof value === "number") {
|
||||
return roundNumber(value, 2);
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(normalizeDataValue);
|
||||
}
|
||||
|
||||
if (value && typeof value === "object" && "value" in value) {
|
||||
const item = value as { value: unknown };
|
||||
return {
|
||||
...(value as Record<string, unknown>),
|
||||
value: normalizeDataValue(item.value),
|
||||
};
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
|
||||
const normalizeSeries = (series?: EChartsOption["series"]): EChartsOption["series"] => {
|
||||
if (!series) return series;
|
||||
|
||||
const normalizeOne = (s: any) => {
|
||||
if (!s || !("data" in s) || !Array.isArray(s.data)) {
|
||||
return s;
|
||||
}
|
||||
|
||||
return {
|
||||
...s,
|
||||
data: s.data.map(normalizeDataValue),
|
||||
};
|
||||
};
|
||||
|
||||
return Array.isArray(series) ? series.map(normalizeOne) : normalizeOne(series);
|
||||
};
|
||||
const BaseEChart = ({
|
||||
option,
|
||||
height = CHART_HEIGHTS.DEFAULT,
|
||||
className,
|
||||
contentClassName,
|
||||
chartClassName,
|
||||
notMerge = true,
|
||||
lazyUpdate = false, //이거 켜져있으면 오류남 Cannot read properties of undefined (reading 'getRawIndex')
|
||||
onEvents,
|
||||
}: BaseEChartProps) => {
|
||||
const resizeKey = useResizeKey(150);
|
||||
|
||||
const normalizedOption = useMemo<EChartsOption>(() => {
|
||||
return {
|
||||
...option,
|
||||
series: normalizeSeries(option.series),
|
||||
};
|
||||
}, [option]);
|
||||
|
||||
return (
|
||||
<div className={className} style={{ display: "flex", flexDirection: "column", height: height }}>
|
||||
<div className={contentClassName} style={{ flex: 1, minHeight: 0 }}>
|
||||
<ReactECharts
|
||||
key={resizeKey}
|
||||
option={normalizedOption}
|
||||
className={chartClassName}
|
||||
style={{ width: "100%", height: "100%" }}
|
||||
notMerge={notMerge}
|
||||
lazyUpdate={lazyUpdate}
|
||||
onEvents={onEvents}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default BaseEChart;
|
||||
91
src/components/chart/HorizontalBar.tsx
Normal file
91
src/components/chart/HorizontalBar.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import type { EChartsOption } from "echarts";
|
||||
import {ChartData, ShowLabel} from "@/components/chart/types";
|
||||
import {ValueFormatter} from "@/components/table/types";
|
||||
import {buildLgPalette} from "@/components/chart/color";
|
||||
import {
|
||||
createCategoryAxis,
|
||||
createDefaultGrid,
|
||||
createDefaultLegend,
|
||||
createDefaultTooltip, createValueAxis
|
||||
} from "@/components/chart/chart-options";
|
||||
import {getIsShowLabel} from "@/components/chart/utill";
|
||||
import BaseEChart from "@/components/chart/BaseEChart";
|
||||
import {BAR_WIDTHS} from "@/components/chart/chart.config";
|
||||
|
||||
type Props = {
|
||||
data: ChartData;
|
||||
height?: number | string;
|
||||
className?: string;
|
||||
paletteVarNames?: string[];
|
||||
valueFormatter?: ValueFormatter;
|
||||
tooltip?: EChartsOption["tooltip"];
|
||||
legend?: EChartsOption["legend"];
|
||||
grid?: EChartsOption["grid"];
|
||||
xAxis?: EChartsOption["xAxis"];
|
||||
yAxis?: EChartsOption["yAxis"];
|
||||
barMaxWidth?: number;
|
||||
showFocusLabel?:ShowLabel;
|
||||
labelOptions?: {
|
||||
position?: "right" | "insideRight";
|
||||
color?: string;
|
||||
distance?: number;
|
||||
};
|
||||
};
|
||||
|
||||
const HorizontalBar = ({
|
||||
data,
|
||||
height,
|
||||
className,
|
||||
paletteVarNames,
|
||||
valueFormatter,
|
||||
tooltip,
|
||||
legend,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
barMaxWidth,
|
||||
showFocusLabel = "all",
|
||||
labelOptions,
|
||||
}: Props) => {
|
||||
const palette = useMemo(() => buildLgPalette(paletteVarNames), [paletteVarNames]);
|
||||
|
||||
const option: EChartsOption = useMemo(() => {
|
||||
const fmt = valueFormatter ?? ((v: number) => String(v));
|
||||
|
||||
return {
|
||||
color: palette,
|
||||
tooltip: tooltip ?? createDefaultTooltip(fmt),
|
||||
legend: legend ?? createDefaultLegend(),
|
||||
grid: grid ?? createDefaultGrid(),
|
||||
xAxis: xAxis ?? createValueAxis(),
|
||||
yAxis: yAxis ?? createCategoryAxis(data.categories),
|
||||
series: data.series.map((s, index) => {
|
||||
const showLabel = getIsShowLabel(showFocusLabel, index, data.series.length);
|
||||
|
||||
return {
|
||||
name: s.name,
|
||||
type: "bar",
|
||||
data: s.data,
|
||||
emphasis: { disabled: true },
|
||||
barMaxWidth: barMaxWidth ?? BAR_WIDTHS.DEFAULT,
|
||||
label: showLabel
|
||||
? {
|
||||
show: true,
|
||||
position: labelOptions?.position ?? "right",
|
||||
color: labelOptions?.color,
|
||||
distance: labelOptions?.distance,
|
||||
formatter: (p: any) => (p?.value ?? "") as any,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}, [data, palette, valueFormatter, tooltip, legend, grid, xAxis, yAxis, barMaxWidth, showFocusLabel, labelOptions]);
|
||||
|
||||
return <BaseEChart option={option} height={height} className={className} />;
|
||||
}
|
||||
|
||||
export default HorizontalBar;
|
||||
93
src/components/chart/VerticalBar.tsx
Normal file
93
src/components/chart/VerticalBar.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import type { EChartsOption } from "echarts";
|
||||
import {buildLgPalette} from "@/components/chart/color";
|
||||
import {
|
||||
createCategoryAxis,
|
||||
createDefaultGrid,
|
||||
createDefaultLegend,
|
||||
createDefaultTooltip, createValueAxis
|
||||
} from "@/components/chart/chart-options";
|
||||
import {getIsShowLabel} from "@/components/chart/utill";
|
||||
import BaseEChart from "@/components/chart/BaseEChart";
|
||||
import {BAR_WIDTHS} from "@/components/chart/chart.config";
|
||||
import {ChartData, ShowLabel} from "@/components/chart/types";
|
||||
import {ValueFormatter} from "@/components/table/types";
|
||||
|
||||
|
||||
type Props = {
|
||||
data: ChartData;
|
||||
height?: number | string;
|
||||
className?: string;
|
||||
paletteVarNames?: string[];
|
||||
valueFormatter?: ValueFormatter;
|
||||
|
||||
tooltip?: EChartsOption["tooltip"];
|
||||
legend?: EChartsOption["legend"];
|
||||
grid?: EChartsOption["grid"];
|
||||
xAxis?: EChartsOption["xAxis"];
|
||||
yAxis?: EChartsOption["yAxis"];
|
||||
barMaxWidth?: number;
|
||||
showFocusLabel?:ShowLabel;
|
||||
labelOptions?: {
|
||||
position?: "top" | "insideTop" | "right" | "insideRight";
|
||||
color?: string;
|
||||
distance?: number;
|
||||
};
|
||||
};
|
||||
|
||||
const VerticalBar = ({
|
||||
data,
|
||||
height,
|
||||
className,
|
||||
paletteVarNames,
|
||||
valueFormatter,
|
||||
tooltip,
|
||||
legend,
|
||||
grid,
|
||||
xAxis,
|
||||
yAxis,
|
||||
barMaxWidth,
|
||||
showFocusLabel = "all",
|
||||
labelOptions,
|
||||
}: Props) => {
|
||||
const palette = useMemo(() => buildLgPalette(paletteVarNames), [paletteVarNames]);
|
||||
|
||||
const option: EChartsOption = useMemo(() => {
|
||||
const fmt = valueFormatter ?? ((v: number) => String(v));
|
||||
|
||||
return {
|
||||
color: palette,
|
||||
tooltip: tooltip ?? createDefaultTooltip(fmt),
|
||||
legend: legend ?? createDefaultLegend(),
|
||||
grid: grid ?? createDefaultGrid(),
|
||||
xAxis: xAxis ?? createCategoryAxis(data.categories, false, { axisTick: { alignWithLabel: true } }),
|
||||
yAxis: yAxis ?? createValueAxis(),
|
||||
series: data.series.map((s, index) => {
|
||||
const showLabel = getIsShowLabel(showFocusLabel, index, data.series.length);
|
||||
|
||||
return {
|
||||
name: s.name,
|
||||
type: "bar",
|
||||
data: s.data,
|
||||
emphasis: { disabled: true },
|
||||
barMaxWidth: barMaxWidth ?? BAR_WIDTHS.DEFAULT,
|
||||
label: showLabel
|
||||
? {
|
||||
show: true,
|
||||
position: labelOptions?.position ?? "right",
|
||||
color: labelOptions?.color,
|
||||
distance: labelOptions?.distance,
|
||||
formatter: (p: any) => (typeof p?.value === "number" ? fmt(p.value) : (p?.value ?? "")) as any,
|
||||
}
|
||||
: undefined,
|
||||
}
|
||||
}),
|
||||
};
|
||||
}, [data, palette, valueFormatter, tooltip, legend, grid, xAxis, yAxis, barMaxWidth, showFocusLabel, labelOptions]);
|
||||
|
||||
return <BaseEChart option={option} height={height} className={className} />;
|
||||
}
|
||||
|
||||
export default VerticalBar;
|
||||
134
src/components/chart/color.ts
Normal file
134
src/components/chart/color.ts
Normal file
@@ -0,0 +1,134 @@
|
||||
type Rgb = { r: number; g: number; b: number };
|
||||
|
||||
const MAX_VAR_DEPTH = 10;
|
||||
|
||||
const getCssVarRaw = (varName: string) =>
|
||||
getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
|
||||
|
||||
const clamp = (value: number, min: number, max: number) =>
|
||||
Math.min(max, Math.max(min, value));
|
||||
|
||||
const getVarFallback = (varName: string) =>
|
||||
varName.startsWith("--") ? `var(${varName})` : varName;
|
||||
|
||||
/** Resolve var(--a) / var(--a, fallback) to its concrete CSS value. */
|
||||
export const resolveCssVarValue = (varName: string, depth = 0): string | null => {
|
||||
if (typeof window === "undefined") return null;
|
||||
if (depth > MAX_VAR_DEPTH) return null;
|
||||
|
||||
const raw = getCssVarRaw(varName);
|
||||
if (!raw) return null;
|
||||
|
||||
const m = raw.match(/^var\(\s*(--[^,\s)]+)\s*(?:,\s*([^)]+))?\s*\)$/);
|
||||
if (m) {
|
||||
const inner = m[1];
|
||||
const fallback = m[2]?.trim() ?? null;
|
||||
return resolveCssVarValue(inner, depth + 1) ?? fallback;
|
||||
}
|
||||
|
||||
return raw;
|
||||
};
|
||||
|
||||
export const resolveColorVar = (varName: string): string =>
|
||||
resolveCssVarValue(varName) ?? getVarFallback(varName);
|
||||
|
||||
const parseHexColor = (color: string): Rgb | null => {
|
||||
const hex = color.trim().replace(/^#/, "");
|
||||
|
||||
if (/^[\da-f]{3}$/i.test(hex)) {
|
||||
const [r, g, b] = hex.split("").map((v) => parseInt(v + v, 16));
|
||||
return { r, g, b };
|
||||
}
|
||||
|
||||
if (/^[\da-f]{6}$/i.test(hex)) {
|
||||
return {
|
||||
r: parseInt(hex.slice(0, 2), 16),
|
||||
g: parseInt(hex.slice(2, 4), 16),
|
||||
b: parseInt(hex.slice(4, 6), 16),
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const parseRgbChannel = (token: string): number | null => {
|
||||
const t = token.trim();
|
||||
const parsed = Number.parseFloat(t);
|
||||
if (!Number.isFinite(parsed)) return null;
|
||||
|
||||
if (t.endsWith("%")) return clamp((parsed / 100) * 255, 0, 255);
|
||||
return clamp(parsed, 0, 255);
|
||||
};
|
||||
|
||||
const parseRgbColor = (color: string): Rgb | null => {
|
||||
const m = color
|
||||
.trim()
|
||||
.match(/^rgba?\(\s*([^)]+?)\s*\)$/i);
|
||||
if (!m) return null;
|
||||
|
||||
const tokens = m[1].replace(/\s*\/\s*[^, ]+$/, "").split(/[,\s]+/).filter(Boolean);
|
||||
if (tokens.length < 3) return null;
|
||||
|
||||
const [r, g, b] = tokens.slice(0, 3).map(parseRgbChannel);
|
||||
if (r == null || g == null || b == null) return null;
|
||||
|
||||
return { r, g, b };
|
||||
};
|
||||
|
||||
const parseCssColor = (color: string): Rgb | null =>
|
||||
parseHexColor(color) ?? parseRgbColor(color);
|
||||
|
||||
const rgbCss = ({ r, g, b }: Rgb, alpha = 1) =>
|
||||
`rgb(${Math.round(r)} ${Math.round(g)} ${Math.round(b)} / ${alpha})`;
|
||||
|
||||
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
|
||||
|
||||
const buildPalette = (defaults: string[], varNames?: string[]): string[] =>
|
||||
(varNames ?? defaults).map(resolveColorVar);
|
||||
|
||||
export const buildLgPalette = (varNames?: string[]): string[] =>
|
||||
buildPalette(["--chart-1", "--chart-2", "--chart-3"], varNames);
|
||||
|
||||
export const buildLgStackPalette = (varNames?: string[]): string[] =>
|
||||
buildPalette(
|
||||
[
|
||||
"--chart-stack-1",
|
||||
"--chart-stack-2",
|
||||
"--chart-stack-3",
|
||||
"--chart-stack-4",
|
||||
"--chart-stack-5",
|
||||
"--chart-stack-6",
|
||||
"--chart-stack-7",
|
||||
"--chart-stack-8",
|
||||
"--chart-stack-9",
|
||||
"--chart-stack-10",
|
||||
"--chart-stack-11",
|
||||
"--chart-stack-12",
|
||||
"--chart-stack-13",
|
||||
],
|
||||
varNames
|
||||
);
|
||||
|
||||
/** Interpolate a row-level heatmap background between two CSS colors. */
|
||||
export const rowHeatColor = (
|
||||
value: number,
|
||||
rowMin: number,
|
||||
rowMax: number,
|
||||
low: string,
|
||||
high: string,
|
||||
alpha = 0.18
|
||||
) => {
|
||||
const lowRgb = parseCssColor(low);
|
||||
const highRgb = parseCssColor(high);
|
||||
if (!lowRgb || !highRgb) return high;
|
||||
|
||||
const t = rowMax === rowMin ? 0.5 : clamp((value - rowMin) / (rowMax - rowMin), 0, 1);
|
||||
return rgbCss(
|
||||
{
|
||||
r: lerp(lowRgb.r, highRgb.r, t),
|
||||
g: lerp(lowRgb.g, highRgb.g, t),
|
||||
b: lerp(lowRgb.b, highRgb.b, t),
|
||||
},
|
||||
alpha
|
||||
);
|
||||
};
|
||||
@@ -15,3 +15,5 @@ export type ChartData = {
|
||||
/** 시리즈(막대/스택 등) */
|
||||
series: ChartSeries[];
|
||||
};
|
||||
|
||||
export type ShowLabel = "none" | "all" | "last" | "first";
|
||||
22
src/components/chart/utill.ts
Normal file
22
src/components/chart/utill.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import {ShowLabel} from "@/components/chart/types";
|
||||
|
||||
|
||||
export const roundedRectIcon = (w: number, h: number, r: number) => {
|
||||
const rr = Math.max(0, Math.min(r, Math.min(w, h) / 2));
|
||||
// ECharts legend icon은 'path://' 지원
|
||||
return `path://M${rr},0 H${w - rr} Q${w},0 ${w},${rr} V${h - rr} Q${w},${h} ${w - rr},${h} H${rr} Q0,${h} 0,${h - rr} V${rr} Q0,0 ${rr},0 Z`;
|
||||
};
|
||||
|
||||
export const getIsShowLabel = (showFocusLabel:ShowLabel, i:number, arrayLength: number ):boolean => {
|
||||
let isShowLabel = false;
|
||||
|
||||
if (showFocusLabel === "all") {
|
||||
isShowLabel = true;
|
||||
} else if (showFocusLabel === "last") {
|
||||
isShowLabel = i === arrayLength - 1;
|
||||
} else if (showFocusLabel === "first") {
|
||||
isShowLabel = i === 0;
|
||||
}
|
||||
|
||||
return isShowLabel;
|
||||
}
|
||||
236
src/components/combo/TopChartTable.tsx
Normal file
236
src/components/combo/TopChartTable.tsx
Normal file
@@ -0,0 +1,236 @@
|
||||
"use client";
|
||||
|
||||
import React, { useMemo } from "react";
|
||||
import { cn, parseNumber } from "@/lib/utils";
|
||||
import BaseTableHeader from "../table/core/BaseTableHeader";
|
||||
import {
|
||||
formatSignedValue, getSignTextClass,
|
||||
resolveSignStyle,
|
||||
toRoundedNumber
|
||||
} from "../table/core/table-core.helpers";
|
||||
import {TopChartTablePreAppendCell, TopChartTablePreAppendCellConfig, TopChartTableRow} from "./types";
|
||||
import {ChartData} from "../chart/types";
|
||||
import {CHART_HEIGHTS, TABLE_DIMENSIONS} from "../chart/chart.config";
|
||||
import {SignStyle} from "@/components/table/types";
|
||||
|
||||
export type TopChartTableProps = {
|
||||
title?: string;
|
||||
categories: string[];
|
||||
rows: TopChartTableRow[];
|
||||
chart?:
|
||||
| React.ReactNode
|
||||
| ((ctx: {
|
||||
chartData: ChartData;
|
||||
}) => React.ReactNode);
|
||||
chartHeight?: number | string;
|
||||
minWidthPx?: number;
|
||||
minWidth?: number;
|
||||
subLabelHeader?: string;
|
||||
rowHeaderWidth?: number | string;
|
||||
tableClassName?: string;
|
||||
wrapperClassName?: string;
|
||||
signStyle?: SignStyle<TopChartTableRow>;
|
||||
};
|
||||
|
||||
const toCssSize = (value?: number | string) =>
|
||||
typeof value === "number" ? `${value}px` : value;
|
||||
|
||||
const isPreAppendCellConfig = (
|
||||
cell: TopChartTablePreAppendCell
|
||||
): cell is TopChartTablePreAppendCellConfig =>
|
||||
typeof cell === "object" &&
|
||||
cell !== null &&
|
||||
!Array.isArray(cell) &&
|
||||
"content" in cell;
|
||||
|
||||
const renderPreAppendCell = (cell: TopChartTablePreAppendCell, index: number) => {
|
||||
if (!isPreAppendCellConfig(cell)) {
|
||||
return <td key={`pre-append-${index}`}>{cell}</td>;
|
||||
}
|
||||
|
||||
return (
|
||||
<td
|
||||
key={`pre-append-${index}`}
|
||||
className={cell.className}
|
||||
colSpan={cell.colSpan}
|
||||
rowSpan={cell.rowSpan}
|
||||
style={{ width: toCssSize(cell.width), minWidth: toCssSize(cell.width) }}
|
||||
>
|
||||
{cell.content}
|
||||
</td>
|
||||
);
|
||||
};
|
||||
|
||||
const getLeadingColumnWidths = (rows: TopChartTableRow[], preAppendColumnCount: number) => {
|
||||
const widths = Array<string | undefined>(preAppendColumnCount).fill(undefined);
|
||||
|
||||
rows.forEach((row) => {
|
||||
let columnIndex = 0;
|
||||
|
||||
row.preAppendCells?.forEach((cell) => {
|
||||
const colSpan = isPreAppendCellConfig(cell) ? cell.colSpan ?? 1 : 1;
|
||||
const width = isPreAppendCellConfig(cell) ? toCssSize(cell.width) : undefined;
|
||||
|
||||
if (width && colSpan === 1 && !widths[columnIndex]) {
|
||||
widths[columnIndex] = width;
|
||||
}
|
||||
|
||||
columnIndex += colSpan;
|
||||
});
|
||||
});
|
||||
|
||||
return widths;
|
||||
};
|
||||
|
||||
const getLabelColumnWidth = (rows: TopChartTableRow[]) =>
|
||||
rows.map((row) => toCssSize(row.labelWidth)).find(Boolean);
|
||||
|
||||
export default function TopChartTable({
|
||||
title,
|
||||
rows,
|
||||
categories,
|
||||
chart,
|
||||
chartHeight = CHART_HEIGHTS.DEFAULT,
|
||||
minWidthPx = TABLE_DIMENSIONS.MIN_WIDTH.STANDARD,
|
||||
minWidth,
|
||||
subLabelHeader = "",
|
||||
rowHeaderWidth,
|
||||
tableClassName,
|
||||
wrapperClassName,
|
||||
signStyle,
|
||||
}: Readonly<TopChartTableProps>) {
|
||||
const resolvedSignStyle = resolveSignStyle(signStyle, {
|
||||
positiveTextClassName: "kfpa-num-pos",
|
||||
negativeTextClassName: "kfpa-num-neg",
|
||||
zeroTextClassName: "",
|
||||
arrowWithNumber: true,
|
||||
});
|
||||
|
||||
const maxPreAppendCellCount = useMemo(
|
||||
() => Math.max(0, ...rows.map((row) => row.preAppendCells?.length ?? 0)),
|
||||
[rows]
|
||||
);
|
||||
const leadingColumnCount = maxPreAppendCellCount + 1;
|
||||
const leadingColumnWidths = useMemo(
|
||||
() => [...getLeadingColumnWidths(rows, maxPreAppendCellCount), getLabelColumnWidth(rows)],
|
||||
[maxPreAppendCellCount, rows]
|
||||
);
|
||||
|
||||
const chartData: ChartData = useMemo(
|
||||
() => ({
|
||||
categories,
|
||||
series: rows.map((row) => ({
|
||||
name: row.label,
|
||||
data: row.values.map((value) => parseNumber(value) ?? null),
|
||||
})),
|
||||
}),
|
||||
[categories, rows]
|
||||
);
|
||||
|
||||
const chartNode = useMemo(() => {
|
||||
if (!chart) {
|
||||
return null;
|
||||
}
|
||||
return typeof chart === "function" ? chart({ chartData }) : chart;
|
||||
}, [chart, chartData]);
|
||||
const rowHeaderStyle = useMemo(() => {
|
||||
const width = toCssSize(rowHeaderWidth);
|
||||
return width ? { width, minWidth: width } : undefined;
|
||||
}, [rowHeaderWidth]);
|
||||
|
||||
return (
|
||||
<div className={cn("w-full", wrapperClassName)}>
|
||||
<BaseTableHeader title={title} />
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className={cn("lg-table kfpa-table", tableClassName)} style={{ minWidth: `${minWidth ?? minWidthPx}px` }}>
|
||||
<colgroup>
|
||||
{leadingColumnWidths.map((width, index) => (
|
||||
<col key={`leading-col-${index}`} style={width ? { width, minWidth: width } : undefined} />
|
||||
))}
|
||||
{categories.map((category) => (
|
||||
<col key={`category-col-${category}`} />
|
||||
))}
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
colSpan={leadingColumnCount}
|
||||
className={rowHeaderWidth ? undefined : "w-44"}
|
||||
style={{ whiteSpace: "nowrap", ...rowHeaderStyle }}
|
||||
/>
|
||||
<td colSpan={categories.length} style={{ padding: 0, height: chartNode ? chartHeight : 0 }}>
|
||||
{chartNode ? <div style={{ width: "100%", height: "100%" }}>{chartNode}</div> : null}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr className="lg-table__subhead kfpa-table__subhead">
|
||||
<th
|
||||
colSpan={leadingColumnCount}
|
||||
className="lg-table__sep-r kfpa-table__sep-r content-text-base"
|
||||
style={rowHeaderStyle}
|
||||
>
|
||||
{subLabelHeader}
|
||||
</th>
|
||||
{categories.map((category) => (
|
||||
<th key={category} className="content-text-base">
|
||||
{category}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{rows.map((row, rowIndex) => {
|
||||
const signRow = !!signStyle?.rowSelector?.(row, rowIndex);
|
||||
const preAppendCells = row.preAppendCells ?? [];
|
||||
|
||||
return (
|
||||
<tr key={`${row.label}-${rowIndex}`}>
|
||||
{preAppendCells.map(renderPreAppendCell)}
|
||||
<th
|
||||
scope="row"
|
||||
className={cn(
|
||||
"lg-table__rowhead kfpa-table__rowhead lg-table__sep-r kfpa-table__sep-r content-text-base",
|
||||
row.labelClassName
|
||||
)}
|
||||
style={{
|
||||
width: toCssSize(row.labelWidth),
|
||||
minWidth: toCssSize(row.labelWidth),
|
||||
}}
|
||||
>
|
||||
{row.label}
|
||||
</th>
|
||||
|
||||
{categories.map((_, categoryIndex) => {
|
||||
const rawValue = row.values?.[categoryIndex];
|
||||
const roundedValue = toRoundedNumber(rawValue, 2);
|
||||
|
||||
if (roundedValue === null) {
|
||||
return <td key={categoryIndex}>-</td>;
|
||||
}
|
||||
|
||||
if(!signRow) {
|
||||
return (
|
||||
<td key={categoryIndex}>
|
||||
{roundedValue}
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<td key={categoryIndex} className={getSignTextClass(roundedValue, resolvedSignStyle)}>
|
||||
{formatSignedValue(roundedValue, resolvedSignStyle)}
|
||||
</td>
|
||||
);
|
||||
|
||||
})}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
21
src/components/combo/types.ts
Normal file
21
src/components/combo/types.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import type React from "react";
|
||||
|
||||
export type TopChartTablePreAppendCellConfig = {
|
||||
content: React.ReactNode;
|
||||
className?: string;
|
||||
colSpan?: number;
|
||||
rowSpan?: number;
|
||||
width?: number | string;
|
||||
};
|
||||
|
||||
export type TopChartTablePreAppendCell =
|
||||
| React.ReactNode
|
||||
| TopChartTablePreAppendCellConfig;
|
||||
|
||||
export type TopChartTableRow = {
|
||||
label: string;
|
||||
labelClassName?: string;
|
||||
labelWidth?: number | string;
|
||||
preAppendCells?: TopChartTablePreAppendCell[];
|
||||
values: Array<number | string | null | undefined>;
|
||||
};
|
||||
@@ -9,7 +9,7 @@ export function LoadingOverlay({ force = false }: { force?: boolean }) {
|
||||
if (!force && !isLoading) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[9999] bg-black/70 flex items-center justify-center">
|
||||
<div className="fixed inset-0 z-[9999] bg-black-600/70 flex items-center justify-center">
|
||||
{/* 심플 로딩 인디케이터 */}
|
||||
<div className="h-12 w-12 rounded-full border-4 border-gray-400 border-t-white animate-spin" />
|
||||
</div>
|
||||
|
||||
10
src/components/common/SectionTitle.tsx
Normal file
10
src/components/common/SectionTitle.tsx
Normal file
@@ -0,0 +1,10 @@
|
||||
const SectionTitle = ({title}:{title:string}) => {
|
||||
return (
|
||||
<div className="font-semibold flex items-center gap-2">
|
||||
<span className="w-3 h-3 bg-primary" />
|
||||
{title}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SectionTitle;
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import {useEffect, useRef, useState} from "react";
|
||||
import {apiError} from "@/lib/http-util";
|
||||
import {NONE_HTTP_ERROR} from "@/const/commonConst";
|
||||
import {NONE_HTTP_ERROR} from "../../const/common.const";
|
||||
import {DialogId} from "@/store/jotai/dialog";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {useLoginMutation} from "@/query/auth";
|
||||
|
||||
@@ -55,7 +55,7 @@ const MainLayout = ({ children }: MainLayoutProps) => {
|
||||
if(!isMounted) return null;
|
||||
|
||||
return (
|
||||
<div className="h-screen flex flex-col bg-transparent overflow-hidden">
|
||||
<div className="flex h-dvh flex-col overflow-hidden bg-transparent">
|
||||
<LayoutCategoryProvider selectedDiv={selectedDiv}>
|
||||
<Header
|
||||
topMenus={TOP_MENUS}
|
||||
@@ -65,16 +65,18 @@ const MainLayout = ({ children }: MainLayoutProps) => {
|
||||
onLogin={openLoginDialog}
|
||||
onLogout={handleLogout}
|
||||
/>
|
||||
<div className="flex flex-1">
|
||||
<div className="flex h-[calc(100dvh-4rem)] min-h-0 overflow-hidden">
|
||||
<Sidebar
|
||||
sideMenus={SIDE_MENUS}
|
||||
isOpen={menuOpen}
|
||||
selectedDiv={selectedDiv}
|
||||
onChangeDiv={setSelectedDiv}
|
||||
/>
|
||||
<main className="flex-1 p-4">
|
||||
{children}
|
||||
</main>
|
||||
<div className="h-full min-h-0 flex-1 overflow-y-scroll overscroll-contain p-4">
|
||||
<main className="h-full min-h-0 flex-1">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<LoginDialog />
|
||||
|
||||
|
||||
162
src/components/table/BaseDataTable.tsx
Normal file
162
src/components/table/BaseDataTable.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
"use client";
|
||||
|
||||
import type React from "react";
|
||||
import { cn, parseNumber } from "@/lib/utils";
|
||||
|
||||
import BaseTableRenderer from "./core/BaseTableRenderer";
|
||||
import {
|
||||
appendCellMarker,
|
||||
getColumnAlign,
|
||||
getLeafColumns,
|
||||
toRoundedNumber,
|
||||
toTableCellContent,
|
||||
} from "./core/table-core.helpers";
|
||||
import {DataColumn} from "@/components/table/types";
|
||||
import {isGapRow} from "@/lib/kfpa-utill";
|
||||
|
||||
export type MergedTableCell<T> = {
|
||||
key: keyof T;
|
||||
content: React.ReactNode;
|
||||
startRowIndex?: number;
|
||||
rowSpan?: number;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export type PreAppendTableCell =
|
||||
| React.ReactNode
|
||||
| {
|
||||
content: React.ReactNode;
|
||||
className?: string;
|
||||
colSpan?: number;
|
||||
rowSpan?: number;
|
||||
};
|
||||
|
||||
type Props<T extends Record<string, unknown>> = {
|
||||
columns: DataColumn<T>[];
|
||||
rows: T[];
|
||||
title?: string;
|
||||
wrapperClassName?: string;
|
||||
tableClassName?: string;
|
||||
subheadRowClassName?: string;
|
||||
minWidth?: number | string;
|
||||
fillGapRow?: boolean;
|
||||
mergedCell?: MergedTableCell<T>;
|
||||
getCellClassName?: (row: T, column: DataColumn<T>, rowIndex: number) => string | undefined;
|
||||
};
|
||||
|
||||
const getPreAppendCells = (row: Record<string, unknown>): PreAppendTableCell[] => {
|
||||
const cells = row.preAppendCells;
|
||||
return Array.isArray(cells) ? (cells as PreAppendTableCell[]) : [];
|
||||
};
|
||||
|
||||
const renderPreAppendCell = (cell: PreAppendTableCell, index: number) => {
|
||||
const isCellConfig =
|
||||
typeof cell === "object" &&
|
||||
cell !== null &&
|
||||
!Array.isArray(cell) &&
|
||||
"content" in cell;
|
||||
|
||||
if (!isCellConfig) {
|
||||
return <td key={`pre-append-${index}`}>{cell}</td>;
|
||||
}
|
||||
|
||||
return (
|
||||
<td
|
||||
key={`pre-append-${index}`}
|
||||
className={cell.className}
|
||||
colSpan={cell.colSpan}
|
||||
rowSpan={cell.rowSpan}
|
||||
>
|
||||
{cell.content}
|
||||
</td>
|
||||
);
|
||||
};
|
||||
|
||||
export default function BaseDataTable<T extends Record<string, unknown>>({
|
||||
columns,
|
||||
rows,
|
||||
title,
|
||||
wrapperClassName,
|
||||
tableClassName,
|
||||
subheadRowClassName,
|
||||
minWidth,
|
||||
fillGapRow = false,
|
||||
mergedCell,
|
||||
getCellClassName,
|
||||
}: Readonly<Props<T>>) {
|
||||
const mergedCellStart = mergedCell?.startRowIndex ?? 0;
|
||||
const mergedCellSpan = mergedCell?.rowSpan ?? Math.max(0, rows.length - mergedCellStart);
|
||||
const leafColumns = getLeafColumns(columns);
|
||||
|
||||
return (
|
||||
<BaseTableRenderer
|
||||
columns={columns}
|
||||
title={title}
|
||||
wrapperClassName={wrapperClassName}
|
||||
tableClassName={tableClassName}
|
||||
subheadRowClassName={subheadRowClassName}
|
||||
minWidth={minWidth}
|
||||
>
|
||||
{rows.map((row, rowIndex) => {
|
||||
const rowTotal = parseNumber(row.total);
|
||||
const isFillGapRow = fillGapRow && isGapRow((row.rowLabel as string) ?? "")
|
||||
const fillGapClass = isFillGapRow ? "bg-gray-100" : "";
|
||||
const preAppendCells = getPreAppendCells(row);
|
||||
|
||||
return (
|
||||
<tr key={rowIndex}>
|
||||
{preAppendCells.map(renderPreAppendCell)}
|
||||
{leafColumns.map((column) => {
|
||||
const dynamicCellClassName = getCellClassName?.(row, column, rowIndex);
|
||||
|
||||
if (mergedCell && column.key === mergedCell.key && rowIndex >= mergedCellStart) {
|
||||
if (rowIndex > mergedCellStart) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<td
|
||||
key={String(column.key)}
|
||||
rowSpan={mergedCellSpan}
|
||||
className={cn(column.cellClassName, mergedCell.className)}
|
||||
style={{ padding: 0, verticalAlign: "middle" }}
|
||||
>
|
||||
{mergedCell.content}
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
const rawValue = row[column.key];
|
||||
const align = getColumnAlign(column);
|
||||
const defaultContent = column.render ? column.render(row) : toTableCellContent(rawValue);
|
||||
const numericValue = "numeric" in column && column.numeric ? parseNumber(rawValue ?? defaultContent) ?? 0 : 0;
|
||||
|
||||
if (column.rowHead) {
|
||||
return (
|
||||
<th
|
||||
key={String(column.key)}
|
||||
scope="row"
|
||||
className={cn("lg-table__rowhead", column.cellClassName, dynamicCellClassName, fillGapClass)}
|
||||
style={{ textAlign: align }}
|
||||
>
|
||||
{defaultContent}
|
||||
</th>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<td
|
||||
key={String(column.key)}
|
||||
className={cn(column.cellClassName, dynamicCellClassName, fillGapClass ? "bg-red-200" : "")}
|
||||
style={{ textAlign: align }}
|
||||
>
|
||||
{defaultContent}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</BaseTableRenderer>
|
||||
);
|
||||
}
|
||||
43
src/components/table/DataTable.tsx
Normal file
43
src/components/table/DataTable.tsx
Normal file
@@ -0,0 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import BaseDataTable from "./BaseDataTable";
|
||||
import {DataColumn} from "@/components/table/types";
|
||||
|
||||
type Props<T extends Record<string, unknown>> = {
|
||||
columns: DataColumn<T>[];
|
||||
rows: T[];
|
||||
title?: string;
|
||||
className?: string;
|
||||
tableClassName?: string;
|
||||
wrapperClassName?: string;
|
||||
subheadRowClassName?: string;
|
||||
minWidth?: number | string;
|
||||
fillGapRow?: boolean;
|
||||
};
|
||||
|
||||
const DataTable = <T extends Record<string, unknown>>({
|
||||
columns,
|
||||
rows,
|
||||
title,
|
||||
className,
|
||||
tableClassName,
|
||||
wrapperClassName,
|
||||
subheadRowClassName,
|
||||
minWidth,
|
||||
fillGapRow = false,
|
||||
}: Props<T>) => {
|
||||
return (
|
||||
<BaseDataTable
|
||||
columns={columns}
|
||||
rows={rows}
|
||||
title={title}
|
||||
tableClassName={tableClassName ?? className}
|
||||
wrapperClassName={wrapperClassName}
|
||||
subheadRowClassName={subheadRowClassName}
|
||||
minWidth={minWidth}
|
||||
fillGapRow={fillGapRow}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default DataTable;
|
||||
18
src/components/table/core/BaseTableHeader.tsx
Normal file
18
src/components/table/core/BaseTableHeader.tsx
Normal file
@@ -0,0 +1,18 @@
|
||||
import SectionTitle from "@/components/common/SectionTitle";
|
||||
|
||||
|
||||
type Props = {
|
||||
title?: string;
|
||||
};
|
||||
|
||||
export default function BaseTableHeader({ title }: Readonly<Props>) {
|
||||
if (!title) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<SectionTitle title={title} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
68
src/components/table/core/BaseTableRenderer.tsx
Normal file
68
src/components/table/core/BaseTableRenderer.tsx
Normal file
@@ -0,0 +1,68 @@
|
||||
"use client";
|
||||
|
||||
import type React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
import BaseTableHeader from "./BaseTableHeader";
|
||||
import { buildHeaderRows } from "./table-core.helpers";
|
||||
import {DataColumn} from "@/components/table/types";
|
||||
|
||||
type BaseColumn<T> = DataColumn<T>;
|
||||
|
||||
type Props<T> = {
|
||||
columns: BaseColumn<T>[];
|
||||
title?: string;
|
||||
wrapperClassName?: string;
|
||||
tableClassName?: string;
|
||||
subheadRowClassName?: string;
|
||||
minWidth?: number | string;
|
||||
colgroup?: React.ReactNode;
|
||||
renderHeaderPrefix?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
};
|
||||
|
||||
export default function BaseTableRenderer<T>({
|
||||
columns,
|
||||
title,
|
||||
wrapperClassName,
|
||||
tableClassName,
|
||||
subheadRowClassName,
|
||||
minWidth,
|
||||
colgroup,
|
||||
renderHeaderPrefix,
|
||||
children,
|
||||
}: Readonly<Props<T>>) {
|
||||
const headerRows = buildHeaderRows(columns);
|
||||
const lastHeaderRowIndex = headerRows.length - 1;
|
||||
|
||||
return (
|
||||
<div className={cn("w-full", wrapperClassName)}>
|
||||
<BaseTableHeader title={title} />
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table
|
||||
className={cn("lg-table", tableClassName)}
|
||||
style={minWidth === undefined ? undefined : { minWidth: typeof minWidth === "number" ? `${minWidth}px` : minWidth }}
|
||||
>
|
||||
{colgroup}
|
||||
<thead>
|
||||
{renderHeaderPrefix}
|
||||
{headerRows.map((row, rowIndex) => (
|
||||
<tr
|
||||
key={`header-row-${rowIndex}`}
|
||||
className={cn(rowIndex === lastHeaderRowIndex ? "lg-table__subhead" : "lg-table__group", rowIndex === lastHeaderRowIndex ? subheadRowClassName : undefined)}
|
||||
>
|
||||
{row.map((cell) => (
|
||||
<th key={cell.id} colSpan={cell.colSpan} rowSpan={cell.rowSpan} className={cell.className}>
|
||||
{cell.label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>{children}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
242
src/components/table/core/table-core.helpers.tsx
Normal file
242
src/components/table/core/table-core.helpers.tsx
Normal file
@@ -0,0 +1,242 @@
|
||||
import type React from "react";
|
||||
import { parseNumber, roundNumber } from "@/lib/utils";
|
||||
import {
|
||||
DataColumn,
|
||||
DataColumnLeaf,
|
||||
SignDisplayMode,
|
||||
SignStyle,
|
||||
ValueFormatter
|
||||
} from "@/components/table/types";
|
||||
|
||||
export type TableColumnNode<T> = DataColumn<T>;
|
||||
export type TableColumnLeaf<T> = DataColumnLeaf<T>;
|
||||
|
||||
export type GroupHeaderCell = {
|
||||
id: string;
|
||||
label: string;
|
||||
colSpan: number;
|
||||
rowSpan: number;
|
||||
className?: string;
|
||||
isLeaf: boolean;
|
||||
};
|
||||
|
||||
export type ResolvedSignStyle = {
|
||||
paint: "text" | "cell";
|
||||
display: SignDisplayMode;
|
||||
showPlus: boolean;
|
||||
arrowWithNumber: boolean;
|
||||
zeroText: string;
|
||||
valueFormatter: ValueFormatter;
|
||||
positiveTextClassName: string;
|
||||
negativeTextClassName: string;
|
||||
zeroTextClassName: string;
|
||||
positiveCellBg: string;
|
||||
negativeCellBg: string;
|
||||
zeroCellBg: string;
|
||||
};
|
||||
|
||||
const defaultValueFormatter: ValueFormatter = (value) =>
|
||||
Number.isInteger(value) ? String(roundNumber(value)) : value.toLocaleString();
|
||||
|
||||
function isColumnLeaf<T>(column: TableColumnNode<T>): column is TableColumnLeaf<T> {
|
||||
return !("children" in column) || !column.children?.length;
|
||||
}
|
||||
|
||||
export function getLeafColumns<T>(columns: TableColumnNode<T>[]) {
|
||||
const leaves: TableColumnLeaf<T>[] = [];
|
||||
|
||||
const visit = (nodes: TableColumnNode<T>[]) => {
|
||||
nodes.forEach((node) => {
|
||||
if (isColumnLeaf(node)) {
|
||||
leaves.push(node);
|
||||
return;
|
||||
}
|
||||
|
||||
visit(node.children);
|
||||
});
|
||||
};
|
||||
|
||||
visit(columns);
|
||||
return leaves;
|
||||
}
|
||||
|
||||
function getHeaderDepth<T>(columns: TableColumnNode<T>[]) {
|
||||
const visit = (nodes: TableColumnNode<T>[], depth: number): number =>
|
||||
nodes.reduce((maxDepth, node) => {
|
||||
if (isColumnLeaf(node)) {
|
||||
return Math.max(maxDepth, depth);
|
||||
}
|
||||
|
||||
return Math.max(maxDepth, visit(node.children, depth + 1));
|
||||
}, depth);
|
||||
|
||||
return columns.length ? visit(columns, 1) : 0;
|
||||
}
|
||||
|
||||
function getLeafCount<T>(column: TableColumnNode<T>): number {
|
||||
if (isColumnLeaf(column)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return column.children.reduce((sum, child) => sum + getLeafCount(child), 0);
|
||||
}
|
||||
|
||||
export function buildHeaderRows<T>(columns: TableColumnNode<T>[]) {
|
||||
const depth = getHeaderDepth(columns);
|
||||
|
||||
if (!depth) {
|
||||
return [] as GroupHeaderCell[][];
|
||||
}
|
||||
|
||||
const rows = Array.from({ length: depth }, () => [] as GroupHeaderCell[]);
|
||||
|
||||
const visit = (nodes: TableColumnNode<T>[], level: number, path: string[]) => {
|
||||
nodes.forEach((node, index) => {
|
||||
const nodeId = node.id ?? (isColumnLeaf(node) ? String(node.key) : `${path.join(".") || "root"}:${index}:${node.header}`);
|
||||
const nextPath = [...path, nodeId];
|
||||
const isLeaf = isColumnLeaf(node);
|
||||
|
||||
rows[level].push({
|
||||
id: nextPath.join("/"),
|
||||
label: node.header,
|
||||
colSpan: isLeaf ? 1 : getLeafCount(node),
|
||||
rowSpan: isLeaf ? depth - level : 1,
|
||||
className: node.headerClassName,
|
||||
isLeaf,
|
||||
});
|
||||
|
||||
if (!isLeaf) {
|
||||
visit(node.children, level + 1, nextPath);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
visit(columns, 0, []);
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function hasGroupedHeader<T>(columns: TableColumnNode<T>[]) {
|
||||
return getHeaderDepth(columns) > 1;
|
||||
}
|
||||
|
||||
export function getColumnAlign<T>(column: TableColumnLeaf<T>, fallback: "left" | "center" | "right" = "center") {
|
||||
if (column.align) {
|
||||
return column.align;
|
||||
}
|
||||
|
||||
if ("numeric" in column && column.numeric) {
|
||||
return "right";
|
||||
}
|
||||
|
||||
if (column.rowHead) {
|
||||
return "left";
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function toTableCellContent(raw: unknown): React.ReactNode {
|
||||
if (raw == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (typeof raw === "string") {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) {
|
||||
return raw;
|
||||
}
|
||||
|
||||
const parsed = Number(trimmed);
|
||||
return Number.isNaN(parsed) ? raw : roundNumber(parsed);
|
||||
}
|
||||
|
||||
if (typeof raw === "number") {
|
||||
return String(roundNumber(raw));
|
||||
}
|
||||
|
||||
return String(raw);
|
||||
}
|
||||
|
||||
export function toRoundedNumber(raw: unknown, decimalPoint?: number) {
|
||||
const parsed = parseNumber(raw);
|
||||
return parsed === null ? null : roundNumber(parsed, decimalPoint);
|
||||
}
|
||||
|
||||
const defaultSignStyle: ResolvedSignStyle = {
|
||||
paint: "text",
|
||||
display: "number",
|
||||
showPlus: true,
|
||||
arrowWithNumber: false,
|
||||
zeroText: "-",
|
||||
valueFormatter: defaultValueFormatter,
|
||||
positiveTextClassName: "text-primary font-semibold",
|
||||
negativeTextClassName: "text-info font-semibold",
|
||||
zeroTextClassName: "text-gray-600",
|
||||
positiveCellBg: "hsl(var(--primary) / 0.08)",
|
||||
negativeCellBg: "hsl(var(--info) / 0.08)",
|
||||
zeroCellBg: "hsl(var(--lg-gray-200) / 0.6)",
|
||||
};
|
||||
|
||||
|
||||
export function resolveSignStyle<T>(signStyle?: SignStyle<T>, fallback?: Partial<ResolvedSignStyle>) {
|
||||
return {
|
||||
...defaultSignStyle,
|
||||
...fallback,
|
||||
...signStyle,
|
||||
valueFormatter: signStyle?.valueFormatter ?? fallback?.valueFormatter ?? defaultSignStyle.valueFormatter,
|
||||
};
|
||||
}
|
||||
|
||||
export function formatSignedValue(
|
||||
value: number,
|
||||
options: Pick<ResolvedSignStyle, "arrowWithNumber" | "display" | "showPlus" | "valueFormatter" | "zeroText">
|
||||
) {
|
||||
if (options.display === "arrow") {
|
||||
if (value > 0) {
|
||||
return options.arrowWithNumber ? `▲${options.valueFormatter(Math.abs(value))}` : "▲";
|
||||
}
|
||||
if (value < 0) {
|
||||
return options.arrowWithNumber ? `▼${options.valueFormatter(Math.abs(value))}` : "▼";
|
||||
}
|
||||
return options.zeroText;
|
||||
}
|
||||
|
||||
if (value > 0) {
|
||||
return options.showPlus ? `+${options.valueFormatter(value)}` : options.valueFormatter(value);
|
||||
}
|
||||
if (value < 0) {
|
||||
return options.valueFormatter(value);
|
||||
}
|
||||
return options.zeroText;
|
||||
}
|
||||
|
||||
|
||||
export function getSignTextClass(
|
||||
value: number,
|
||||
options: Pick<ResolvedSignStyle, "negativeTextClassName" | "positiveTextClassName" | "zeroTextClassName">
|
||||
) {
|
||||
if (value > 0) {
|
||||
return options.positiveTextClassName;
|
||||
}
|
||||
if (value < 0) {
|
||||
return options.negativeTextClassName;
|
||||
}
|
||||
return options.zeroTextClassName;
|
||||
}
|
||||
|
||||
export function appendCellMarker(content: React.ReactNode, marker: string) {
|
||||
if (!marker) {
|
||||
return content;
|
||||
}
|
||||
|
||||
if (typeof content === "string" || typeof content === "number") {
|
||||
return `${content}${marker}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{content}
|
||||
{marker}
|
||||
</>
|
||||
);
|
||||
}
|
||||
12
src/components/table/table.config.ts
Normal file
12
src/components/table/table.config.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
export const TABLE_DIMENSIONS = {
|
||||
CELL_HEIGHT: {
|
||||
DEFAULT: 26,
|
||||
COMPACT: 20,
|
||||
EXPANDED: 32,
|
||||
},
|
||||
MIN_WIDTH: {
|
||||
STANDARD: 1600,
|
||||
COMPACT: 1200,
|
||||
WIDE: 2000,
|
||||
},
|
||||
} as const;
|
||||
64
src/components/table/types.ts
Normal file
64
src/components/table/types.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
export type ValueFormatter = (v: number) => string;
|
||||
|
||||
export type TableColumnAlign = "left" | "center" | "right";
|
||||
|
||||
type TableColumnShared<T> = {
|
||||
id?: string;
|
||||
header: string;
|
||||
width?: number | string;
|
||||
align?: TableColumnAlign;
|
||||
headerClassName?: string;
|
||||
cellClassName?: string;
|
||||
render?: (row: T) => React.ReactNode;
|
||||
};
|
||||
|
||||
export type DataColumnLeaf<T> = TableColumnShared<T> & {
|
||||
key: keyof T;
|
||||
rowHead?: boolean; // 첫 컬럼 등 row header
|
||||
numeric?: boolean; // 숫자열(정렬 기본값/색상 타겟 기본값에 사용)
|
||||
children?: undefined;
|
||||
};
|
||||
|
||||
export type DataColumnGroup<T> = TableColumnShared<T> & {
|
||||
children: DataColumn<T>[];
|
||||
key?: undefined;
|
||||
rowHead?: undefined;
|
||||
numeric?: undefined;
|
||||
};
|
||||
|
||||
export type DataColumn<T> = DataColumnLeaf<T> | DataColumnGroup<T>;
|
||||
|
||||
export type SignDisplayMode = "number" | "arrow";
|
||||
|
||||
export type SignStyle<T> = {
|
||||
/** 어떤 row에 +/ -/ 0 색상표기를 적용할지 선택 */
|
||||
rowSelector: (row: T, rowIndex: number) => boolean;
|
||||
|
||||
/** 어떤 컬럼에 적용할지(미지정 시 numeric 컬럼 전체) */
|
||||
keys?: (keyof T)[];
|
||||
|
||||
/** 색상 적용 방식 */
|
||||
paint?: "text" | "cell"; // 기본 text
|
||||
|
||||
/** 표기 방식 */
|
||||
display?: SignDisplayMode; // 기본 number
|
||||
showPlus?: boolean; // number 모드에서 + 표시(기본 true)
|
||||
|
||||
/** 0 값 표기(기본 "-") */
|
||||
zeroText?: string;
|
||||
|
||||
/** arrow 모드 옵션 */
|
||||
arrowWithNumber?: boolean; // ▲ 2 처럼 (기본 false)
|
||||
|
||||
/** 값 포맷(기본: 정수면 그대로/그 외 toLocaleString) */
|
||||
valueFormatter?: (v: number) => string;
|
||||
|
||||
/** 색상 커스터마이즈(기본: + primary, - info, 0 gray) */
|
||||
positiveTextClassName?: string; // 기본 "text-primary font-semibold"
|
||||
negativeTextClassName?: string; // 기본 "text-info font-semibold"
|
||||
zeroTextClassName?: string; // 기본 "text-gray-600"
|
||||
|
||||
positiveCellBg?: string; // ex) "hsl(var(--primary) / 0.08)"
|
||||
negativeCellBg?: string; // ex) "hsl(var(--info) / 0.08)"
|
||||
zeroCellBg?: string; // ex) "hsl(var(--lg-gray-200) / 0.6)"
|
||||
};
|
||||
@@ -39,7 +39,7 @@ function DialogOverlay({
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||
"fixed inset-0 isolate z-50 bg-black-600/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -2,11 +2,11 @@ export const SITE_TITLE = "화재보험협회 대시보드"
|
||||
|
||||
export const CATEGORY_KEY_MAP: Record<string, string> = {
|
||||
'2601009_A': '안전점검',
|
||||
'2604005_E': 'UCIS',
|
||||
'2604005_D': 'Bridge플랫폼',
|
||||
'2604005_C': '방재컨설팅',
|
||||
'2604005_A': '보험 공동인수',
|
||||
'2604005_B': '화재조사',
|
||||
//'2604005_E': 'UCIS',
|
||||
//'2604005_D': 'Bridge플랫폼',
|
||||
//'2604005_C': '방재컨설팅',
|
||||
//'2604005_A': '보험 공동인수',
|
||||
//'2604005_B': '화재조사',
|
||||
};
|
||||
|
||||
export const CATEGORY_PATH_MAP: Record<string, string> = {
|
||||
@@ -25,22 +25,22 @@ export const CATEGORIES = Object.values(CATEGORY_KEY_MAP) as Array<string>;
|
||||
export const DIV_KEY_MAP: Record<string, string> = {
|
||||
'-1': '전체',
|
||||
'1': '서울인천지역본부',
|
||||
'2': '경기강원지역본부',
|
||||
'3': '부산경남지역본부',
|
||||
'4': '대구경북지역본부',
|
||||
'5': '대전충청지역본부',
|
||||
'6': '광주호남지역본부',
|
||||
'3': '경기강원지역본부',
|
||||
'2': '부산경남지역본부',
|
||||
'5': '대구경북지역본부',
|
||||
'6': '대전충청지역본부',
|
||||
'4': '광주호남지역본부',
|
||||
};
|
||||
|
||||
export const DIV_KEYS = Object.keys(DIV_KEY_MAP) as Array<keyof typeof DIV_KEY_MAP>;
|
||||
export const DIV_KEYS = ["-1", "1", "3", "2", "5", "6", "4"] as const;
|
||||
|
||||
export const DIVS = Object.values(DIV_KEY_MAP) as Array<string>;
|
||||
export const DIVS = DIV_KEYS.map((key) => DIV_KEY_MAP[key]);
|
||||
|
||||
export const REGION_KEY_MAP: Record<string, string> = {
|
||||
'1': '서울',
|
||||
'2': '경기',
|
||||
'3': '부산',
|
||||
'4': '대구',
|
||||
'5': '대전',
|
||||
'6': '광주',
|
||||
};
|
||||
'3': '경기',
|
||||
'2': '부산',
|
||||
'5': '대구',
|
||||
'6': '대전',
|
||||
'4': '광주',
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {SideMenuItem, TopMenuItem} from "@/config/menu.type";
|
||||
import {CATEGORY_KEY_MAP, CATEGORY_PATH_MAP, DIV_KEY_MAP} from "./kfpaConfig";
|
||||
import {CATEGORY_KEY_MAP, CATEGORY_PATH_MAP, DIV_KEY_MAP, DIV_KEYS} from "./kfpaConfig";
|
||||
import { Building } from 'lucide-react';
|
||||
|
||||
export const TOP_MENUS: TopMenuItem[] = Object.entries(CATEGORY_KEY_MAP).map(
|
||||
@@ -15,14 +15,9 @@ export const TOP_MENUS: TopMenuItem[] = Object.entries(CATEGORY_KEY_MAP).map(
|
||||
}
|
||||
);
|
||||
|
||||
export const SIDE_MENUS :SideMenuItem[] = Object.entries(DIV_KEY_MAP)
|
||||
.sort(([a], [b]) => {
|
||||
if (a === "-1") return -1;
|
||||
if (b === "-1") return 1;
|
||||
return Number(a) - Number(b);
|
||||
})
|
||||
.map(([key, value]) => ({
|
||||
export const SIDE_MENUS :SideMenuItem[] = DIV_KEYS
|
||||
.map((key) => ({
|
||||
id: key,
|
||||
label: value,
|
||||
label: DIV_KEY_MAP[key],
|
||||
icon: Building,
|
||||
}));
|
||||
|
||||
2
src/const/kfpa.const.ts
Normal file
2
src/const/kfpa.const.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export const VIEW_DECIMAL_POINT = 0;
|
||||
export const GAP_WORDING = "전년 대비";
|
||||
@@ -1,7 +1,7 @@
|
||||
import {NextResponse} from "next/server";
|
||||
import {HttpError} from "@/lib/http-client";
|
||||
import {clientEnv} from "@/lib/env.client";
|
||||
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "@/const/commonConst";
|
||||
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "../const/common.const";
|
||||
|
||||
export type ApiError = {
|
||||
status: number
|
||||
|
||||
3
src/lib/kfpa-utill.ts
Normal file
3
src/lib/kfpa-utill.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export const isGapRow = (raw: string) => raw.replace(/\s+/g, "").toUpperCase().includes("전년대비");
|
||||
|
||||
export const isSampleRow = (raw: string) => raw.replace(/\s+/g, "").includes("사례수");
|
||||
@@ -1,6 +1,61 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
import {VIEW_DECIMAL_POINT} from "@/const/kfpa.const";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
export const formatKoreanBaseDate = (date = new Date()) => {
|
||||
const year = String(date.getFullYear()).slice(-2);
|
||||
return `${year}년 ${date.getMonth() + 1}월 ${date.getDate()}일 기준`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 다양한 형식의 값을 숫자로 파싱합니다.
|
||||
* - 쉼표, 퍼센트, 유니코드 마이너스 자동 처리
|
||||
* - null/undefined/빈문자열/"−" 등은 null 반환
|
||||
* - 유한하지 않은 숫자는 null 반환
|
||||
*/
|
||||
export function parseNumber(
|
||||
value: unknown,
|
||||
options?: {
|
||||
allowComma?: boolean; // 기본값: true
|
||||
allowPercent?: boolean; // 기본값: true
|
||||
allowMinus?: boolean; // 기본값: true (유니코드 마이너스 포함)
|
||||
}
|
||||
): number | null {
|
||||
const { allowComma = true, allowPercent = true, allowMinus = true } = options ?? {};
|
||||
|
||||
if (value === null || value === undefined) return null;
|
||||
|
||||
if (typeof value === "number") {
|
||||
return Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
if (typeof value === "string") {
|
||||
let s = value.trim();
|
||||
|
||||
if (s === "" || s === "-" || s === "−") return null;
|
||||
|
||||
s = s.replaceAll("(", "");
|
||||
s = s.replaceAll(")", "");
|
||||
|
||||
if (allowComma) s = s.replaceAll(",", "");
|
||||
if (allowPercent) s = s.replaceAll("%", "");
|
||||
if (allowMinus) s = s.replaceAll("−", "-"); // 유니코드 마이너스 -> ASCII 마이너스
|
||||
|
||||
const n = Number(s);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export const roundNumber = (num: number|null, decimalPoint?: number) => {
|
||||
if(num == null) return null;
|
||||
|
||||
decimalPoint ??= VIEW_DECIMAL_POINT;
|
||||
const factor = 10 ** decimalPoint;
|
||||
return Math.round(num * factor) / factor;
|
||||
};
|
||||
|
||||
15
src/query/admin.ts
Normal file
15
src/query/admin.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import {useMutation} from "@tanstack/react-query";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {RequestWriteDivComment} from "@/types/kfpa";
|
||||
import {adminQueryKeys} from "@/query/key/keys";
|
||||
|
||||
export const writeDivComment = (body: RequestWriteDivComment) => {
|
||||
return nextApi.patch<boolean>("/admin/div-comment", body);
|
||||
};
|
||||
|
||||
export const useWriteDivCommentMutation = () => {
|
||||
return useMutation({
|
||||
mutationKey: adminQueryKeys.divComment(),
|
||||
mutationFn: writeDivComment,
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
export const adminQueryKeys = {
|
||||
all: ["admin"] as const,
|
||||
divComment: () => [...adminQueryKeys.all, "div-comment"] as const,
|
||||
};
|
||||
|
||||
export const statisticsQueryKeys = {
|
||||
all: ["statistics"] as const,
|
||||
csi: () => [...statisticsQueryKeys.all, "csi"] as const,
|
||||
divDetail: (divId: string | number) => [...statisticsQueryKeys.all, "div-detail", String(divId)] as const,
|
||||
};
|
||||
|
||||
27
src/query/statistics.ts
Normal file
27
src/query/statistics.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import {useQuery} from "@tanstack/react-query";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {CsiDataMap, DivDetailDataMap} from "@/types/kfpa";
|
||||
import {statisticsQueryKeys} from "@/query/key/keys";
|
||||
|
||||
export const getCsiData = () => {
|
||||
return nextApi.get<CsiDataMap>("/statistics/csi");
|
||||
};
|
||||
|
||||
export const getDivDetailData = (divId: string | number) => {
|
||||
return nextApi.get<DivDetailDataMap>(`/statistics/div-detail/${divId}`);
|
||||
};
|
||||
|
||||
export const useCsiDataQuery = () => {
|
||||
return useQuery({
|
||||
queryKey: statisticsQueryKeys.csi(),
|
||||
queryFn: getCsiData,
|
||||
});
|
||||
};
|
||||
|
||||
export const useDivDetailDataQuery = (divId: string | number, enabled = true) => {
|
||||
return useQuery({
|
||||
queryKey: statisticsQueryKeys.divDetail(divId),
|
||||
queryFn: () => getDivDetailData(divId),
|
||||
enabled,
|
||||
});
|
||||
};
|
||||
@@ -2,4 +2,38 @@ import {CATEGORY_KEY_MAP, DIV_KEY_MAP} from "@/config/kfpaConfig";
|
||||
|
||||
export type CategoryKey = keyof typeof CATEGORY_KEY_MAP;
|
||||
|
||||
export type DivKey = keyof typeof DIV_KEY_MAP;
|
||||
export type DivKey = keyof typeof DIV_KEY_MAP;
|
||||
|
||||
export type CommentValue = {
|
||||
directExperience: string;
|
||||
indirectExperience: string;
|
||||
capability: string;
|
||||
};
|
||||
|
||||
export type RequestWriteDivComment = {
|
||||
divId: number;
|
||||
commentValues: Record<string, CommentValue>;
|
||||
};
|
||||
|
||||
export type CsiData = {
|
||||
wave: number;
|
||||
csi: number;
|
||||
safeHelp: number;
|
||||
recHelp: number;
|
||||
staffProf: number;
|
||||
staffAtt: number;
|
||||
};
|
||||
|
||||
export type CsiRank = {
|
||||
csi: number;
|
||||
divRank: number;
|
||||
};
|
||||
|
||||
export type DivDetailData = {
|
||||
csiRanks: Record<string, CsiRank>;
|
||||
commentValues: Record<string, CommentValue>;
|
||||
};
|
||||
|
||||
export type CsiDataMap = Record<string, CsiData[]>;
|
||||
|
||||
export type DivDetailDataMap = Record<string, DivDetailData>;
|
||||
|
||||
Reference in New Issue
Block a user