Merge remote-tracking branch 'upstream/main'

This commit is contained in:
kjs
2026-01-08 14:59:38 +09:00
40 changed files with 3490 additions and 1222 deletions

View File

@@ -58,6 +58,7 @@ import riskAlertRoutes from "./routes/riskAlertRoutes"; // 리스크/알림 관
import todoRoutes from "./routes/todoRoutes"; // To-Do 관리
import bookingRoutes from "./routes/bookingRoutes"; // 예약 요청 관리
import mapDataRoutes from "./routes/mapDataRoutes"; // 지도 데이터 관리
import excelMappingRoutes from "./routes/excelMappingRoutes"; // 엑셀 매핑 템플릿
import yardLayoutRoutes from "./routes/yardLayoutRoutes"; // 3D 필드
//import materialRoutes from "./routes/materialRoutes"; // 자재 관리
import digitalTwinRoutes from "./routes/digitalTwinRoutes"; // 디지털 트윈 (야드 관제)
@@ -220,6 +221,7 @@ app.use("/api/external-rest-api-connections", externalRestApiConnectionRoutes);
app.use("/api/multi-connection", multiConnectionRoutes);
app.use("/api/screen-files", screenFileRoutes);
app.use("/api/batch-configs", batchRoutes);
app.use("/api/excel-mapping", excelMappingRoutes); // 엑셀 매핑 템플릿
app.use("/api/batch-management", batchManagementRoutes);
app.use("/api/batch-execution-logs", batchExecutionLogRoutes);
// app.use("/api/db-type-categories", dbTypeCategoryRoutes); // 파일이 존재하지 않음

View File

@@ -282,3 +282,175 @@ export async function previewCodeMerge(
}
}
/**
* 값 기반 코드 병합 - 모든 테이블의 모든 컬럼에서 해당 값을 찾아 변경
* 컬럼명에 상관없이 oldValue를 가진 모든 곳을 newValue로 변경
*/
export async function mergeCodeByValue(
req: AuthenticatedRequest,
res: Response
): Promise<void> {
const { oldValue, newValue } = req.body;
const companyCode = req.user?.companyCode;
try {
// 입력값 검증
if (!oldValue || !newValue) {
res.status(400).json({
success: false,
message: "필수 필드가 누락되었습니다. (oldValue, newValue)",
});
return;
}
if (!companyCode) {
res.status(401).json({
success: false,
message: "인증 정보가 없습니다.",
});
return;
}
// 같은 값으로 병합 시도 방지
if (oldValue === newValue) {
res.status(400).json({
success: false,
message: "기존 값과 새 값이 동일합니다.",
});
return;
}
logger.info("값 기반 코드 병합 시작", {
oldValue,
newValue,
companyCode,
userId: req.user?.userId,
});
// PostgreSQL 함수 호출
const result = await pool.query(
"SELECT * FROM merge_code_by_value($1, $2, $3)",
[oldValue, newValue, companyCode]
);
// 결과 처리
const affectedData = Array.isArray(result) ? result : ((result as any).rows || []);
const totalRows = affectedData.reduce(
(sum: number, row: any) => sum + parseInt(row.out_rows_updated || 0),
0
);
logger.info("값 기반 코드 병합 완료", {
oldValue,
newValue,
affectedTablesCount: affectedData.length,
totalRowsUpdated: totalRows,
});
res.json({
success: true,
message: `코드 병합 완료: ${oldValue}${newValue}`,
data: {
oldValue,
newValue,
affectedData: affectedData.map((row: any) => ({
tableName: row.out_table_name,
columnName: row.out_column_name,
rowsUpdated: parseInt(row.out_rows_updated),
})),
totalRowsUpdated: totalRows,
},
});
} catch (error: any) {
logger.error("값 기반 코드 병합 실패:", {
error: error.message,
stack: error.stack,
oldValue,
newValue,
});
res.status(500).json({
success: false,
message: "코드 병합 중 오류가 발생했습니다.",
error: {
code: "CODE_MERGE_BY_VALUE_ERROR",
details: error.message,
},
});
}
}
/**
* 값 기반 코드 병합 미리보기
* 컬럼명에 상관없이 해당 값을 가진 모든 테이블/컬럼 조회
*/
export async function previewMergeCodeByValue(
req: AuthenticatedRequest,
res: Response
): Promise<void> {
const { oldValue } = req.body;
const companyCode = req.user?.companyCode;
try {
if (!oldValue) {
res.status(400).json({
success: false,
message: "필수 필드가 누락되었습니다. (oldValue)",
});
return;
}
if (!companyCode) {
res.status(401).json({
success: false,
message: "인증 정보가 없습니다.",
});
return;
}
logger.info("값 기반 코드 병합 미리보기", { oldValue, companyCode });
// PostgreSQL 함수 호출
const result = await pool.query(
"SELECT * FROM preview_merge_code_by_value($1, $2)",
[oldValue, companyCode]
);
const preview = Array.isArray(result) ? result : ((result as any).rows || []);
const totalRows = preview.reduce(
(sum: number, row: any) => sum + parseInt(row.out_affected_rows || 0),
0
);
logger.info("값 기반 코드 병합 미리보기 완료", {
tablesCount: preview.length,
totalRows,
});
res.json({
success: true,
message: "코드 병합 미리보기 완료",
data: {
oldValue,
preview: preview.map((row: any) => ({
tableName: row.out_table_name,
columnName: row.out_column_name,
affectedRows: parseInt(row.out_affected_rows),
})),
totalAffectedRows: totalRows,
},
});
} catch (error: any) {
logger.error("값 기반 코드 병합 미리보기 실패:", error);
res.status(500).json({
success: false,
message: "코드 병합 미리보기 중 오류가 발생했습니다.",
error: {
code: "PREVIEW_BY_VALUE_ERROR",
details: error.message,
},
});
}
}

