260928_01_ENH: 신청서 파일 업로드/다운로드 추가
This commit is contained in:
@@ -12,9 +12,20 @@ const toResponse = (result: unknown) => (result === undefined ? new NextResponse
|
||||
*/
|
||||
const isBinaryExcelPath = (slug: string[]) => slug[0] === "excel" && (slug[1] === "download" || slug[1] === "template");
|
||||
|
||||
/*
|
||||
* request-form/download/{performanceId}/{formType}은 신청서 원본 파일 바이너리를
|
||||
* 그대로 반환한다. 첨부파일 이름을 위해 Content-Disposition 헤더를 릴레이한다.
|
||||
*/
|
||||
const isBinaryRequestFormPath = (slug: string[]) => slug[0] === "request-form" && slug[1] === "download";
|
||||
|
||||
export async function GET(request: NextRequest, context: RouteContext) {
|
||||
try {
|
||||
const { slug = [] } = await context.params;
|
||||
|
||||
if (isBinaryRequestFormPath(slug)) {
|
||||
return await fetchBackBinary(apiPath(slug));
|
||||
}
|
||||
|
||||
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
|
||||
const serverApi = await createBackApi();
|
||||
return toResponse(await serverApi.get<unknown>(apiPath(slug), { query }));
|
||||
|
||||
@@ -15,15 +15,18 @@ import type {
|
||||
PerformanceReview,
|
||||
PerformanceReviewSlot,
|
||||
PerformanceStaff,
|
||||
RequestFormType,
|
||||
} from "@/types/kmusical";
|
||||
import {PDF_CONVERT_STATUS} from "@/types/kmusical";
|
||||
import {PDF_CONVERT_STATUS, REQUEST_FORM_DETAIL_KEY, REQUEST_FORM_LABEL, REQUEST_FORM_TYPE} from "@/types/kmusical";
|
||||
import type {CodeGroup} from "@/query/code";
|
||||
import {HttpError} from "@kri/common/http";
|
||||
import {
|
||||
useDownloadReviewOriginalMutation,
|
||||
useDownloadReviewPdfMutation,
|
||||
useDownloadReviewTemplateMutation,
|
||||
useUploadReviewFileMutation,
|
||||
} from "@/query/review";
|
||||
import {useDownloadRequestFormMutation, useUploadRequestFormMutation} from "@/query/performance";
|
||||
import {useUserQuery} from "@/query/user";
|
||||
import {downloadBlob, downloadFromUrl} from "@/lib/kmusical/file";
|
||||
import {toLocalDateString} from "@/lib/kmusical/date";
|
||||
@@ -147,6 +150,70 @@ function ReviewSlotCard({
|
||||
);
|
||||
}
|
||||
|
||||
function RequestFormRow({
|
||||
performanceId,
|
||||
formType,
|
||||
fileName,
|
||||
canEdit,
|
||||
onUploaded,
|
||||
}: Readonly<{
|
||||
performanceId: string;
|
||||
formType: RequestFormType;
|
||||
fileName?: string;
|
||||
canEdit: boolean;
|
||||
onUploaded?: (formType: RequestFormType, savedFileName: string) => void;
|
||||
}>) {
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const uploadMutation = useUploadRequestFormMutation();
|
||||
const downloadMutation = useDownloadRequestFormMutation();
|
||||
|
||||
const upload = async (file?: File) => {
|
||||
try {
|
||||
if (!file) return;
|
||||
const formData = new FormData();
|
||||
formData.append("file", file, file.name);
|
||||
const savedFileName = await uploadMutation.mutateAsync({performanceId, formType, formData});
|
||||
alert(`${REQUEST_FORM_LABEL[formType]} 파일이 등록되었습니다.`);
|
||||
onUploaded?.(formType, savedFileName);
|
||||
} finally {
|
||||
if (fileInputRef.current) fileInputRef.current.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
const download = async () => {
|
||||
try {
|
||||
await downloadMutation.mutateAsync({performanceId, formType});
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError && error.status === 404) {
|
||||
alert("등록된 파일이 없습니다.");
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<DetailRow label={REQUEST_FORM_LABEL[formType]}>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="min-w-0 flex-1 break-all">{fileName || "등록된 파일 없음"}</span>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{canEdit && (
|
||||
<>
|
||||
<input ref={fileInputRef} type="file" className="hidden" onChange={(event) => void upload(event.target.files?.[0])} />
|
||||
<Button type="button" size="xs" variant="outline" className="rounded-full" onClick={() => fileInputRef.current?.click()} disabled={uploadMutation.isPending}>
|
||||
<Upload className="size-3" /> {fileName ? "교체" : "등록"}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button type="button" size="xs" variant="outline" className="rounded-full" onClick={download} disabled={!fileName || downloadMutation.isPending}>
|
||||
<Download className="size-3" /> 다운로드
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DetailRow>
|
||||
);
|
||||
}
|
||||
|
||||
const clonePerformance = (performance: PerformanceCompact): PerformanceCompact => ({
|
||||
...performance,
|
||||
performanceDetail: {...performance.performanceDetail},
|
||||
@@ -279,6 +346,23 @@ export function PerformanceDetailDialog({
|
||||
<DetailRow label={PERFORMANCE_FIELD_LABELS.clientManagerName}>{isEditing ? <Input value={draft.performanceDetail.clientManagerName ?? ""} onChange={(event) => updateDetail("clientManagerName", event.target.value)} /> : draft.performanceDetail.clientManagerName}</DetailRow>
|
||||
</section>
|
||||
|
||||
<section className="rounded-md border">
|
||||
<div className="border-b bg-muted px-3 py-2 font-semibold">신청서 파일</div>
|
||||
{[REQUEST_FORM_TYPE.PUBLIC_OFFERING, REQUEST_FORM_TYPE.ISSUANCE].map((formType) => (
|
||||
<RequestFormRow
|
||||
key={formType}
|
||||
performanceId={draft.performanceId}
|
||||
formType={formType}
|
||||
fileName={draft.performanceDetail[REQUEST_FORM_DETAIL_KEY[formType]] || undefined}
|
||||
canEdit={canEdit}
|
||||
onUploaded={(uploadedType, savedFileName) => {
|
||||
updateDetail(REQUEST_FORM_DETAIL_KEY[uploadedType], savedFileName);
|
||||
onRefresh?.();
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
|
||||
<section className="rounded-md border">
|
||||
<div className="border-b bg-muted px-3 py-2 font-semibold">관계자 정보</div>
|
||||
<div className="overflow-auto">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {downloadFile} from "@kri/common/browser";
|
||||
import {HttpError} from "@kri/common/http";
|
||||
|
||||
const trimDispositionValue = (value: string) => value.trim().replace(/^"|"$/g, "");
|
||||
|
||||
@@ -41,6 +42,22 @@ export const downloadExcelBuffer = (buffer: ArrayBuffer, fileName: string) => {
|
||||
downloadBlob(buffer, fileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
};
|
||||
|
||||
/*
|
||||
* 다운로드 API를 raw fetch로 호출해 Blob으로 저장한다.
|
||||
* expectBinary 경로는 응답 헤더를 버리므로, 첨부파일 이름은 여기서 Content-Disposition으로 결정한다.
|
||||
* 파일이 없으면 API가 404를 반환하며 HttpError로 전파한다.
|
||||
*/
|
||||
export const downloadFromApiUrl = async (url: string, fallbackFileName = "download") => {
|
||||
const response = await fetch(url, {cache: "no-store"});
|
||||
if (!response.ok) {
|
||||
const data = await response.json().catch(() => null);
|
||||
throw new HttpError(response.status, data, response.url, response.headers);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const fileName = getFileNameFromContentDisposition(response.headers.get("content-disposition")) ?? fallbackFileName;
|
||||
downloadFile(blob, fileName);
|
||||
};
|
||||
|
||||
export const downloadFromUrl = (url: string) => {
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
|
||||
@@ -3,8 +3,16 @@
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ExcelUploadResult } from "@kri/common";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { clientEnv } from "@/lib/env.client";
|
||||
import { downloadFromApiUrl } from "@/lib/kmusical/file";
|
||||
import { queryKeys } from "@/query/key/keys";
|
||||
import type { PerformanceCompact, PerformanceFull } from "@/types/kmusical";
|
||||
import type { PerformanceCompact, PerformanceFull, RequestFormType } from "@/types/kmusical";
|
||||
|
||||
const requestFormPath = (performanceId: string, formType: RequestFormType) =>
|
||||
`/performance/request-form/upload/${encodeURIComponent(performanceId)}/${formType}`;
|
||||
|
||||
const requestFormDownloadUrl = (performanceId: string, formType: RequestFormType) =>
|
||||
`${clientEnv.API_BASE}/performance/request-form/download/${encodeURIComponent(performanceId)}/${formType}`;
|
||||
|
||||
export const usePerformanceListQuery = () => useQuery({
|
||||
queryKey: queryKeys.performance.list,
|
||||
@@ -58,3 +66,27 @@ export function useUploadPerformanceExcelMutation() {
|
||||
onSuccess: () => client.invalidateQueries({ queryKey: queryKeys.performance.all }),
|
||||
});
|
||||
}
|
||||
|
||||
/*
|
||||
* 신청서 파일 업로드. 같은 공연·formType으로 다시 올리면 기존 파일이 교체된다.
|
||||
* 응답 본문은 저장된 원본 파일명 문자열이다.
|
||||
*/
|
||||
export function useUploadRequestFormMutation() {
|
||||
const client = useQueryClient();
|
||||
return useMutation({
|
||||
mutationFn: ({ performanceId, formType, formData }: { performanceId: string; formType: RequestFormType; formData: FormData }) =>
|
||||
nextApi.postForm<string>(requestFormPath(performanceId, formType), formData),
|
||||
onSuccess: () => client.invalidateQueries({ queryKey: queryKeys.performance.all }),
|
||||
});
|
||||
}
|
||||
|
||||
/*
|
||||
* 신청서 파일 다운로드. Blob으로 받아 Content-Disposition의 파일명으로 저장한다.
|
||||
* 파일이 없으면 404(HttpError)로 전파된다.
|
||||
*/
|
||||
export function useDownloadRequestFormMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({ performanceId, formType }: { performanceId: string; formType: RequestFormType }) =>
|
||||
downloadFromApiUrl(requestFormDownloadUrl(performanceId, formType)),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -139,3 +139,25 @@ export type PerformanceFull = PerformanceCompact & {
|
||||
performanceAssignList: PerformanceAssign[];
|
||||
performanceReviewMap: Record<string, PerformanceReview>;
|
||||
};
|
||||
|
||||
// Request Form (공연별 신청서 파일)
|
||||
export const REQUEST_FORM_TYPE = {
|
||||
PUBLIC_OFFERING: 1, // 공모신청서
|
||||
ISSUANCE: 2, // 교부신청서
|
||||
} as const;
|
||||
|
||||
export type RequestFormType = typeof REQUEST_FORM_TYPE[keyof typeof REQUEST_FORM_TYPE];
|
||||
|
||||
/*
|
||||
* performanceDetail에 양식별 파일명이 담기는 key.
|
||||
* 값은 파일명만이며 저장 경로가 아니므로, 다운로드는 반드시 다운로드 API를 호출한다.
|
||||
*/
|
||||
export const REQUEST_FORM_DETAIL_KEY: Record<RequestFormType, string> = {
|
||||
[REQUEST_FORM_TYPE.PUBLIC_OFFERING]: "PublicOfferingRequestForm",
|
||||
[REQUEST_FORM_TYPE.ISSUANCE]: "IssuanceRequestForm",
|
||||
};
|
||||
|
||||
export const REQUEST_FORM_LABEL: Record<RequestFormType, string> = {
|
||||
[REQUEST_FORM_TYPE.PUBLIC_OFFERING]: "공모신청서",
|
||||
[REQUEST_FORM_TYPE.ISSUANCE]: "교부신청서",
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user