496 lines
16 KiB
TypeScript
496 lines
16 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useRef, useState } from "react";
|
|
import { Controller, useFormContext } from "react-hook-form";
|
|
|
|
import { useQueryClient } from "@tanstack/react-query";
|
|
import { Download } from "lucide-react";
|
|
|
|
import { ENDPOINT } from "@/shared/config";
|
|
import { useTus } from "@/shared/lib";
|
|
import type { AtflMngClientResponseDto, EsntlAtchFileMngTreeResponseDto } from "@/shared/model";
|
|
import {
|
|
AttachmentFileField,
|
|
FileAddButton,
|
|
SectionCollapsible,
|
|
UploadedFileChip,
|
|
} from "@/shared/ui";
|
|
import { attachService, useDownloadAttachmentByAtflCd, useDownloadAttachmentByAtflId } from "@/entities/attach";
|
|
import { useEsntlAtchFileMngTree } from "@/entities/esntl";
|
|
import {
|
|
Button,
|
|
Skeleton,
|
|
Table,
|
|
TableBody,
|
|
TableCell,
|
|
TableHead,
|
|
TableHeader,
|
|
TableRow,
|
|
} from "@common/components";
|
|
|
|
import {
|
|
atchFileGroupIdPath,
|
|
createEtcUploadKey,
|
|
createUploadKey,
|
|
type FieldPrefix,
|
|
isEtcFileKey,
|
|
toFileAccept,
|
|
} from "../lib/attachments-form-utils";
|
|
|
|
interface AttachmentsFormData {
|
|
esntlAtchFileList: Array<{
|
|
esntlAtchFileId: string;
|
|
atchFileGroupId: string;
|
|
}>;
|
|
}
|
|
|
|
interface AttachmentsFormSectionProps {
|
|
docSeComCd: string;
|
|
fieldPrefix: FieldPrefix;
|
|
initialEsntlFiles?: EsntlAtchFileMngTreeResponseDto[];
|
|
initialEtcFiles?: AtflMngClientResponseDto[];
|
|
}
|
|
|
|
interface UploadedFileItem {
|
|
file?: File;
|
|
fileName: string;
|
|
fileKey: string;
|
|
atflId?: string;
|
|
atflCd?: string;
|
|
}
|
|
|
|
interface EtcFileItem {
|
|
file?: File;
|
|
fileName: string;
|
|
fileKey: string;
|
|
atflId?: string;
|
|
atflCd?: string;
|
|
}
|
|
|
|
interface UploadMapping {
|
|
esntlAtchFileId: string;
|
|
file: File;
|
|
}
|
|
|
|
function AttachmentsFormSection({
|
|
docSeComCd,
|
|
fieldPrefix,
|
|
initialEsntlFiles,
|
|
initialEtcFiles,
|
|
}: AttachmentsFormSectionProps) {
|
|
const { control, getValues, setValue } = useFormContext<AttachmentsFormData>();
|
|
const queryClient = useQueryClient();
|
|
const [uploadedFiles, setUploadedFiles] = useState<Record<string, UploadedFileItem[]>>({});
|
|
const [etcFiles, setEtcFiles] = useState<EtcFileItem[]>([]);
|
|
const initialFilesMappedRef = useRef(false);
|
|
|
|
const uploadMappingRef = useRef<Map<string, UploadMapping>>(new Map());
|
|
const atflCdBySlotRef = useRef<Record<string, string>>({});
|
|
|
|
const atchGroupPath = atchFileGroupIdPath(fieldPrefix);
|
|
|
|
function getAtchFileGroupId(): string {
|
|
return (getValues as (name: string) => string | undefined)(atchGroupPath) ?? "";
|
|
}
|
|
|
|
function setAtchFileGroupId(value: string) {
|
|
(setValue as (name: string, value: string, options?: { shouldDirty?: boolean }) => void)(
|
|
atchGroupPath,
|
|
value,
|
|
{ shouldDirty: true },
|
|
);
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (initialFilesMappedRef.current) return;
|
|
if (!initialEsntlFiles?.length && !initialEtcFiles?.length) return;
|
|
|
|
if (initialEsntlFiles?.length) {
|
|
const nextUploadedFiles: Record<string, UploadedFileItem[]> = {};
|
|
|
|
for (const slot of initialEsntlFiles) {
|
|
if (!slot.esntlAtchFileId) continue;
|
|
|
|
const files = (slot.atchFileList ?? []).filter((file) => file.atflId && file.atflCd);
|
|
if (files.length === 0) continue;
|
|
|
|
const [firstFile] = files;
|
|
if (!firstFile) continue;
|
|
|
|
nextUploadedFiles[slot.esntlAtchFileId] = files.map((file) => ({
|
|
fileName: file.orgnlFileNm ?? "첨부파일",
|
|
fileKey: `server::${slot.esntlAtchFileId}::${file.atflId}`,
|
|
atflId: file.atflId,
|
|
atflCd: file.atflCd,
|
|
}));
|
|
atflCdBySlotRef.current[slot.esntlAtchFileId] = firstFile.atflCd;
|
|
}
|
|
|
|
setUploadedFiles(nextUploadedFiles);
|
|
}
|
|
|
|
if (initialEtcFiles?.length) {
|
|
setEtcFiles(
|
|
initialEtcFiles.map((file) => ({
|
|
fileName: file.orgnlFileNm ?? "첨부파일",
|
|
fileKey: `server::etc::${file.atflId}`,
|
|
atflId: file.atflId,
|
|
atflCd: file.atflCd,
|
|
})),
|
|
);
|
|
}
|
|
|
|
initialFilesMappedRef.current = true;
|
|
}, [initialEsntlFiles, initialEtcFiles]);
|
|
|
|
const { uploadFileAsync, isUploading, uploads } = useTus({
|
|
onSuccess: (atflCd, atflId, _file, fileKey) => {
|
|
if (!atflCd || !atflId) return;
|
|
|
|
if (isEtcFileKey(fileKey)) {
|
|
if (!getAtchFileGroupId()) {
|
|
setAtchFileGroupId(atflCd);
|
|
}
|
|
|
|
setEtcFiles((prev) =>
|
|
prev.map((item) => (item.fileKey === fileKey ? { ...item, atflCd, atflId } : item)),
|
|
);
|
|
return;
|
|
}
|
|
|
|
const mapping = uploadMappingRef.current.get(fileKey);
|
|
if (!mapping) return;
|
|
|
|
const { esntlAtchFileId } = mapping;
|
|
atflCdBySlotRef.current[esntlAtchFileId] = atflCd;
|
|
|
|
setUploadedFiles((prev) => ({
|
|
...prev,
|
|
[esntlAtchFileId]: (prev[esntlAtchFileId] ?? []).map((item) =>
|
|
item.fileKey === fileKey ? { ...item, atflCd, atflId } : item,
|
|
),
|
|
}));
|
|
|
|
const currentList = getValues("esntlAtchFileList");
|
|
const existingIndex = currentList.findIndex(
|
|
(item) => item.esntlAtchFileId === esntlAtchFileId,
|
|
);
|
|
|
|
if (existingIndex >= 0) {
|
|
const nextList = [...currentList];
|
|
nextList[existingIndex] = { esntlAtchFileId, atchFileGroupId: atflCd };
|
|
setValue("esntlAtchFileList", nextList, { shouldDirty: true });
|
|
} else {
|
|
setValue(
|
|
"esntlAtchFileList",
|
|
[...currentList, { esntlAtchFileId, atchFileGroupId: atflCd }],
|
|
{ shouldDirty: true },
|
|
);
|
|
}
|
|
|
|
uploadMappingRef.current.delete(fileKey);
|
|
},
|
|
onError: (_error, _file, fileKey) => {
|
|
if (isEtcFileKey(fileKey)) {
|
|
setEtcFiles((prev) => prev.filter((item) => item.fileKey !== fileKey));
|
|
return;
|
|
}
|
|
|
|
uploadMappingRef.current.delete(fileKey);
|
|
|
|
setUploadedFiles((prev) => {
|
|
const next = { ...prev };
|
|
|
|
Object.keys(next).forEach((esntlAtchFileId) => {
|
|
next[esntlAtchFileId] = next[esntlAtchFileId].filter((item) => item.fileKey !== fileKey);
|
|
if (next[esntlAtchFileId].length === 0) {
|
|
delete next[esntlAtchFileId];
|
|
}
|
|
});
|
|
|
|
return next;
|
|
});
|
|
},
|
|
});
|
|
|
|
const { data: essentialFiles = [], isPending: isLoadingEssentialFiles } = useEsntlAtchFileMngTree(
|
|
{ docSeComCd },
|
|
);
|
|
const { mutate: downloadTemplate } = useDownloadAttachmentByAtflCd();
|
|
const { mutate: downloadByAtflId } = useDownloadAttachmentByAtflId();
|
|
|
|
async function invalidateAttachmentQueries() {
|
|
await queryClient.invalidateQueries({
|
|
queryKey: [ENDPOINT.AS_SERVICE.ESNTL_ATCH_FILE, "tree", { docSeComCd }],
|
|
});
|
|
await queryClient.invalidateQueries({
|
|
queryKey: [ENDPOINT.ATTACH_SERVICE.ATTACHMENTS],
|
|
});
|
|
}
|
|
|
|
async function handleEtcFileUpload(files: FileList | null) {
|
|
if (!files || files.length === 0) return;
|
|
|
|
const fileArray = Array.from(files);
|
|
let etcAtflCd = getAtchFileGroupId();
|
|
|
|
for (const file of fileArray) {
|
|
const fileKey = createEtcUploadKey(file);
|
|
|
|
setEtcFiles((prev) => [...prev, { file, fileName: file.name, fileKey }]);
|
|
|
|
try {
|
|
const atflCd = await uploadFileAsync(file, {
|
|
fileKey,
|
|
metadata: etcAtflCd ? { atflCd: etcAtflCd } : undefined,
|
|
});
|
|
|
|
if (!etcAtflCd) {
|
|
etcAtflCd = atflCd;
|
|
setAtchFileGroupId(atflCd);
|
|
}
|
|
} catch {
|
|
// onError callback handles cleanup
|
|
}
|
|
}
|
|
}
|
|
|
|
async function removeEtcFile(fileIndex: number) {
|
|
const fileToRemove = etcFiles[fileIndex];
|
|
if (!fileToRemove) return;
|
|
|
|
uploads[fileToRemove.fileKey]?.abort();
|
|
|
|
if (fileToRemove.atflId) {
|
|
try {
|
|
await attachService.deleteAttachmentByAtflId(fileToRemove.atflId);
|
|
await invalidateAttachmentQueries();
|
|
} catch (error) {
|
|
console.error("기타 첨부 파일 삭제 실패:", error);
|
|
}
|
|
}
|
|
|
|
const nextFiles = etcFiles.filter((_, index) => index !== fileIndex);
|
|
setEtcFiles(nextFiles);
|
|
|
|
if (nextFiles.length === 0) {
|
|
setAtchFileGroupId("");
|
|
}
|
|
}
|
|
|
|
async function removeEssentialFile(esntlAtchFileId: string, fileIndex: number) {
|
|
const target = uploadedFiles[esntlAtchFileId]?.[fileIndex];
|
|
if (!target) return;
|
|
|
|
const { fileKey, atflId } = target;
|
|
uploads[fileKey]?.abort();
|
|
uploadMappingRef.current.delete(fileKey);
|
|
|
|
if (atflId) {
|
|
try {
|
|
await attachService.deleteAttachmentByAtflId(atflId);
|
|
await invalidateAttachmentQueries();
|
|
} catch (error) {
|
|
console.error("파일 삭제 실패:", error);
|
|
}
|
|
}
|
|
|
|
const updatedList = (uploadedFiles[esntlAtchFileId] ?? []).filter(
|
|
(_, index) => index !== fileIndex,
|
|
);
|
|
const isSlotEmpty = updatedList.length === 0;
|
|
|
|
setUploadedFiles((prev) => {
|
|
const next = { ...prev };
|
|
|
|
if (isSlotEmpty) {
|
|
delete next[esntlAtchFileId];
|
|
} else {
|
|
next[esntlAtchFileId] = updatedList;
|
|
}
|
|
|
|
return next;
|
|
});
|
|
|
|
if (isSlotEmpty) {
|
|
delete atflCdBySlotRef.current[esntlAtchFileId];
|
|
|
|
const currentList = getValues("esntlAtchFileList");
|
|
setValue(
|
|
"esntlAtchFileList",
|
|
currentList.filter((item) => item.esntlAtchFileId !== esntlAtchFileId),
|
|
{ shouldDirty: true },
|
|
);
|
|
}
|
|
}
|
|
|
|
async function handleEssentialFileUpload(esntlAtchFileId: string, files: FileList | null) {
|
|
if (!files || files.length === 0) return;
|
|
|
|
const fileArray = Array.from(files);
|
|
|
|
for (const file of fileArray) {
|
|
const fileKey = createUploadKey(esntlAtchFileId, file);
|
|
const existingAtflCd = atflCdBySlotRef.current[esntlAtchFileId] ?? "";
|
|
|
|
setUploadedFiles((prev) => ({
|
|
...prev,
|
|
[esntlAtchFileId]: [
|
|
...(prev[esntlAtchFileId] ?? []),
|
|
{ file, fileName: file.name, fileKey },
|
|
],
|
|
}));
|
|
|
|
uploadMappingRef.current.set(fileKey, { esntlAtchFileId, file });
|
|
|
|
try {
|
|
const atflCd = await uploadFileAsync(file, {
|
|
fileKey,
|
|
metadata: existingAtflCd ? { atflCd: existingAtflCd } : undefined,
|
|
});
|
|
|
|
if (!existingAtflCd) {
|
|
atflCdBySlotRef.current[esntlAtchFileId] = atflCd;
|
|
}
|
|
} catch {
|
|
// onError callback handles cleanup
|
|
}
|
|
}
|
|
}
|
|
|
|
if (isLoadingEssentialFiles) {
|
|
return (
|
|
<SectionCollapsible title="첨부파일">
|
|
<div className="space-y-4 p-4">
|
|
<Skeleton className="h-12 w-full" />
|
|
<Skeleton className="h-24 w-full" />
|
|
<Skeleton className="h-24 w-full" />
|
|
</div>
|
|
</SectionCollapsible>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<SectionCollapsible title="첨부파일">
|
|
<div className="space-y-6">
|
|
<Controller
|
|
name="esntlAtchFileList"
|
|
control={control}
|
|
render={() => (
|
|
<div className="px-2">
|
|
<h3 className="mb-4 text-xl font-semibold">필수 첨부파일</h3>
|
|
<Table variant="secondary" className="table-fixed">
|
|
<colgroup>
|
|
<col width="44%" />
|
|
<col width="12%" />
|
|
<col width="44%" />
|
|
</colgroup>
|
|
<TableHeader>
|
|
<TableRow>
|
|
<TableHead className="w-[30rem]" align="left">
|
|
파일명
|
|
</TableHead>
|
|
<TableHead>파일 확장자</TableHead>
|
|
<TableHead>파일첨부</TableHead>
|
|
</TableRow>
|
|
</TableHeader>
|
|
<TableBody>
|
|
{essentialFiles.length === 0 ? (
|
|
<TableRow>
|
|
<TableCell colSpan={4} className="py-12 text-center text-muted-foreground">
|
|
조회된 필수 첨부파일 항목이 없습니다.
|
|
</TableCell>
|
|
</TableRow>
|
|
) : (
|
|
essentialFiles.map((file) => {
|
|
const atflCd = file.atchFileGroupId ?? "";
|
|
|
|
return (
|
|
<TableRow key={file.esntlAtchFileId}>
|
|
<TableHead
|
|
className="group break-keep font-medium"
|
|
data-required={file.esntlAtchYn === "Y"}
|
|
align="left"
|
|
>
|
|
<div className="inline-flex w-[calc(100%-1rem)] items-center justify-between gap-10">
|
|
{file.esntlAtchFileNm}
|
|
{atflCd ? (
|
|
<Button
|
|
size="sm"
|
|
color="white"
|
|
onClick={() => downloadTemplate(atflCd)}
|
|
>
|
|
<Download className="!size-5 shrink-0" />
|
|
양식내려받기
|
|
</Button>
|
|
) : null}
|
|
</div>
|
|
</TableHead>
|
|
<TableCell align="center">{file.esntlAtchFileRmrk}</TableCell>
|
|
<TableCell className="space-y-2">
|
|
<AttachmentFileField
|
|
files={(uploadedFiles[file.esntlAtchFileId] ?? []).map((item) => ({
|
|
fileKey: item.fileKey,
|
|
fileName: item.file?.name ?? item.fileName,
|
|
onDownload: item.atflId
|
|
? () => downloadByAtflId(item.atflId!)
|
|
: undefined,
|
|
}))}
|
|
inputId={`${file.esntlAtchFileId}-file-input`}
|
|
isUploadingByKey={isUploading}
|
|
accept={toFileAccept(file.esntlAtchFileRmrk) || undefined}
|
|
onAdd={(fileList) =>
|
|
void handleEssentialFileUpload(file.esntlAtchFileId, fileList)
|
|
}
|
|
onRemove={(index) =>
|
|
void removeEssentialFile(file.esntlAtchFileId, index)
|
|
}
|
|
/>
|
|
</TableCell>
|
|
</TableRow>
|
|
);
|
|
})
|
|
)}
|
|
</TableBody>
|
|
</Table>
|
|
</div>
|
|
)}
|
|
/>
|
|
|
|
<div className="px-2">
|
|
<div className="mb-4 flex items-center justify-between">
|
|
<h3 className="text-xl font-semibold">기타 첨부파일</h3>
|
|
<FileAddButton
|
|
inputId="etc-file-input"
|
|
onFilesSelected={(files) => void handleEtcFileUpload(files)}
|
|
/>
|
|
</div>
|
|
<div className="rounded border p-4">
|
|
{etcFiles.length > 0 ? (
|
|
<div className="flex flex-wrap gap-2">
|
|
{etcFiles.map((item, idx) => (
|
|
<UploadedFileChip
|
|
key={item.fileKey}
|
|
fileName={item.file?.name ?? item.fileName}
|
|
isUploading={isUploading[item.fileKey] ?? false}
|
|
onRemove={() => void removeEtcFile(idx)}
|
|
onDownload={
|
|
item.atflId ? () => downloadByAtflId(item.atflId!) : undefined
|
|
}
|
|
/>
|
|
))}
|
|
</div>
|
|
) : (
|
|
<div className="flex items-center justify-center py-6 text-center text-xl text-muted-foreground">
|
|
파일을 추가해주세요
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</SectionCollapsible>
|
|
);
|
|
}
|
|
|
|
export { AttachmentsFormSection };
|