View File

@@ -0,0 +1,208 @@
import { Response } from "express";
import { AuthenticatedRequest } from "../middleware/authMiddleware";
import excelMappingService from "../services/excelMappingService";
import { logger } from "../utils/logger";
/**
* 엑셀 컬럼 구조로 매핑 템플릿 조회
* POST /api/excel-mapping/find
*/
export async function findMappingByColumns(
req: AuthenticatedRequest,
res: Response
): Promise<void> {
try {
const { tableName, excelColumns } = req.body;
const companyCode = req.user?.companyCode || "*";
if (!tableName || !excelColumns || !Array.isArray(excelColumns)) {
res.status(400).json({
success: false,
message: "tableName과 excelColumns(배열)가 필요합니다.",
});
return;
}
logger.info("엑셀 매핑 템플릿 조회 요청", {
tableName,
excelColumns,
companyCode,
userId: req.user?.userId,
});
const template = await excelMappingService.findMappingByColumns(
tableName,
excelColumns,
companyCode
);
if (template) {
res.json({
success: true,
data: template,
message: "기존 매핑 템플릿을 찾았습니다.",
});
} else {
res.json({
success: true,
data: null,
message: "일치하는 매핑 템플릿이 없습니다.",
});
}
} catch (error: any) {
logger.error("매핑 템플릿 조회 실패", { error: error.message });
res.status(500).json({
success: false,
message: "매핑 템플릿 조회 중 오류가 발생했습니다.",
error: error.message,
});
}
}
/**
* 매핑 템플릿 저장 (UPSERT)
* POST /api/excel-mapping/save
*/
export async function saveMappingTemplate(
req: AuthenticatedRequest,
res: Response
): Promise<void> {
try {
const { tableName, excelColumns, columnMappings } = req.body;
const companyCode = req.user?.companyCode || "*";
const userId = req.user?.userId;
if (!tableName || !excelColumns || !columnMappings) {
res.status(400).json({
success: false,
message: "tableName, excelColumns, columnMappings가 필요합니다.",
});
return;
}
logger.info("엑셀 매핑 템플릿 저장 요청", {
tableName,
excelColumns,
columnMappings,
companyCode,
userId,
});
const template = await excelMappingService.saveMappingTemplate(
tableName,
excelColumns,
columnMappings,
companyCode,
userId
);
res.json({
success: true,
data: template,
message: "매핑 템플릿이 저장되었습니다.",
});
} catch (error: any) {
logger.error("매핑 템플릿 저장 실패", { error: error.message });
res.status(500).json({
success: false,
message: "매핑 템플릿 저장 중 오류가 발생했습니다.",
error: error.message,
});
}
}
/**
* 테이블의 매핑 템플릿 목록 조회
* GET /api/excel-mapping/list/:tableName
*/
export async function getMappingTemplates(
req: AuthenticatedRequest,
res: Response
): Promise<void> {
try {
const { tableName } = req.params;
const companyCode = req.user?.companyCode || "*";
if (!tableName) {
res.status(400).json({
success: false,
message: "tableName이 필요합니다.",
});
return;
}
logger.info("매핑 템플릿 목록 조회 요청", {
tableName,
companyCode,
});
const templates = await excelMappingService.getMappingTemplates(
tableName,
companyCode
);
res.json({
success: true,
data: templates,
});
} catch (error: any) {
logger.error("매핑 템플릿 목록 조회 실패", { error: error.message });
res.status(500).json({
success: false,
message: "매핑 템플릿 목록 조회 중 오류가 발생했습니다.",
error: error.message,
});
}
}
/**
* 매핑 템플릿 삭제
* DELETE /api/excel-mapping/:id
*/
export async function deleteMappingTemplate(
req: AuthenticatedRequest,
res: Response
): Promise<void> {
try {
const { id } = req.params;
const companyCode = req.user?.companyCode || "*";
if (!id) {
res.status(400).json({
success: false,
message: "id가 필요합니다.",
});
return;
}
logger.info("매핑 템플릿 삭제 요청", {
id,
companyCode,
});
const deleted = await excelMappingService.deleteMappingTemplate(
parseInt(id),
companyCode
);
if (deleted) {
res.json({
success: true,
message: "매핑 템플릿이 삭제되었습니다.",
});
} else {
res.status(404).json({
success: false,
message: "삭제할 매핑 템플릿을 찾을 수 없습니다.",
});
}
} catch (error: any) {
logger.error("매핑 템플릿 삭제 실패", { error: error.message });
res.status(500).json({
success: false,
message: "매핑 템플릿 삭제 중 오류가 발생했습니다.",
error: error.message,
});
}
}

