241 lines
11 KiB
TypeScript
241 lines
11 KiB
TypeScript
import * as XLSX from "xlsx";
|
|
|
|
import { formatDate } from "../../common/util";
|
|
import type { ObsltPplBusiness, ObsltPplBusinessSaveRequest } from "../model/obslt-ppl-types";
|
|
|
|
type BusinessType = ObsltPplBusinessSaveRequest["bizSe"];
|
|
|
|
type SheetContract = {
|
|
sheetName: BusinessType;
|
|
businessCodeHeader: string;
|
|
extensionHeader: string;
|
|
progressHeader: string;
|
|
startDateHeader: string;
|
|
};
|
|
|
|
const SHEET_CONTRACTS: SheetContract[] = [
|
|
{
|
|
sheetName: "정밀조사",
|
|
businessCodeHeader: "정밀조사사업코드",
|
|
extensionHeader: "조사연장(km)",
|
|
progressHeader: "정밀조사추진현황",
|
|
startDateHeader: "착수(예정)일자(yyyy.mm.dd)",
|
|
},
|
|
{
|
|
sheetName: "정비사업",
|
|
businessCodeHeader: "정비사업사업코드",
|
|
extensionHeader: "정비연장(km)",
|
|
progressHeader: "정비사업추진현황",
|
|
startDateHeader: "착공(예정)일자(yyyy.mm.dd)",
|
|
},
|
|
];
|
|
|
|
const DATA_START_ROW_INDEX = 7;
|
|
const FIRST_DATA_COLUMN_INDEX = 1;
|
|
const DATA_COLUMN_COUNT = 21;
|
|
const DOWNLOAD_FILENAME = "노후하수관로 정밀조사 및 정비사업 현황.xlsx";
|
|
|
|
/** 줄바꿈과 공백이 포함된 병합 헤더를 비교 가능한 문자열로 정규화한다. */
|
|
const normalizeHeader = (value: string) => value.replace(/\s+/g, "").trim();
|
|
|
|
/** SheetJS 셀의 화면 표시값을 원본 양식과 같은 문자열로 읽는다. */
|
|
const cellText = (sheet: XLSX.WorkSheet, rowIndex: number, columnIndex: number) => {
|
|
const cell = sheet[XLSX.utils.encode_cell({ r: rowIndex, c: columnIndex })];
|
|
return cell ? XLSX.utils.format_cell(cell).trim() : "";
|
|
};
|
|
|
|
/** 새 업로드 양식의 공통·업무별 핵심 헤더가 정확한 위치에 있는지 확인한다. */
|
|
const validateHeaders = (sheet: XLSX.WorkSheet, contract: SheetContract) => {
|
|
const expectedHeaders: Array<[number, number, string]> = [
|
|
[5, 1, "순번"], [5, 2, "정밀조사차수"], [5, 3, contract.businessCodeHeader],
|
|
[5, 4, "시도"], [5, 5, "시군"], [5, 6, "환경청"], [5, 7, "사업명"],
|
|
[5, 8, "추진현황"], [5, 9, "착수년도"], [5, 10, "준공(예정)년도"],
|
|
[5, 11, contract.extensionHeader], [6, 11, "계획연장(km)"],
|
|
[6, 12, "상반기(예상)연장(km)"], [6, 13, "잔여연장(km)"],
|
|
[6, 14, "증빙서류제출여부"], [5, 15, contract.progressHeader],
|
|
[6, 15, contract.startDateHeader], [6, 16, "준공(예정)일자(yyyy.mm.dd)"],
|
|
[5, 17, "사업추진부진사유"], [5, 18, "사업담당자(지자체)"],
|
|
[6, 18, "이름"], [6, 19, "연락처"], [5, 20, "비고"], [6, 21, "공단의견"],
|
|
];
|
|
|
|
for (const [rowIndex, columnIndex, expected] of expectedHeaders) {
|
|
const actual = normalizeHeader(cellText(sheet, rowIndex, columnIndex));
|
|
if (actual !== normalizeHeader(expected)) {
|
|
const address = XLSX.utils.encode_cell({ r: rowIndex, c: columnIndex });
|
|
throw new Error(
|
|
`${contract.sheetName} 시트 ${address} 헤더가 올바르지 않습니다. 기대값: '${expected}', 실제값: '${actual || "(빈 값)"}'`,
|
|
);
|
|
}
|
|
}
|
|
};
|
|
|
|
/** 빈 셀과 대시 표기를 API의 null 값으로 정규화한다. */
|
|
const optionalText = (value: string): string | null => {
|
|
const normalized = value.trim();
|
|
return !normalized || normalized === "-" ? null : normalized;
|
|
};
|
|
|
|
/** 필수 문자열을 검사하고 시트·행이 포함된 오류를 제공한다. */
|
|
const requiredText = (value: string, sheetName: string, rowNumber: number, fieldName: string) => {
|
|
const normalized = optionalText(value);
|
|
if (!normalized) throw new Error(`${sheetName} 시트 ${rowNumber}행의 ${fieldName} 값은 필수입니다.`);
|
|
return normalized;
|
|
};
|
|
|
|
/** 연장 셀의 콤마와 km 단위를 제거하고 유한한 숫자로 변환한다. */
|
|
const optionalDecimal = (value: string, sheetName: string, rowNumber: number, fieldName: string): number | null => {
|
|
const normalized = optionalText(value)?.replace(/,/g, "").replace(/km/gi, "").trim();
|
|
if (!normalized) return null;
|
|
const parsed = Number(normalized);
|
|
if (!Number.isFinite(parsed)) {
|
|
throw new Error(`${sheetName} 시트 ${rowNumber}행의 ${fieldName} 값이 숫자가 아닙니다.`);
|
|
}
|
|
return parsed;
|
|
};
|
|
|
|
/** 연도 셀은 DB 계약에 맞게 최초 4자리 연도를 보존한다. */
|
|
const yearText = (value: string): string | null => {
|
|
const normalized = optionalText(value);
|
|
if (!normalized) return null;
|
|
return normalized.match(/(19|20)\d{2}/)?.[0] ?? normalized.slice(0, 4);
|
|
};
|
|
|
|
/** 혼합 날짜 표기에서 숫자를 추출하고 DB 최대 길이 8자로 제한한다. */
|
|
const dateText = (value: string): string | null => {
|
|
const normalized = optionalText(value);
|
|
if (!normalized) return null;
|
|
const digits = normalized.replace(/[^0-9]/g, "");
|
|
return (digits || normalized).slice(0, 8);
|
|
};
|
|
|
|
/** B~V가 모두 비어 있는 행은 데이터가 아닌 양식 여백으로 판단한다. */
|
|
const isEmptyDataRow = (sheet: XLSX.WorkSheet, rowIndex: number) =>
|
|
Array.from({ length: DATA_COLUMN_COUNT }, (_, offset) =>
|
|
cellText(sheet, rowIndex, FIRST_DATA_COLUMN_INDEX + offset),
|
|
).every((value) => !value.trim());
|
|
|
|
/** 한 업무 시트의 데이터행을 JSON 저장 요청으로 변환한다. */
|
|
const parseSheet = (sheet: XLSX.WorkSheet, contract: SheetContract): ObsltPplBusinessSaveRequest[] => {
|
|
validateHeaders(sheet, contract);
|
|
const range = XLSX.utils.decode_range(sheet["!ref"] ?? "A1:A1");
|
|
const result: ObsltPplBusinessSaveRequest[] = [];
|
|
|
|
for (let rowIndex = DATA_START_ROW_INDEX; rowIndex <= range.e.r; rowIndex += 1) {
|
|
if (isEmptyDataRow(sheet, rowIndex)) continue;
|
|
const values = Array.from({ length: DATA_COLUMN_COUNT }, (_, offset) =>
|
|
cellText(sheet, rowIndex, FIRST_DATA_COLUMN_INDEX + offset),
|
|
);
|
|
const valueAt = (index: number) => values[index] ?? "";
|
|
const rowNumber = rowIndex + 1;
|
|
const originalBizCd = optionalText(valueAt(2));
|
|
|
|
result.push({
|
|
bizSe: contract.sheetName,
|
|
prcisExmnCycl: optionalText(valueAt(1)),
|
|
bizCd: originalBizCd ?? "",
|
|
sggCd: null,
|
|
ctpvNm: optionalText(valueAt(3)),
|
|
sigunNm: optionalText(valueAt(4)),
|
|
envoNm: optionalText(valueAt(5)),
|
|
bizNm: requiredText(valueAt(6), contract.sheetName, rowNumber, "사업명"),
|
|
prplPrst: optionalText(valueAt(7)),
|
|
bgngYr: yearText(valueAt(8)),
|
|
cmcnYr: yearText(valueAt(9)),
|
|
planPrlg: optionalDecimal(valueAt(10), contract.sheetName, rowNumber, "계획연장(km)"),
|
|
frhfyrExpcPrlg: optionalDecimal(valueAt(11), contract.sheetName, rowNumber, "상반기(예상)연장(km)"),
|
|
rmndPrlg: optionalDecimal(valueAt(12), contract.sheetName, rowNumber, "잔여연장(km)"),
|
|
evdncDcmntSbmsnStts: optionalText(valueAt(13)),
|
|
bgngYmd: dateText(valueAt(14)),
|
|
cmcnYmd: dateText(valueAt(15)),
|
|
bizPrplDlyRsnCn: optionalText(valueAt(16)),
|
|
bizPicNm: optionalText(valueAt(17)),
|
|
bizPicCnpl: optionalText(valueAt(18)),
|
|
rmrkCn: optionalText(valueAt(19)),
|
|
pbcpOpnnCn: optionalText(valueAt(20)),
|
|
});
|
|
}
|
|
return result;
|
|
};
|
|
|
|
/** ArrayBuffer workbook을 검증·파싱하여 두 시트의 JSON 저장 요청을 반환한다. */
|
|
export const parseObsltPplWorkbook = (workbookData: ArrayBuffer | Uint8Array): ObsltPplBusinessSaveRequest[] => {
|
|
const workbook = XLSX.read(workbookData, { type: "array", cellDates: false });
|
|
const rows = SHEET_CONTRACTS.flatMap((contract) => {
|
|
const sheet = workbook.Sheets[contract.sheetName];
|
|
if (!sheet) throw new Error(`필수 시트가 없습니다: ${contract.sheetName}`);
|
|
return parseSheet(sheet, contract);
|
|
});
|
|
if (rows.length === 0) throw new Error("업로드할 사업 자료가 없습니다.");
|
|
return rows;
|
|
};
|
|
|
|
/** 사용자가 선택한 xlsx 파일을 브라우저에서 읽고 JSON 요청 목록으로 변환한다. */
|
|
export const parseObsltPplExcel = async (file: File): Promise<ObsltPplBusinessSaveRequest[]> => {
|
|
if (!file.name.toLowerCase().endsWith(".xlsx")) throw new Error("xlsx 파일만 업로드할 수 있습니다.");
|
|
return parseObsltPplWorkbook(await file.arrayBuffer());
|
|
};
|
|
|
|
/** 업로드 검증과 정확히 같은 B6:V7 위치에 시트별 헤더를 배치한다. */
|
|
const downloadHeaderRows = (contract: SheetContract) => {
|
|
const rows = Array.from({ length: DATA_START_ROW_INDEX }, () => Array<string | number>(22).fill(""));
|
|
const topHeaders = [
|
|
"순번", "정밀조사차수", contract.businessCodeHeader, "시도", "시군", "환경청", "사업명",
|
|
"추진현황", "착수년도", "준공(예정)년도", contract.extensionHeader, "", "", "",
|
|
contract.progressHeader, "", "사업추진부진사유", "사업담당자(지자체)", "", "비고", "",
|
|
];
|
|
const bottomHeaders = [
|
|
"", "", "", "", "", "", "", "", "", "", "계획연장(km)", "상반기(예상)연장(km)",
|
|
"잔여연장(km)", "증빙서류제출여부", contract.startDateHeader, "준공(예정)일자(yyyy.mm.dd)",
|
|
"", "이름", "연락처", "", "공단의견",
|
|
];
|
|
topHeaders.forEach((value, index) => { rows[5]![index + FIRST_DATA_COLUMN_INDEX] = value; });
|
|
bottomHeaders.forEach((value, index) => { rows[6]![index + FIRST_DATA_COLUMN_INDEX] = value; });
|
|
return rows;
|
|
};
|
|
|
|
/** DB에 저장하지 않는 B열 순번을 시트 출력 순서로 만들고 C~V에 업무값을 배치한다. */
|
|
const downloadDataRow = (row: ObsltPplBusiness, index: number): Array<string | number> => [
|
|
"",
|
|
index + 1,
|
|
row.prcisExmnCycl ?? "",
|
|
row.bizCd ?? "",
|
|
row.ctpvNm ?? "",
|
|
row.sigunNm ?? "",
|
|
row.envoNm ?? "",
|
|
row.bizNm ?? "",
|
|
row.prplPrst ?? "",
|
|
row.bgngYr ?? "",
|
|
row.cmcnYr ?? "",
|
|
row.planPrlg ?? "",
|
|
row.frhfyrExpcPrlg ?? "",
|
|
row.rmndPrlg ?? "",
|
|
row.evdncDcmntSbmsnStts ?? "",
|
|
formatDate(row.bgngYmd),
|
|
formatDate(row.cmcnYmd),
|
|
row.bizPrplDlyRsnCn ?? "",
|
|
row.bizPicNm ?? "",
|
|
row.bizPicCnpl ?? "",
|
|
row.rmrkCn ?? "",
|
|
row.pbcpOpnnCn ?? "",
|
|
];
|
|
|
|
/** 조회 결과를 정밀조사·정비사업 두 시트의 재업로드 가능한 위치 구조로 생성한다. */
|
|
export const buildObsltPplWorkbook = (businesses: ObsltPplBusiness[]): XLSX.WorkBook => {
|
|
const workbook = XLSX.utils.book_new();
|
|
SHEET_CONTRACTS.forEach((contract) => {
|
|
const data = businesses.filter((row) => row.bizSe === contract.sheetName);
|
|
const worksheet = XLSX.utils.aoa_to_sheet([
|
|
...downloadHeaderRows(contract),
|
|
...data.map(downloadDataRow),
|
|
]);
|
|
worksheet["!cols"] = Array.from({ length: 22 }, (_, index) => ({ wch: index === 7 ? 30 : 16 }));
|
|
XLSX.utils.book_append_sheet(workbook, worksheet, contract.sheetName);
|
|
});
|
|
return workbook;
|
|
};
|
|
|
|
/** 생성한 두 시트 workbook을 브라우저 다운로드로 저장한다. */
|
|
export const downloadObsltPplExcel = (businesses: ObsltPplBusiness[]) => {
|
|
XLSX.writeFileXLSX(buildObsltPplWorkbook(businesses), DOWNLOAD_FILENAME);
|
|
};
|