View File

@@ -3,6 +3,8 @@ import {
mergeCodeAllTables,
getTablesWithColumn,
previewCodeMerge,
mergeCodeByValue,
previewMergeCodeByValue,
} from "../controllers/codeMergeController";
import { authenticateToken } from "../middleware/authMiddleware";
@@ -13,7 +15,7 @@ router.use(authenticateToken);
/**
* POST /api/code-merge/merge-all-tables
* 코드 병합 실행 (모든 관련 테이블에 적용)
* 코드 병합 실행 (모든 관련 테이블에 적용 - 같은 컬럼명만)
* Body: { columnName, oldValue, newValue }
*/
router.post("/merge-all-tables", mergeCodeAllTables);
@@ -26,10 +28,24 @@ router.get("/tables-with-column/:columnName", getTablesWithColumn);
/**
* POST /api/code-merge/preview
* 코드 병합 미리보기 (실제 실행 없이 영향받을 데이터 확인)
* 코드 병합 미리보기 (같은 컬럼명 기준)
* Body: { columnName, oldValue }
*/
router.post("/preview", previewCodeMerge);
/**
* POST /api/code-merge/merge-by-value
* 값 기반 코드 병합 (모든 테이블의 모든 컬럼에서 해당 값을 찾아 변경)
* Body: { oldValue, newValue }
*/
router.post("/merge-by-value", mergeCodeByValue);
/**
* POST /api/code-merge/preview-by-value
* 값 기반 코드 병합 미리보기 (컬럼명 상관없이 값으로 검색)
* Body: { oldValue }
*/
router.post("/preview-by-value", previewMergeCodeByValue);
export default router;

View File

@@ -698,6 +698,7 @@ router.post(
try {
const { tableName } = req.params;
const filterConditions = req.body;
const userCompany = req.user?.companyCode;
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)) {
return res.status(400).json({
@@ -706,11 +707,12 @@ router.post(
});
}
console.log(`🗑️ 그룹 삭제:`, { tableName, filterConditions });
console.log(`🗑️ 그룹 삭제:`, { tableName, filterConditions, userCompany });
const result = await dataService.deleteGroupRecords(
tableName,
filterConditions
filterConditions,
userCompany // 회사 코드 전달
);
if (!result.success) {

View File

@@ -0,0 +1,25 @@
import { Router } from "express";
import { authenticateToken } from "../middleware/authMiddleware";
import {
findMappingByColumns,
saveMappingTemplate,
getMappingTemplates,
deleteMappingTemplate,
} from "../controllers/excelMappingController";
const router = Router();
// 엑셀 컬럼 구조로 매핑 템플릿 조회
router.post("/find", authenticateToken, findMappingByColumns);
// 매핑 템플릿 저장 (UPSERT)
router.post("/save", authenticateToken, saveMappingTemplate);
// 테이블의 매핑 템플릿 목록 조회
router.get("/list/:tableName", authenticateToken, getMappingTemplates);
// 매핑 템플릿 삭제
router.delete("/:id", authenticateToken, deleteMappingTemplate);
export default router;

View File

@@ -1189,6 +1189,13 @@ class DataService {
[tableName]
);
console.log(`🔍 테이블 ${tableName}의 Primary Key 조회 결과:`, {
pkColumns: pkResult.map((r) => r.attname),
pkCount: pkResult.length,
inputId: typeof id === "object" ? JSON.stringify(id).substring(0, 200) + "..." : id,
inputIdType: typeof id,
});
let whereClauses: string[] = [];
let params: any[] = [];
@@ -1216,17 +1223,31 @@ class DataService {
params.push(typeof id === "object" ? id[pkColumn] : id);
}
const queryText = `DELETE FROM "${tableName}" WHERE ${whereClauses.join(" AND ")}`;
const queryText = `DELETE FROM "${tableName}" WHERE ${whereClauses.join(" AND ")} RETURNING *`;
console.log(`🗑️ 삭제 쿼리:`, queryText, params);
const result = await query<any>(queryText, params);
// 삭제된 행이 없으면 실패 처리
if (result.length === 0) {
console.warn(
`⚠️ 레코드 삭제 실패: ${tableName}, 해당 조건에 맞는 레코드가 없습니다.`,
{ whereClauses, params }
);
return {
success: false,
message: "삭제할 레코드를 찾을 수 없습니다. 이미 삭제되었거나 권한이 없습니다.",
error: "RECORD_NOT_FOUND",
};
}
console.log(
`✅ 레코드 삭제 완료: ${tableName}, 영향받은 행: ${result.length}`
);
return {
success: true,
data: result[0], // 삭제된 레코드 정보 반환
};
} catch (error) {
console.error(`레코드 삭제 오류 (${tableName}):`, error);
@@ -1240,10 +1261,14 @@ class DataService {
/**
* 조건에 맞는 모든 레코드 삭제 (그룹 삭제)
* @param tableName 테이블명
* @param filterConditions 삭제 조건
* @param userCompany 사용자 회사 코드 (멀티테넌시 필터링)
*/
async deleteGroupRecords(
tableName: string,
filterConditions: Record<string, any>
filterConditions: Record<string, any>,
userCompany?: string
): Promise<ServiceResponse<{ deleted: number }>> {
try {
const validation = await this.validateTableAccess(tableName);
@@ -1255,6 +1280,7 @@ class DataService {
const whereValues: any[] = [];
let paramIndex = 1;
// 사용자 필터 조건 추가
for (const [key, value] of Object.entries(filterConditions)) {
whereConditions.push(`"${key}" = $${paramIndex}`);
whereValues.push(value);
@@ -1269,10 +1295,24 @@ class DataService {
};
}
// 🔒 멀티테넌시: company_code 필터링 (최고 관리자 제외)
const hasCompanyCode = await this.checkColumnExists(tableName, "company_code");
if (hasCompanyCode && userCompany && userCompany !== "*") {
whereConditions.push(`"company_code" = $${paramIndex}`);
whereValues.push(userCompany);
paramIndex++;
console.log(`🔒 멀티테넌시 필터 적용: company_code = ${userCompany}`);
}
const whereClause = whereConditions.join(" AND ");
const deleteQuery = `DELETE FROM "${tableName}" WHERE ${whereClause} RETURNING *`;
console.log(`🗑️ 그룹 삭제:`, { tableName, conditions: filterConditions });
console.log(`🗑️ 그룹 삭제:`, {
tableName,
conditions: filterConditions,
userCompany,
whereClause,
});
const result = await pool.query(deleteQuery, whereValues);

View File

@@ -1,6 +1,7 @@
import { query, queryOne, transaction, getPool } from "../database/db";
import { EventTriggerService } from "./eventTriggerService";
import { DataflowControlService } from "./dataflowControlService";
import tableCategoryValueService from "./tableCategoryValueService";
export interface FormDataResult {
id: number;
@@ -427,6 +428,24 @@ export class DynamicFormService {
dataToInsert,
});
// 카테고리 타입 컬럼의 라벨 값을 코드 값으로 변환 (엑셀 업로드 등 지원)
console.log("🏷️ 카테고리 라벨→코드 변환 시작...");
const companyCodeForCategory = company_code || "*";
const { convertedData: categoryConvertedData, conversions } =
await tableCategoryValueService.convertCategoryLabelsToCodesForData(
tableName,
companyCodeForCategory,
dataToInsert
);
if (conversions.length > 0) {
console.log(`🏷️ 카테고리 라벨→코드 변환 완료: ${conversions.length}`, conversions);
// 변환된 데이터로 교체
Object.assign(dataToInsert, categoryConvertedData);
} else {
console.log("🏷️ 카테고리 라벨→코드 변환 없음 (카테고리 컬럼 없거나 이미 코드 값)");
}
// 테이블 컬럼 정보 조회하여 타입 변환 적용
console.log("🔍 테이블 컬럼 정보 조회 중...");
const columnInfo = await this.getTableColumnInfo(tableName);

View File

@@ -0,0 +1,283 @@
import { getPool } from "../database/db";
import { logger } from "../utils/logger";
import crypto from "crypto";
export interface ExcelMappingTemplate {
id?: number;
tableName: string;
excelColumns: string[];
excelColumnsHash: string;
columnMappings: Record<string, string | null>; // { "엑셀컬럼": "시스템컬럼" }
companyCode: string;
createdDate?: Date;
updatedDate?: Date;
}
class ExcelMappingService {
/**
* 엑셀 컬럼 목록으로 해시 생성
* 정렬 후 MD5 해시 생성하여 동일한 컬럼 구조 식별
*/
generateColumnsHash(columns: string[]): string {
// 컬럼 목록을 정렬하여 순서와 무관하게 동일한 해시 생성
const sortedColumns = [...columns].sort();
const columnsString = sortedColumns.join("|");
return crypto.createHash("md5").update(columnsString).digest("hex");
}
/**
* 엑셀 컬럼 구조로 매핑 템플릿 조회
* 동일한 컬럼 구조가 있으면 기존 매핑 반환
*/
async findMappingByColumns(
tableName: string,
excelColumns: string[],
companyCode: string
): Promise<ExcelMappingTemplate | null> {
try {
const hash = this.generateColumnsHash(excelColumns);
logger.info("엑셀 매핑 템플릿 조회", {
tableName,
excelColumns,
hash,
companyCode,
});
const pool = getPool();
// 회사별 매핑 먼저 조회, 없으면 공통(*) 매핑 조회
let query: string;
let params: any[];
if (companyCode === "*") {
query = `
SELECT
id,
table_name as "tableName",
excel_columns as "excelColumns",
excel_columns_hash as "excelColumnsHash",
column_mappings as "columnMappings",
company_code as "companyCode",
created_date as "createdDate",
updated_date as "updatedDate"
FROM excel_mapping_template
WHERE table_name = $1
AND excel_columns_hash = $2
ORDER BY updated_date DESC
LIMIT 1
`;
params = [tableName, hash];
} else {
query = `
SELECT
id,
table_name as "tableName",
excel_columns as "excelColumns",
excel_columns_hash as "excelColumnsHash",
column_mappings as "columnMappings",
company_code as "companyCode",
created_date as "createdDate",
updated_date as "updatedDate"
FROM excel_mapping_template
WHERE table_name = $1
AND excel_columns_hash = $2
AND (company_code = $3 OR company_code = '*')
ORDER BY
CASE WHEN company_code = $3 THEN 0 ELSE 1 END,
updated_date DESC
LIMIT 1
`;
params = [tableName, hash, companyCode];
}
const result = await pool.query(query, params);
if (result.rows.length > 0) {
logger.info("기존 매핑 템플릿 발견", {
id: result.rows[0].id,
tableName,
});
return result.rows[0];
}
logger.info("매핑 템플릿 없음 - 새 구조", { tableName, hash });
return null;
} catch (error: any) {
logger.error(`매핑 템플릿 조회 실패: ${error.message}`, { error });
throw error;
}
}
/**
* 매핑 템플릿 저장 (UPSERT)
* 동일한 테이블+컬럼구조+회사코드가 있으면 업데이트, 없으면 삽입
*/
async saveMappingTemplate(
tableName: string,
excelColumns: string[],
columnMappings: Record<string, string | null>,
companyCode: string,
userId?: string
): Promise<ExcelMappingTemplate> {
try {
const hash = this.generateColumnsHash(excelColumns);
logger.info("엑셀 매핑 템플릿 저장 (UPSERT)", {
tableName,
excelColumns,
hash,
columnMappings,
companyCode,
});
const pool = getPool();
const query = `
INSERT INTO excel_mapping_template (
table_name,
excel_columns,
excel_columns_hash,
column_mappings,
company_code,
created_date,
updated_date
) VALUES ($1, $2, $3, $4, $5, NOW(), NOW())
ON CONFLICT (table_name, excel_columns_hash, company_code)
DO UPDATE SET
column_mappings = EXCLUDED.column_mappings,
updated_date = NOW()
RETURNING
id,
table_name as "tableName",
excel_columns as "excelColumns",
excel_columns_hash as "excelColumnsHash",
column_mappings as "columnMappings",
company_code as "companyCode",
created_date as "createdDate",
updated_date as "updatedDate"
`;
const result = await pool.query(query, [
tableName,
excelColumns,
hash,
JSON.stringify(columnMappings),
companyCode,
]);
logger.info("매핑 템플릿 저장 완료", {
id: result.rows[0].id,
tableName,
hash,
});
return result.rows[0];
} catch (error: any) {
logger.error(`매핑 템플릿 저장 실패: ${error.message}`, { error });
throw error;
}
}
/**
* 테이블의 모든 매핑 템플릿 조회
*/
async getMappingTemplates(
tableName: string,
companyCode: string
): Promise<ExcelMappingTemplate[]> {
try {
logger.info("테이블 매핑 템플릿 목록 조회", { tableName, companyCode });
const pool = getPool();
let query: string;
let params: any[];
if (companyCode === "*") {
query = `
SELECT
id,
table_name as "tableName",
excel_columns as "excelColumns",
excel_columns_hash as "excelColumnsHash",
column_mappings as "columnMappings",
company_code as "companyCode",
created_date as "createdDate",
updated_date as "updatedDate"
FROM excel_mapping_template
WHERE table_name = $1
ORDER BY updated_date DESC
`;
params = [tableName];
} else {
query = `
SELECT
id,
table_name as "tableName",
excel_columns as "excelColumns",
excel_columns_hash as "excelColumnsHash",
column_mappings as "columnMappings",
company_code as "companyCode",
created_date as "createdDate",
updated_date as "updatedDate"
FROM excel_mapping_template
WHERE table_name = $1
AND (company_code = $2 OR company_code = '*')
ORDER BY updated_date DESC
`;
params = [tableName, companyCode];
}
const result = await pool.query(query, params);
logger.info(`매핑 템플릿 ${result.rows.length}개 조회`, { tableName });
return result.rows;
} catch (error: any) {
logger.error(`매핑 템플릿 목록 조회 실패: ${error.message}`, { error });
throw error;
}
}
/**
* 매핑 템플릿 삭제
*/
async deleteMappingTemplate(
id: number,
companyCode: string
): Promise<boolean> {
try {
logger.info("매핑 템플릿 삭제", { id, companyCode });
const pool = getPool();
let query: string;
let params: any[];
if (companyCode === "*") {
query = `DELETE FROM excel_mapping_template WHERE id = $1`;
params = [id];
} else {
query = `DELETE FROM excel_mapping_template WHERE id = $1 AND company_code = $2`;
params = [id, companyCode];
}
const result = await pool.query(query, params);
if (result.rowCount && result.rowCount > 0) {
logger.info("매핑 템플릿 삭제 완료", { id });
return true;
}
logger.warn("삭제할 매핑 템플릿 없음", { id, companyCode });
return false;
} catch (error: any) {
logger.error(`매핑 템플릿 삭제 실패: ${error.message}`, { error });
throw error;
}
}
}
export default new ExcelMappingService();

View File

@@ -1398,6 +1398,220 @@ class TableCategoryValueService {
throw error;
}
}
/**
* 테이블의 카테고리 타입 컬럼과 해당 값 매핑 조회 (라벨 → 코드 변환용)
*
* 엑셀 업로드 등에서 라벨 값을 코드 값으로 변환할 때 사용
*
* @param tableName - 테이블명
* @param companyCode - 회사 코드
* @returns { [columnName]: { [label]: code } } 형태의 매핑 객체
*/
async getCategoryLabelToCodeMapping(
tableName: string,
companyCode: string
): Promise<Record<string, Record<string, string>>> {
try {
logger.info("카테고리 라벨→코드 매핑 조회", { tableName, companyCode });
const pool = getPool();
// 1. 해당 테이블의 카테고리 타입 컬럼 조회
const categoryColumnsQuery = `
SELECT column_name
FROM table_type_columns
WHERE table_name = $1
AND input_type = 'category'
`;
const categoryColumnsResult = await pool.query(categoryColumnsQuery, [tableName]);
if (categoryColumnsResult.rows.length === 0) {
logger.info("카테고리 타입 컬럼 없음", { tableName });
return {};
}
const categoryColumns = categoryColumnsResult.rows.map(row => row.column_name);
logger.info(`카테고리 컬럼 ${categoryColumns.length}개 발견`, { categoryColumns });
// 2. 각 카테고리 컬럼의 라벨→코드 매핑 조회
const result: Record<string, Record<string, string>> = {};
for (const columnName of categoryColumns) {
let query: string;
let params: any[];
if (companyCode === "*") {
// 최고 관리자: 모든 카테고리 값 조회
query = `
SELECT value_code, value_label
FROM table_column_category_values
WHERE table_name = $1
AND column_name = $2
AND is_active = true
`;
params = [tableName, columnName];
} else {
// 일반 회사: 자신의 카테고리 값 + 공통 카테고리 값 조회
query = `
SELECT value_code, value_label
FROM table_column_category_values
WHERE table_name = $1
AND column_name = $2
AND is_active = true
AND (company_code = $3 OR company_code = '*')
`;
params = [tableName, columnName, companyCode];
}
const valuesResult = await pool.query(query, params);
// { [label]: code } 형태로 변환
const labelToCodeMap: Record<string, string> = {};
for (const row of valuesResult.rows) {
// 라벨을 소문자로 변환하여 대소문자 구분 없이 매핑
labelToCodeMap[row.value_label] = row.value_code;
// 소문자 키도 추가 (대소문자 무시 검색용)
labelToCodeMap[row.value_label.toLowerCase()] = row.value_code;
}
if (Object.keys(labelToCodeMap).length > 0) {
result[columnName] = labelToCodeMap;
logger.info(`컬럼 ${columnName}의 라벨→코드 매핑 ${valuesResult.rows.length}개 조회`);
}
}
logger.info(`카테고리 라벨→코드 매핑 조회 완료`, {
tableName,
columnCount: Object.keys(result).length
});
return result;
} catch (error: any) {
logger.error(`카테고리 라벨→코드 매핑 조회 실패: ${error.message}`, { error });
throw error;
}
}
/**
* 데이터의 카테고리 라벨 값을 코드 값으로 변환
*
* 엑셀 업로드 등에서 사용자가 입력한 라벨 값을 DB 저장용 코드 값으로 변환
*
* @param tableName - 테이블명
* @param companyCode - 회사 코드
* @param data - 변환할 데이터 객체
* @returns 라벨이 코드로 변환된 데이터 객체
*/
async convertCategoryLabelsToCodesForData(
tableName: string,
companyCode: string,
data: Record<string, any>
): Promise<{ convertedData: Record<string, any>; conversions: Array<{ column: string; label: string; code: string }> }> {
try {
// 라벨→코드 매핑 조회
const labelToCodeMapping = await this.getCategoryLabelToCodeMapping(tableName, companyCode);
if (Object.keys(labelToCodeMapping).length === 0) {
// 카테고리 컬럼 없음
return { convertedData: data, conversions: [] };
}
const convertedData = { ...data };
const conversions: Array<{ column: string; label: string; code: string }> = [];
for (const [columnName, labelCodeMap] of Object.entries(labelToCodeMapping)) {
const value = data[columnName];
if (value !== undefined && value !== null && value !== "") {
const stringValue = String(value).trim();
// 다중 값 확인 (쉼표로 구분된 경우)
if (stringValue.includes(",")) {
// 다중 카테고리 값 처리
const labels = stringValue.split(",").map(s => s.trim()).filter(s => s !== "");
const convertedCodes: string[] = [];
let allConverted = true;
for (const label of labels) {
// 정확한 라벨 매칭 시도
let matchedCode = labelCodeMap[label];
// 대소문자 무시 매칭
if (!matchedCode) {
matchedCode = labelCodeMap[label.toLowerCase()];
}
if (matchedCode) {
convertedCodes.push(matchedCode);
conversions.push({
column: columnName,
label: label,
code: matchedCode,
});
logger.info(`카테고리 라벨→코드 변환 (다중): ${columnName} "${label}" → "${matchedCode}"`);
} else {
// 이미 코드값인지 확인
const isAlreadyCode = Object.values(labelCodeMap).includes(label);
if (isAlreadyCode) {
// 이미 코드값이면 그대로 사용
convertedCodes.push(label);
} else {
// 라벨도 코드도 아니면 원래 값 유지
convertedCodes.push(label);
allConverted = false;
logger.warn(`카테고리 값 매핑 없음 (다중): ${columnName} = "${label}" (라벨도 코드도 아님)`);
}
}
}
// 변환된 코드들을 쉼표로 합쳐서 저장
convertedData[columnName] = convertedCodes.join(",");
logger.info(`다중 카테고리 변환 완료: ${columnName} "${stringValue}" → "${convertedData[columnName]}"`);
} else {
// 단일 값 처리
// 정확한 라벨 매칭 시도
let matchedCode = labelCodeMap[stringValue];
// 대소문자 무시 매칭
if (!matchedCode) {
matchedCode = labelCodeMap[stringValue.toLowerCase()];
}
if (matchedCode) {
// 라벨 값을 코드 값으로 변환
convertedData[columnName] = matchedCode;
conversions.push({
column: columnName,
label: stringValue,
code: matchedCode,
});
logger.info(`카테고리 라벨→코드 변환: ${columnName} "${stringValue}" → "${matchedCode}"`);
} else {
// 이미 코드값인지 확인 (역방향 확인)
const isAlreadyCode = Object.values(labelCodeMap).includes(stringValue);
if (!isAlreadyCode) {
logger.warn(`카테고리 값 매핑 없음: ${columnName} = "${stringValue}" (라벨도 코드도 아님)`);
}
// 변환 없이 원래 값 유지
}
}
}
}
logger.info(`카테고리 라벨→코드 변환 완료`, {
tableName,
conversionCount: conversions.length,
conversions,
});
return { convertedData, conversions };
} catch (error: any) {
logger.error(`카테고리 라벨→코드 변환 실패: ${error.message}`, { error });
// 실패 시 원본 데이터 반환
return { convertedData: data, conversions: [] };
}
}
}
export default new TableCategoryValueService();