lhj #362
|
|
@ -30,7 +30,6 @@ export class EntityJoinController {
|
|||
autoFilter, // 🔒 멀티테넌시 자동 필터
|
||||
dataFilter, // 🆕 데이터 필터 (JSON 문자열)
|
||||
excludeFilter, // 🆕 제외 필터 (JSON 문자열) - 다른 테이블에 이미 존재하는 데이터 제외
|
||||
deduplication, // 🆕 중복 제거 설정 (JSON 문자열)
|
||||
userLang, // userLang은 별도로 분리하여 search에 포함되지 않도록 함
|
||||
...otherParams
|
||||
} = req.query;
|
||||
|
|
@ -50,9 +49,6 @@ export class EntityJoinController {
|
|||
// search가 문자열인 경우 JSON 파싱
|
||||
searchConditions =
|
||||
typeof search === "string" ? JSON.parse(search) : search;
|
||||
|
||||
// 🔍 디버그: 파싱된 검색 조건 로깅
|
||||
logger.info(`🔍 파싱된 검색 조건:`, JSON.stringify(searchConditions, null, 2));
|
||||
} catch (error) {
|
||||
logger.warn("검색 조건 파싱 오류:", error);
|
||||
searchConditions = {};
|
||||
|
|
@ -155,24 +151,6 @@ export class EntityJoinController {
|
|||
}
|
||||
}
|
||||
|
||||
// 🆕 중복 제거 설정 처리
|
||||
let parsedDeduplication: {
|
||||
enabled: boolean;
|
||||
groupByColumn: string;
|
||||
keepStrategy: "latest" | "earliest" | "base_price" | "current_date";
|
||||
sortColumn?: string;
|
||||
} | undefined = undefined;
|
||||
if (deduplication) {
|
||||
try {
|
||||
parsedDeduplication =
|
||||
typeof deduplication === "string" ? JSON.parse(deduplication) : deduplication;
|
||||
logger.info("중복 제거 설정 파싱 완료:", parsedDeduplication);
|
||||
} catch (error) {
|
||||
logger.warn("중복 제거 설정 파싱 오류:", error);
|
||||
parsedDeduplication = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
const result = await tableManagementService.getTableDataWithEntityJoins(
|
||||
tableName,
|
||||
{
|
||||
|
|
@ -190,26 +168,13 @@ export class EntityJoinController {
|
|||
screenEntityConfigs: parsedScreenEntityConfigs,
|
||||
dataFilter: parsedDataFilter, // 🆕 데이터 필터 전달
|
||||
excludeFilter: parsedExcludeFilter, // 🆕 제외 필터 전달
|
||||
deduplication: parsedDeduplication, // 🆕 중복 제거 설정 전달
|
||||
}
|
||||
);
|
||||
|
||||
// 🆕 중복 제거 처리 (결과 데이터에 적용)
|
||||
let finalData = result;
|
||||
if (parsedDeduplication?.enabled && parsedDeduplication.groupByColumn && Array.isArray(result.data)) {
|
||||
logger.info(`🔄 중복 제거 시작: 기준 컬럼 = ${parsedDeduplication.groupByColumn}, 전략 = ${parsedDeduplication.keepStrategy}`);
|
||||
const originalCount = result.data.length;
|
||||
finalData = {
|
||||
...result,
|
||||
data: this.deduplicateData(result.data, parsedDeduplication),
|
||||
};
|
||||
logger.info(`✅ 중복 제거 완료: ${originalCount}개 → ${finalData.data.length}개`);
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
message: "Entity 조인 데이터 조회 성공",
|
||||
data: finalData,
|
||||
data: result,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error("Entity 조인 데이터 조회 실패", error);
|
||||
|
|
@ -584,98 +549,6 @@ export class EntityJoinController {
|
|||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 중복 데이터 제거 (메모리 내 처리)
|
||||
*/
|
||||
private deduplicateData(
|
||||
data: any[],
|
||||
config: {
|
||||
groupByColumn: string;
|
||||
keepStrategy: "latest" | "earliest" | "base_price" | "current_date";
|
||||
sortColumn?: string;
|
||||
}
|
||||
): any[] {
|
||||
if (!data || data.length === 0) return data;
|
||||
|
||||
// 그룹별로 데이터 분류
|
||||
const groups: Record<string, any[]> = {};
|
||||
|
||||
for (const row of data) {
|
||||
const groupKey = row[config.groupByColumn];
|
||||
if (groupKey === undefined || groupKey === null) continue;
|
||||
|
||||
if (!groups[groupKey]) {
|
||||
groups[groupKey] = [];
|
||||
}
|
||||
groups[groupKey].push(row);
|
||||
}
|
||||
|
||||
// 각 그룹에서 하나의 행만 선택
|
||||
const result: any[] = [];
|
||||
|
||||
for (const [groupKey, rows] of Object.entries(groups)) {
|
||||
if (rows.length === 0) continue;
|
||||
|
||||
let selectedRow: any;
|
||||
|
||||
switch (config.keepStrategy) {
|
||||
case "latest":
|
||||
// 정렬 컬럼 기준 최신 (가장 큰 값)
|
||||
if (config.sortColumn) {
|
||||
rows.sort((a, b) => {
|
||||
const aVal = a[config.sortColumn!];
|
||||
const bVal = b[config.sortColumn!];
|
||||
if (aVal === bVal) return 0;
|
||||
if (aVal > bVal) return -1;
|
||||
return 1;
|
||||
});
|
||||
}
|
||||
selectedRow = rows[0];
|
||||
break;
|
||||
|
||||
case "earliest":
|
||||
// 정렬 컬럼 기준 최초 (가장 작은 값)
|
||||
if (config.sortColumn) {
|
||||
rows.sort((a, b) => {
|
||||
const aVal = a[config.sortColumn!];
|
||||
const bVal = b[config.sortColumn!];
|
||||
if (aVal === bVal) return 0;
|
||||
if (aVal < bVal) return -1;
|
||||
return 1;
|
||||
});
|
||||
}
|
||||
selectedRow = rows[0];
|
||||
break;
|
||||
|
||||
case "base_price":
|
||||
// base_price가 true인 행 선택
|
||||
selectedRow = rows.find((r) => r.base_price === true || r.base_price === "true") || rows[0];
|
||||
break;
|
||||
|
||||
case "current_date":
|
||||
// 오늘 날짜 기준 유효 기간 내 행 선택
|
||||
const today = new Date().toISOString().split("T")[0];
|
||||
selectedRow = rows.find((r) => {
|
||||
const startDate = r.start_date;
|
||||
const endDate = r.end_date;
|
||||
if (!startDate) return true;
|
||||
if (startDate <= today && (!endDate || endDate >= today)) return true;
|
||||
return false;
|
||||
}) || rows[0];
|
||||
break;
|
||||
|
||||
default:
|
||||
selectedRow = rows[0];
|
||||
}
|
||||
|
||||
if (selectedRow) {
|
||||
result.push(selectedRow);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
export const entityJoinController = new EntityJoinController();
|
||||
|
|
|
|||
|
|
@ -1,23 +1,18 @@
|
|||
import { Request, Response } from "express";
|
||||
import { getPool } from "../database/db";
|
||||
import { logger } from "../utils/logger";
|
||||
import { MultiLangService } from "../services/multilangService";
|
||||
import { AuthenticatedRequest } from "../types/auth";
|
||||
|
||||
// pool 인스턴스 가져오기
|
||||
const pool = getPool();
|
||||
|
||||
// 다국어 서비스 인스턴스
|
||||
const multiLangService = new MultiLangService();
|
||||
|
||||
// ============================================================
|
||||
// 화면 그룹 (screen_groups) CRUD
|
||||
// ============================================================
|
||||
|
||||
// 화면 그룹 목록 조회
|
||||
export const getScreenGroups = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const getScreenGroups = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
const { page = 1, size = 20, searchTerm } = req.query;
|
||||
const offset = (parseInt(page as string) - 1) * parseInt(size as string);
|
||||
|
||||
|
|
@ -89,10 +84,10 @@ export const getScreenGroups = async (req: AuthenticatedRequest, res: Response)
|
|||
};
|
||||
|
||||
// 화면 그룹 상세 조회
|
||||
export const getScreenGroup = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const getScreenGroup = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
|
||||
let query = `
|
||||
SELECT sg.*,
|
||||
|
|
@ -135,10 +130,10 @@ export const getScreenGroup = async (req: AuthenticatedRequest, res: Response) =
|
|||
};
|
||||
|
||||
// 화면 그룹 생성
|
||||
export const createScreenGroup = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const createScreenGroup = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const userCompanyCode = req.user!.companyCode;
|
||||
const userId = req.user!.userId;
|
||||
const userCompanyCode = (req.user as any).companyCode;
|
||||
const userId = (req.user as any).userId;
|
||||
const { group_name, group_code, main_table_name, description, icon, display_order, is_active, parent_group_id, target_company_code } = req.body;
|
||||
|
||||
if (!group_name || !group_code) {
|
||||
|
|
@ -196,47 +191,6 @@ export const createScreenGroup = async (req: AuthenticatedRequest, res: Response
|
|||
// 업데이트된 데이터 반환
|
||||
const updatedResult = await pool.query(`SELECT * FROM screen_groups WHERE id = $1`, [newGroupId]);
|
||||
|
||||
// 다국어 카테고리 자동 생성 (그룹 경로 기반)
|
||||
try {
|
||||
// 그룹 경로 조회 (상위 그룹 → 현재 그룹)
|
||||
const groupPathResult = await pool.query(
|
||||
`WITH RECURSIVE group_path AS (
|
||||
SELECT id, parent_group_id, group_name, group_level, 1 as depth
|
||||
FROM screen_groups
|
||||
WHERE id = $1
|
||||
UNION ALL
|
||||
SELECT g.id, g.parent_group_id, g.group_name, g.group_level, gp.depth + 1
|
||||
FROM screen_groups g
|
||||
INNER JOIN group_path gp ON g.id = gp.parent_group_id
|
||||
WHERE g.parent_group_id IS NOT NULL
|
||||
)
|
||||
SELECT group_name FROM group_path
|
||||
ORDER BY depth DESC`,
|
||||
[newGroupId]
|
||||
);
|
||||
|
||||
const groupPath = groupPathResult.rows.map((r: any) => r.group_name);
|
||||
|
||||
// 회사 이름 조회
|
||||
let companyName = "공통";
|
||||
if (finalCompanyCode !== "*") {
|
||||
const companyResult = await pool.query(
|
||||
`SELECT company_name FROM company_mng WHERE company_code = $1`,
|
||||
[finalCompanyCode]
|
||||
);
|
||||
if (companyResult.rows.length > 0) {
|
||||
companyName = companyResult.rows[0].company_name;
|
||||
}
|
||||
}
|
||||
|
||||
// 다국어 카테고리 생성
|
||||
await multiLangService.ensureScreenGroupCategory(finalCompanyCode, companyName, groupPath);
|
||||
logger.info("화면 그룹 다국어 카테고리 자동 생성 완료", { groupPath, companyCode: finalCompanyCode });
|
||||
} catch (multilangError: any) {
|
||||
// 다국어 카테고리 생성 실패해도 그룹 생성은 성공으로 처리
|
||||
logger.warn("화면 그룹 다국어 카테고리 생성 실패 (무시하고 계속):", multilangError.message);
|
||||
}
|
||||
|
||||
logger.info("화면 그룹 생성", { userCompanyCode, finalCompanyCode, groupId: newGroupId, groupName: group_name, parentGroupId: parent_group_id });
|
||||
|
||||
res.json({ success: true, data: updatedResult.rows[0], message: "화면 그룹이 생성되었습니다." });
|
||||
|
|
@ -250,10 +204,10 @@ export const createScreenGroup = async (req: AuthenticatedRequest, res: Response
|
|||
};
|
||||
|
||||
// 화면 그룹 수정
|
||||
export const updateScreenGroup = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const updateScreenGroup = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const userCompanyCode = req.user!.companyCode;
|
||||
const userCompanyCode = (req.user as any).companyCode;
|
||||
const { group_name, group_code, main_table_name, description, icon, display_order, is_active, parent_group_id, target_company_code } = req.body;
|
||||
|
||||
// 회사 코드 결정: 최고 관리자가 특정 회사를 선택한 경우 해당 회사로, 아니면 현재 그룹의 회사 유지
|
||||
|
|
@ -339,10 +293,10 @@ export const updateScreenGroup = async (req: AuthenticatedRequest, res: Response
|
|||
};
|
||||
|
||||
// 화면 그룹 삭제
|
||||
export const deleteScreenGroup = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const deleteScreenGroup = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
|
||||
let query = `DELETE FROM screen_groups WHERE id = $1`;
|
||||
const params: any[] = [id];
|
||||
|
|
@ -375,10 +329,10 @@ export const deleteScreenGroup = async (req: AuthenticatedRequest, res: Response
|
|||
// ============================================================
|
||||
|
||||
// 그룹에 화면 추가
|
||||
export const addScreenToGroup = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const addScreenToGroup = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const companyCode = req.user!.companyCode;
|
||||
const userId = req.user!.userId;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
const userId = (req.user as any).userId;
|
||||
const { group_id, screen_id, screen_role, display_order, is_default } = req.body;
|
||||
|
||||
if (!group_id || !screen_id) {
|
||||
|
|
@ -415,10 +369,10 @@ export const addScreenToGroup = async (req: AuthenticatedRequest, res: Response)
|
|||
};
|
||||
|
||||
// 그룹에서 화면 제거
|
||||
export const removeScreenFromGroup = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const removeScreenFromGroup = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
|
||||
let query = `DELETE FROM screen_group_screens WHERE id = $1`;
|
||||
const params: any[] = [id];
|
||||
|
|
@ -446,10 +400,10 @@ export const removeScreenFromGroup = async (req: AuthenticatedRequest, res: Resp
|
|||
};
|
||||
|
||||
// 그룹 내 화면 순서/역할 수정
|
||||
export const updateScreenInGroup = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const updateScreenInGroup = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
const { screen_role, display_order, is_default } = req.body;
|
||||
|
||||
let query = `
|
||||
|
|
@ -485,9 +439,9 @@ export const updateScreenInGroup = async (req: AuthenticatedRequest, res: Respon
|
|||
// ============================================================
|
||||
|
||||
// 화면 필드 조인 목록 조회
|
||||
export const getFieldJoins = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const getFieldJoins = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
const { screen_id } = req.query;
|
||||
|
||||
let query = `
|
||||
|
|
@ -526,10 +480,10 @@ export const getFieldJoins = async (req: AuthenticatedRequest, res: Response) =>
|
|||
};
|
||||
|
||||
// 화면 필드 조인 생성
|
||||
export const createFieldJoin = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const createFieldJoin = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const companyCode = req.user!.companyCode;
|
||||
const userId = req.user!.userId;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
const userId = (req.user as any).userId;
|
||||
const {
|
||||
screen_id, layout_id, component_id, field_name,
|
||||
save_table, save_column, join_table, join_column, display_column,
|
||||
|
|
@ -567,10 +521,10 @@ export const createFieldJoin = async (req: AuthenticatedRequest, res: Response)
|
|||
};
|
||||
|
||||
// 화면 필드 조인 수정
|
||||
export const updateFieldJoin = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const updateFieldJoin = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
const {
|
||||
layout_id, component_id, field_name,
|
||||
save_table, save_column, join_table, join_column, display_column,
|
||||
|
|
@ -612,10 +566,10 @@ export const updateFieldJoin = async (req: AuthenticatedRequest, res: Response)
|
|||
};
|
||||
|
||||
// 화면 필드 조인 삭제
|
||||
export const deleteFieldJoin = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const deleteFieldJoin = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
|
||||
let query = `DELETE FROM screen_field_joins WHERE id = $1`;
|
||||
const params: any[] = [id];
|
||||
|
|
@ -646,9 +600,9 @@ export const deleteFieldJoin = async (req: AuthenticatedRequest, res: Response)
|
|||
// ============================================================
|
||||
|
||||
// 데이터 흐름 목록 조회
|
||||
export const getDataFlows = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const getDataFlows = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
const { group_id, source_screen_id } = req.query;
|
||||
|
||||
let query = `
|
||||
|
|
@ -696,10 +650,10 @@ export const getDataFlows = async (req: AuthenticatedRequest, res: Response) =>
|
|||
};
|
||||
|
||||
// 데이터 흐름 생성
|
||||
export const createDataFlow = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const createDataFlow = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const companyCode = req.user!.companyCode;
|
||||
const userId = req.user!.userId;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
const userId = (req.user as any).userId;
|
||||
const {
|
||||
group_id, source_screen_id, source_action, target_screen_id, target_action,
|
||||
data_mapping, flow_type, flow_label, condition_expression, is_active
|
||||
|
|
@ -735,10 +689,10 @@ export const createDataFlow = async (req: AuthenticatedRequest, res: Response) =
|
|||
};
|
||||
|
||||
// 데이터 흐름 수정
|
||||
export const updateDataFlow = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const updateDataFlow = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
const {
|
||||
group_id, source_screen_id, source_action, target_screen_id, target_action,
|
||||
data_mapping, flow_type, flow_label, condition_expression, is_active
|
||||
|
|
@ -778,10 +732,10 @@ export const updateDataFlow = async (req: AuthenticatedRequest, res: Response) =
|
|||
};
|
||||
|
||||
// 데이터 흐름 삭제
|
||||
export const deleteDataFlow = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const deleteDataFlow = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
|
||||
let query = `DELETE FROM screen_data_flows WHERE id = $1`;
|
||||
const params: any[] = [id];
|
||||
|
|
@ -812,9 +766,9 @@ export const deleteDataFlow = async (req: AuthenticatedRequest, res: Response) =
|
|||
// ============================================================
|
||||
|
||||
// 화면-테이블 관계 목록 조회
|
||||
export const getTableRelations = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const getTableRelations = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
const { screen_id, group_id } = req.query;
|
||||
|
||||
let query = `
|
||||
|
|
@ -861,10 +815,10 @@ export const getTableRelations = async (req: AuthenticatedRequest, res: Response
|
|||
};
|
||||
|
||||
// 화면-테이블 관계 생성
|
||||
export const createTableRelation = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const createTableRelation = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const companyCode = req.user!.companyCode;
|
||||
const userId = req.user!.userId;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
const userId = (req.user as any).userId;
|
||||
const { group_id, screen_id, table_name, relation_type, crud_operations, description, is_active } = req.body;
|
||||
|
||||
if (!screen_id || !table_name) {
|
||||
|
|
@ -894,10 +848,10 @@ export const createTableRelation = async (req: AuthenticatedRequest, res: Respon
|
|||
};
|
||||
|
||||
// 화면-테이블 관계 수정
|
||||
export const updateTableRelation = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const updateTableRelation = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
const { group_id, table_name, relation_type, crud_operations, description, is_active } = req.body;
|
||||
|
||||
let query = `
|
||||
|
|
@ -929,10 +883,10 @@ export const updateTableRelation = async (req: AuthenticatedRequest, res: Respon
|
|||
};
|
||||
|
||||
// 화면-테이블 관계 삭제
|
||||
export const deleteTableRelation = async (req: AuthenticatedRequest, res: Response) => {
|
||||
export const deleteTableRelation = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const companyCode = req.user!.companyCode;
|
||||
const companyCode = (req.user as any).companyCode;
|
||||
|
||||
let query = `DELETE FROM screen_table_relations WHERE id = $1`;
|
||||
const params: any[] = [id];
|
||||
|
|
|
|||
|
|
@ -804,12 +804,6 @@ export async function getTableData(
|
|||
}
|
||||
}
|
||||
|
||||
// 🆕 최종 검색 조건 로그
|
||||
logger.info(
|
||||
`🔍 최종 검색 조건 (enhancedSearch):`,
|
||||
JSON.stringify(enhancedSearch)
|
||||
);
|
||||
|
||||
// 데이터 조회
|
||||
const result = await tableManagementService.getTableData(tableName, {
|
||||
page: parseInt(page),
|
||||
|
|
@ -893,10 +887,7 @@ export async function addTableData(
|
|||
const companyCode = req.user?.companyCode;
|
||||
if (companyCode && !data.company_code) {
|
||||
// 테이블에 company_code 컬럼이 있는지 확인
|
||||
const hasCompanyCodeColumn = await tableManagementService.hasColumn(
|
||||
tableName,
|
||||
"company_code"
|
||||
);
|
||||
const hasCompanyCodeColumn = await tableManagementService.hasColumn(tableName, "company_code");
|
||||
if (hasCompanyCodeColumn) {
|
||||
data.company_code = companyCode;
|
||||
logger.info(`멀티테넌시: company_code 자동 추가 - ${companyCode}`);
|
||||
|
|
@ -906,10 +897,7 @@ export async function addTableData(
|
|||
// 🆕 writer 컬럼 자동 추가 (테이블에 writer 컬럼이 있고 값이 없는 경우)
|
||||
const userId = req.user?.userId;
|
||||
if (userId && !data.writer) {
|
||||
const hasWriterColumn = await tableManagementService.hasColumn(
|
||||
tableName,
|
||||
"writer"
|
||||
);
|
||||
const hasWriterColumn = await tableManagementService.hasColumn(tableName, "writer");
|
||||
if (hasWriterColumn) {
|
||||
data.writer = userId;
|
||||
logger.info(`writer 자동 추가 - ${userId}`);
|
||||
|
|
@ -917,25 +905,13 @@ export async function addTableData(
|
|||
}
|
||||
|
||||
// 데이터 추가
|
||||
const result = await tableManagementService.addTableData(tableName, data);
|
||||
await tableManagementService.addTableData(tableName, data);
|
||||
|
||||
logger.info(`테이블 데이터 추가 완료: ${tableName}`);
|
||||
|
||||
// 무시된 컬럼이 있으면 경고 정보 포함
|
||||
const response: ApiResponse<{
|
||||
skippedColumns?: string[];
|
||||
savedColumns?: string[];
|
||||
}> = {
|
||||
const response: ApiResponse<null> = {
|
||||
success: true,
|
||||
message:
|
||||
result.skippedColumns.length > 0
|
||||
? `테이블 데이터를 추가했습니다. (무시된 컬럼 ${result.skippedColumns.length}개: ${result.skippedColumns.join(", ")})`
|
||||
: "테이블 데이터를 성공적으로 추가했습니다.",
|
||||
data: {
|
||||
skippedColumns:
|
||||
result.skippedColumns.length > 0 ? result.skippedColumns : undefined,
|
||||
savedColumns: result.savedColumns,
|
||||
},
|
||||
message: "테이블 데이터를 성공적으로 추가했습니다.",
|
||||
};
|
||||
|
||||
res.status(201).json(response);
|
||||
|
|
@ -1663,10 +1639,10 @@ export async function toggleLogTable(
|
|||
|
||||
/**
|
||||
* 메뉴의 상위 메뉴들이 설정한 모든 카테고리 타입 컬럼 조회 (계층 구조 상속)
|
||||
*
|
||||
*
|
||||
* @route GET /api/table-management/menu/:menuObjid/category-columns
|
||||
* @description 현재 메뉴와 상위 메뉴들에서 설정한 category_column_mapping의 모든 카테고리 컬럼 조회
|
||||
*
|
||||
*
|
||||
* 예시:
|
||||
* - 2레벨 메뉴 "고객사관리"에서 discount_type, rounding_type 설정
|
||||
* - 3레벨 메뉴 "고객등록", "고객조회" 등에서도 동일하게 보임 (상속)
|
||||
|
|
@ -1679,10 +1655,7 @@ export async function getCategoryColumnsByMenu(
|
|||
const { menuObjid } = req.params;
|
||||
const companyCode = req.user?.companyCode;
|
||||
|
||||
logger.info("📥 메뉴별 카테고리 컬럼 조회 요청", {
|
||||
menuObjid,
|
||||
companyCode,
|
||||
});
|
||||
logger.info("📥 메뉴별 카테고리 컬럼 조회 요청", { menuObjid, companyCode });
|
||||
|
||||
if (!menuObjid) {
|
||||
res.status(400).json({
|
||||
|
|
@ -1708,11 +1681,8 @@ export async function getCategoryColumnsByMenu(
|
|||
|
||||
if (mappingTableExists) {
|
||||
// 🆕 category_column_mapping을 사용한 계층 구조 기반 조회
|
||||
logger.info(
|
||||
"🔍 category_column_mapping 기반 카테고리 컬럼 조회 (계층 구조 상속)",
|
||||
{ menuObjid, companyCode }
|
||||
);
|
||||
|
||||
logger.info("🔍 category_column_mapping 기반 카테고리 컬럼 조회 (계층 구조 상속)", { menuObjid, companyCode });
|
||||
|
||||
// 현재 메뉴와 모든 상위 메뉴의 objid 조회 (재귀)
|
||||
const ancestorMenuQuery = `
|
||||
WITH RECURSIVE menu_hierarchy AS (
|
||||
|
|
@ -1734,21 +1704,17 @@ export async function getCategoryColumnsByMenu(
|
|||
ARRAY_AGG(menu_name_kor) as menu_names
|
||||
FROM menu_hierarchy
|
||||
`;
|
||||
|
||||
const ancestorMenuResult = await pool.query(ancestorMenuQuery, [
|
||||
parseInt(menuObjid),
|
||||
]);
|
||||
const ancestorMenuObjids = ancestorMenuResult.rows[0]?.menu_objids || [
|
||||
parseInt(menuObjid),
|
||||
];
|
||||
|
||||
const ancestorMenuResult = await pool.query(ancestorMenuQuery, [parseInt(menuObjid)]);
|
||||
const ancestorMenuObjids = ancestorMenuResult.rows[0]?.menu_objids || [parseInt(menuObjid)];
|
||||
const ancestorMenuNames = ancestorMenuResult.rows[0]?.menu_names || [];
|
||||
|
||||
logger.info("✅ 상위 메뉴 계층 조회 완료", {
|
||||
ancestorMenuObjids,
|
||||
|
||||
logger.info("✅ 상위 메뉴 계층 조회 완료", {
|
||||
ancestorMenuObjids,
|
||||
ancestorMenuNames,
|
||||
hierarchyDepth: ancestorMenuObjids.length,
|
||||
hierarchyDepth: ancestorMenuObjids.length
|
||||
});
|
||||
|
||||
|
||||
// 상위 메뉴들에 설정된 모든 카테고리 컬럼 조회 (테이블 필터링 제거)
|
||||
const columnsQuery = `
|
||||
SELECT DISTINCT
|
||||
|
|
@ -1778,31 +1744,20 @@ export async function getCategoryColumnsByMenu(
|
|||
AND ttc.input_type = 'category'
|
||||
ORDER BY ttc.table_name, ccm.logical_column_name
|
||||
`;
|
||||
|
||||
columnsResult = await pool.query(columnsQuery, [
|
||||
companyCode,
|
||||
ancestorMenuObjids,
|
||||
]);
|
||||
logger.info(
|
||||
"✅ category_column_mapping 기반 조회 완료 (계층 구조 상속)",
|
||||
{
|
||||
rowCount: columnsResult.rows.length,
|
||||
columns: columnsResult.rows.map(
|
||||
(r: any) => `${r.tableName}.${r.columnName}`
|
||||
),
|
||||
}
|
||||
);
|
||||
|
||||
columnsResult = await pool.query(columnsQuery, [companyCode, ancestorMenuObjids]);
|
||||
logger.info("✅ category_column_mapping 기반 조회 완료 (계층 구조 상속)", {
|
||||
rowCount: columnsResult.rows.length,
|
||||
columns: columnsResult.rows.map((r: any) => `${r.tableName}.${r.columnName}`)
|
||||
});
|
||||
} else {
|
||||
// 🔄 레거시 방식: 형제 메뉴들의 테이블에서 모든 카테고리 컬럼 조회
|
||||
logger.info("🔍 레거시 방식: 형제 메뉴 테이블 기반 카테고리 컬럼 조회", {
|
||||
menuObjid,
|
||||
companyCode,
|
||||
});
|
||||
|
||||
logger.info("🔍 레거시 방식: 형제 메뉴 테이블 기반 카테고리 컬럼 조회", { menuObjid, companyCode });
|
||||
|
||||
// 형제 메뉴 조회
|
||||
const { getSiblingMenuObjids } = await import("../services/menuService");
|
||||
const siblingObjids = await getSiblingMenuObjids(parseInt(menuObjid));
|
||||
|
||||
|
||||
// 형제 메뉴들이 사용하는 테이블 조회
|
||||
const tablesQuery = `
|
||||
SELECT DISTINCT sd.table_name
|
||||
|
|
@ -1812,17 +1767,11 @@ export async function getCategoryColumnsByMenu(
|
|||
AND sma.company_code = $2
|
||||
AND sd.table_name IS NOT NULL
|
||||
`;
|
||||
|
||||
const tablesResult = await pool.query(tablesQuery, [
|
||||
siblingObjids,
|
||||
companyCode,
|
||||
]);
|
||||
|
||||
const tablesResult = await pool.query(tablesQuery, [siblingObjids, companyCode]);
|
||||
const tableNames = tablesResult.rows.map((row: any) => row.table_name);
|
||||
|
||||
logger.info("✅ 형제 메뉴 테이블 조회 완료", {
|
||||
tableNames,
|
||||
count: tableNames.length,
|
||||
});
|
||||
|
||||
logger.info("✅ 형제 메뉴 테이블 조회 완료", { tableNames, count: tableNames.length });
|
||||
|
||||
if (tableNames.length === 0) {
|
||||
res.json({
|
||||
|
|
@ -1832,7 +1781,7 @@ export async function getCategoryColumnsByMenu(
|
|||
});
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
const columnsQuery = `
|
||||
SELECT
|
||||
ttc.table_name AS "tableName",
|
||||
|
|
@ -1857,15 +1806,13 @@ export async function getCategoryColumnsByMenu(
|
|||
AND ttc.input_type = 'category'
|
||||
ORDER BY ttc.table_name, ttc.column_name
|
||||
`;
|
||||
|
||||
|
||||
columnsResult = await pool.query(columnsQuery, [tableNames, companyCode]);
|
||||
logger.info("✅ 레거시 방식 조회 완료", {
|
||||
rowCount: columnsResult.rows.length,
|
||||
});
|
||||
logger.info("✅ 레거시 방식 조회 완료", { rowCount: columnsResult.rows.length });
|
||||
}
|
||||
|
||||
logger.info("✅ 카테고리 컬럼 조회 완료", {
|
||||
columnCount: columnsResult.rows.length,
|
||||
|
||||
logger.info("✅ 카테고리 컬럼 조회 완료", {
|
||||
columnCount: columnsResult.rows.length
|
||||
});
|
||||
|
||||
res.json({
|
||||
|
|
@ -1890,9 +1837,9 @@ export async function getCategoryColumnsByMenu(
|
|||
|
||||
/**
|
||||
* 범용 다중 테이블 저장 API
|
||||
*
|
||||
*
|
||||
* 메인 테이블과 서브 테이블(들)에 트랜잭션으로 데이터를 저장합니다.
|
||||
*
|
||||
*
|
||||
* 요청 본문:
|
||||
* {
|
||||
* mainTable: { tableName: string, primaryKeyColumn: string },
|
||||
|
|
@ -1962,29 +1909,23 @@ export async function multiTableSave(
|
|||
}
|
||||
|
||||
let mainResult: any;
|
||||
|
||||
|
||||
if (isUpdate && pkValue) {
|
||||
// UPDATE
|
||||
const updateColumns = Object.keys(mainData)
|
||||
.filter((col) => col !== pkColumn)
|
||||
.filter(col => col !== pkColumn)
|
||||
.map((col, idx) => `"${col}" = $${idx + 1}`)
|
||||
.join(", ");
|
||||
const updateValues = Object.keys(mainData)
|
||||
.filter((col) => col !== pkColumn)
|
||||
.map((col) => mainData[col]);
|
||||
|
||||
.filter(col => col !== pkColumn)
|
||||
.map(col => mainData[col]);
|
||||
|
||||
// updated_at 컬럼 존재 여부 확인
|
||||
const hasUpdatedAt = await client.query(
|
||||
`
|
||||
const hasUpdatedAt = await client.query(`
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = $1 AND column_name = 'updated_at'
|
||||
`,
|
||||
[mainTableName]
|
||||
);
|
||||
const updatedAtClause =
|
||||
hasUpdatedAt.rowCount && hasUpdatedAt.rowCount > 0
|
||||
? ", updated_at = NOW()"
|
||||
: "";
|
||||
`, [mainTableName]);
|
||||
const updatedAtClause = hasUpdatedAt.rowCount && hasUpdatedAt.rowCount > 0 ? ", updated_at = NOW()" : "";
|
||||
|
||||
const updateQuery = `
|
||||
UPDATE "${mainTableName}"
|
||||
|
|
@ -1993,43 +1934,29 @@ export async function multiTableSave(
|
|||
${companyCode !== "*" ? `AND company_code = $${updateValues.length + 2}` : ""}
|
||||
RETURNING *
|
||||
`;
|
||||
|
||||
const updateParams =
|
||||
companyCode !== "*"
|
||||
? [...updateValues, pkValue, companyCode]
|
||||
: [...updateValues, pkValue];
|
||||
|
||||
logger.info("메인 테이블 UPDATE:", {
|
||||
query: updateQuery,
|
||||
paramsCount: updateParams.length,
|
||||
});
|
||||
|
||||
const updateParams = companyCode !== "*"
|
||||
? [...updateValues, pkValue, companyCode]
|
||||
: [...updateValues, pkValue];
|
||||
|
||||
logger.info("메인 테이블 UPDATE:", { query: updateQuery, paramsCount: updateParams.length });
|
||||
mainResult = await client.query(updateQuery, updateParams);
|
||||
} else {
|
||||
// INSERT
|
||||
const columns = Object.keys(mainData)
|
||||
.map((col) => `"${col}"`)
|
||||
.join(", ");
|
||||
const placeholders = Object.keys(mainData)
|
||||
.map((_, idx) => `$${idx + 1}`)
|
||||
.join(", ");
|
||||
const columns = Object.keys(mainData).map(col => `"${col}"`).join(", ");
|
||||
const placeholders = Object.keys(mainData).map((_, idx) => `$${idx + 1}`).join(", ");
|
||||
const values = Object.values(mainData);
|
||||
|
||||
// updated_at 컬럼 존재 여부 확인
|
||||
const hasUpdatedAt = await client.query(
|
||||
`
|
||||
const hasUpdatedAt = await client.query(`
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = $1 AND column_name = 'updated_at'
|
||||
`,
|
||||
[mainTableName]
|
||||
);
|
||||
const updatedAtClause =
|
||||
hasUpdatedAt.rowCount && hasUpdatedAt.rowCount > 0
|
||||
? ", updated_at = NOW()"
|
||||
: "";
|
||||
`, [mainTableName]);
|
||||
const updatedAtClause = hasUpdatedAt.rowCount && hasUpdatedAt.rowCount > 0 ? ", updated_at = NOW()" : "";
|
||||
|
||||
const updateSetClause = Object.keys(mainData)
|
||||
.filter((col) => col !== pkColumn)
|
||||
.map((col) => `"${col}" = EXCLUDED."${col}"`)
|
||||
.filter(col => col !== pkColumn)
|
||||
.map(col => `"${col}" = EXCLUDED."${col}"`)
|
||||
.join(", ");
|
||||
|
||||
const insertQuery = `
|
||||
|
|
@ -2040,10 +1967,7 @@ export async function multiTableSave(
|
|||
RETURNING *
|
||||
`;
|
||||
|
||||
logger.info("메인 테이블 INSERT/UPSERT:", {
|
||||
query: insertQuery,
|
||||
paramsCount: values.length,
|
||||
});
|
||||
logger.info("메인 테이블 INSERT/UPSERT:", { query: insertQuery, paramsCount: values.length });
|
||||
mainResult = await client.query(insertQuery, values);
|
||||
}
|
||||
|
||||
|
|
@ -2062,15 +1986,12 @@ export async function multiTableSave(
|
|||
const { tableName, linkColumn, items, options } = subTableConfig;
|
||||
|
||||
// saveMainAsFirst가 활성화된 경우, items가 비어있어도 메인 데이터를 서브 테이블에 저장해야 함
|
||||
const hasSaveMainAsFirst =
|
||||
options?.saveMainAsFirst &&
|
||||
options?.mainFieldMappings &&
|
||||
options.mainFieldMappings.length > 0;
|
||||
|
||||
const hasSaveMainAsFirst = options?.saveMainAsFirst &&
|
||||
options?.mainFieldMappings &&
|
||||
options.mainFieldMappings.length > 0;
|
||||
|
||||
if (!tableName || (!items?.length && !hasSaveMainAsFirst)) {
|
||||
logger.info(
|
||||
`서브 테이블 ${tableName} 스킵: 데이터 없음 (saveMainAsFirst: ${hasSaveMainAsFirst})`
|
||||
);
|
||||
logger.info(`서브 테이블 ${tableName} 스킵: 데이터 없음 (saveMainAsFirst: ${hasSaveMainAsFirst})`);
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
@ -2083,20 +2004,15 @@ export async function multiTableSave(
|
|||
|
||||
// 기존 데이터 삭제 옵션
|
||||
if (options?.deleteExistingBefore && linkColumn?.subColumn) {
|
||||
const deleteQuery =
|
||||
options?.deleteOnlySubItems && options?.mainMarkerColumn
|
||||
? `DELETE FROM "${tableName}" WHERE "${linkColumn.subColumn}" = $1 AND "${options.mainMarkerColumn}" = $2`
|
||||
: `DELETE FROM "${tableName}" WHERE "${linkColumn.subColumn}" = $1`;
|
||||
const deleteQuery = options?.deleteOnlySubItems && options?.mainMarkerColumn
|
||||
? `DELETE FROM "${tableName}" WHERE "${linkColumn.subColumn}" = $1 AND "${options.mainMarkerColumn}" = $2`
|
||||
: `DELETE FROM "${tableName}" WHERE "${linkColumn.subColumn}" = $1`;
|
||||
|
||||
const deleteParams = options?.deleteOnlySubItems && options?.mainMarkerColumn
|
||||
? [savedPkValue, options.subMarkerValue ?? false]
|
||||
: [savedPkValue];
|
||||
|
||||
const deleteParams =
|
||||
options?.deleteOnlySubItems && options?.mainMarkerColumn
|
||||
? [savedPkValue, options.subMarkerValue ?? false]
|
||||
: [savedPkValue];
|
||||
|
||||
logger.info(`서브 테이블 ${tableName} 기존 데이터 삭제:`, {
|
||||
deleteQuery,
|
||||
deleteParams,
|
||||
});
|
||||
logger.info(`서브 테이블 ${tableName} 기존 데이터 삭제:`, { deleteQuery, deleteParams });
|
||||
await client.query(deleteQuery, deleteParams);
|
||||
}
|
||||
|
||||
|
|
@ -2109,12 +2025,7 @@ export async function multiTableSave(
|
|||
linkColumn,
|
||||
mainDataKeys: Object.keys(mainData),
|
||||
});
|
||||
if (
|
||||
options?.saveMainAsFirst &&
|
||||
options?.mainFieldMappings &&
|
||||
options.mainFieldMappings.length > 0 &&
|
||||
linkColumn?.subColumn
|
||||
) {
|
||||
if (options?.saveMainAsFirst && options?.mainFieldMappings && options.mainFieldMappings.length > 0 && linkColumn?.subColumn) {
|
||||
const mainSubItem: Record<string, any> = {
|
||||
[linkColumn.subColumn]: savedPkValue,
|
||||
};
|
||||
|
|
@ -2128,8 +2039,7 @@ export async function multiTableSave(
|
|||
|
||||
// 메인 마커 설정
|
||||
if (options.mainMarkerColumn) {
|
||||
mainSubItem[options.mainMarkerColumn] =
|
||||
options.mainMarkerValue ?? true;
|
||||
mainSubItem[options.mainMarkerColumn] = options.mainMarkerValue ?? true;
|
||||
}
|
||||
|
||||
// company_code 추가
|
||||
|
|
@ -2152,30 +2062,20 @@ export async function multiTableSave(
|
|||
if (companyCode !== "*") {
|
||||
checkParams.push(companyCode);
|
||||
}
|
||||
|
||||
|
||||
const existingResult = await client.query(checkQuery, checkParams);
|
||||
|
||||
|
||||
if (existingResult.rows.length > 0) {
|
||||
// UPDATE
|
||||
const updateColumns = Object.keys(mainSubItem)
|
||||
.filter(
|
||||
(col) =>
|
||||
col !== linkColumn.subColumn &&
|
||||
col !== options.mainMarkerColumn &&
|
||||
col !== "company_code"
|
||||
)
|
||||
.filter(col => col !== linkColumn.subColumn && col !== options.mainMarkerColumn && col !== "company_code")
|
||||
.map((col, idx) => `"${col}" = $${idx + 1}`)
|
||||
.join(", ");
|
||||
|
||||
|
||||
const updateValues = Object.keys(mainSubItem)
|
||||
.filter(
|
||||
(col) =>
|
||||
col !== linkColumn.subColumn &&
|
||||
col !== options.mainMarkerColumn &&
|
||||
col !== "company_code"
|
||||
)
|
||||
.map((col) => mainSubItem[col]);
|
||||
|
||||
.filter(col => col !== linkColumn.subColumn && col !== options.mainMarkerColumn && col !== "company_code")
|
||||
.map(col => mainSubItem[col]);
|
||||
|
||||
if (updateColumns) {
|
||||
const updateQuery = `
|
||||
UPDATE "${tableName}"
|
||||
|
|
@ -2194,26 +2094,14 @@ export async function multiTableSave(
|
|||
}
|
||||
|
||||
const updateResult = await client.query(updateQuery, updateParams);
|
||||
subTableResults.push({
|
||||
tableName,
|
||||
type: "main",
|
||||
data: updateResult.rows[0],
|
||||
});
|
||||
subTableResults.push({ tableName, type: "main", data: updateResult.rows[0] });
|
||||
} else {
|
||||
subTableResults.push({
|
||||
tableName,
|
||||
type: "main",
|
||||
data: existingResult.rows[0],
|
||||
});
|
||||
subTableResults.push({ tableName, type: "main", data: existingResult.rows[0] });
|
||||
}
|
||||
} else {
|
||||
// INSERT
|
||||
const mainSubColumns = Object.keys(mainSubItem)
|
||||
.map((col) => `"${col}"`)
|
||||
.join(", ");
|
||||
const mainSubPlaceholders = Object.keys(mainSubItem)
|
||||
.map((_, idx) => `$${idx + 1}`)
|
||||
.join(", ");
|
||||
const mainSubColumns = Object.keys(mainSubItem).map(col => `"${col}"`).join(", ");
|
||||
const mainSubPlaceholders = Object.keys(mainSubItem).map((_, idx) => `$${idx + 1}`).join(", ");
|
||||
const mainSubValues = Object.values(mainSubItem);
|
||||
|
||||
const insertQuery = `
|
||||
|
|
@ -2223,11 +2111,7 @@ export async function multiTableSave(
|
|||
`;
|
||||
|
||||
const insertResult = await client.query(insertQuery, mainSubValues);
|
||||
subTableResults.push({
|
||||
tableName,
|
||||
type: "main",
|
||||
data: insertResult.rows[0],
|
||||
});
|
||||
subTableResults.push({ tableName, type: "main", data: insertResult.rows[0] });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -2243,12 +2127,8 @@ export async function multiTableSave(
|
|||
item.company_code = companyCode;
|
||||
}
|
||||
|
||||
const subColumns = Object.keys(item)
|
||||
.map((col) => `"${col}"`)
|
||||
.join(", ");
|
||||
const subPlaceholders = Object.keys(item)
|
||||
.map((_, idx) => `$${idx + 1}`)
|
||||
.join(", ");
|
||||
const subColumns = Object.keys(item).map(col => `"${col}"`).join(", ");
|
||||
const subPlaceholders = Object.keys(item).map((_, idx) => `$${idx + 1}`).join(", ");
|
||||
const subValues = Object.values(item);
|
||||
|
||||
const subInsertQuery = `
|
||||
|
|
@ -2257,16 +2137,9 @@ export async function multiTableSave(
|
|||
RETURNING *
|
||||
`;
|
||||
|
||||
logger.info(`서브 테이블 ${tableName} 아이템 저장:`, {
|
||||
subInsertQuery,
|
||||
subValuesCount: subValues.length,
|
||||
});
|
||||
logger.info(`서브 테이블 ${tableName} 아이템 저장:`, { subInsertQuery, subValuesCount: subValues.length });
|
||||
const subResult = await client.query(subInsertQuery, subValues);
|
||||
subTableResults.push({
|
||||
tableName,
|
||||
type: "sub",
|
||||
data: subResult.rows[0],
|
||||
});
|
||||
subTableResults.push({ tableName, type: "sub", data: subResult.rows[0] });
|
||||
}
|
||||
|
||||
logger.info(`서브 테이블 ${tableName} 저장 완료`);
|
||||
|
|
@ -2307,11 +2180,8 @@ export async function multiTableSave(
|
|||
}
|
||||
|
||||
/**
|
||||
* 두 테이블 간의 엔티티 관계 자동 감지
|
||||
* GET /api/table-management/tables/entity-relations?leftTable=xxx&rightTable=yyy
|
||||
*
|
||||
* column_labels에서 정의된 엔티티/카테고리 타입 설정을 기반으로
|
||||
* 두 테이블 간의 외래키 관계를 자동으로 감지합니다.
|
||||
* 두 테이블 간 엔티티 관계 조회
|
||||
* column_labels의 entity/category 타입 설정을 기반으로 두 테이블 간의 관계를 조회
|
||||
*/
|
||||
export async function getTableEntityRelations(
|
||||
req: AuthenticatedRequest,
|
||||
|
|
@ -2320,54 +2190,93 @@ export async function getTableEntityRelations(
|
|||
try {
|
||||
const { leftTable, rightTable } = req.query;
|
||||
|
||||
logger.info(
|
||||
`=== 테이블 엔티티 관계 조회 시작: ${leftTable} <-> ${rightTable} ===`
|
||||
);
|
||||
|
||||
if (!leftTable || !rightTable) {
|
||||
const response: ApiResponse<null> = {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
message: "leftTable과 rightTable 파라미터가 필요합니다.",
|
||||
error: {
|
||||
code: "MISSING_PARAMETERS",
|
||||
details: "leftTable과 rightTable 쿼리 파라미터가 필요합니다.",
|
||||
},
|
||||
};
|
||||
res.status(400).json(response);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const tableManagementService = new TableManagementService();
|
||||
const relations = await tableManagementService.detectTableEntityRelations(
|
||||
String(leftTable),
|
||||
String(rightTable)
|
||||
);
|
||||
logger.info("=== 테이블 엔티티 관계 조회 ===", { leftTable, rightTable });
|
||||
|
||||
logger.info(`테이블 엔티티 관계 조회 완료: ${relations.length}개 발견`);
|
||||
// 두 테이블의 컬럼 라벨 정보 조회
|
||||
const columnLabelsQuery = `
|
||||
SELECT
|
||||
table_name,
|
||||
column_name,
|
||||
column_label,
|
||||
web_type,
|
||||
detail_settings
|
||||
FROM column_labels
|
||||
WHERE table_name IN ($1, $2)
|
||||
AND web_type IN ('entity', 'category')
|
||||
`;
|
||||
|
||||
const response: ApiResponse<any> = {
|
||||
const result = await query(columnLabelsQuery, [leftTable, rightTable]);
|
||||
|
||||
// 관계 분석
|
||||
const relations: Array<{
|
||||
fromTable: string;
|
||||
fromColumn: string;
|
||||
toTable: string;
|
||||
toColumn: string;
|
||||
relationType: string;
|
||||
}> = [];
|
||||
|
||||
for (const row of result) {
|
||||
try {
|
||||
const detailSettings = typeof row.detail_settings === "string"
|
||||
? JSON.parse(row.detail_settings)
|
||||
: row.detail_settings;
|
||||
|
||||
if (detailSettings && detailSettings.referenceTable) {
|
||||
const refTable = detailSettings.referenceTable;
|
||||
const refColumn = detailSettings.referenceColumn || "id";
|
||||
|
||||
// leftTable과 rightTable 간의 관계인지 확인
|
||||
if (
|
||||
(row.table_name === leftTable && refTable === rightTable) ||
|
||||
(row.table_name === rightTable && refTable === leftTable)
|
||||
) {
|
||||
relations.push({
|
||||
fromTable: row.table_name,
|
||||
fromColumn: row.column_name,
|
||||
toTable: refTable,
|
||||
toColumn: refColumn,
|
||||
relationType: row.web_type,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (parseError) {
|
||||
logger.warn("detail_settings 파싱 오류:", {
|
||||
table: row.table_name,
|
||||
column: row.column_name,
|
||||
error: parseError
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("테이블 엔티티 관계 조회 완료", {
|
||||
leftTable,
|
||||
rightTable,
|
||||
relationsCount: relations.length
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: `${relations.length}개의 엔티티 관계를 발견했습니다.`,
|
||||
data: {
|
||||
leftTable: String(leftTable),
|
||||
rightTable: String(rightTable),
|
||||
leftTable,
|
||||
rightTable,
|
||||
relations,
|
||||
},
|
||||
};
|
||||
|
||||
res.status(200).json(response);
|
||||
} catch (error) {
|
||||
logger.error("테이블 엔티티 관계 조회 중 오류 발생:", error);
|
||||
|
||||
const response: ApiResponse<null> = {
|
||||
});
|
||||
} catch (error: any) {
|
||||
logger.error("테이블 엔티티 관계 조회 실패:", error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: "테이블 엔티티 관계 조회 중 오류가 발생했습니다.",
|
||||
error: {
|
||||
code: "ENTITY_RELATIONS_ERROR",
|
||||
details: error instanceof Error ? error.message : "Unknown error",
|
||||
},
|
||||
};
|
||||
|
||||
res.status(500).json(response);
|
||||
message: "테이블 엔티티 관계 조회에 실패했습니다.",
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -241,5 +241,3 @@ export default function ScreenManagementPage() {
|
|||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,6 @@ import { TableSearchWidgetHeightProvider, useTableSearchWidgetHeight } from "@/c
|
|||
import { ScreenContextProvider } from "@/contexts/ScreenContext"; // 컴포넌트 간 통신
|
||||
import { SplitPanelProvider } from "@/lib/registry/components/split-panel-layout/SplitPanelContext"; // 분할 패널 리사이즈
|
||||
import { ActiveTabProvider } from "@/contexts/ActiveTabContext"; // 활성 탭 관리
|
||||
import { ScreenMultiLangProvider } from "@/contexts/ScreenMultiLangContext"; // 화면 다국어
|
||||
|
||||
function ScreenViewPage() {
|
||||
const params = useParams();
|
||||
|
|
@ -114,7 +113,7 @@ function ScreenViewPage() {
|
|||
// 편집 모달 이벤트 리스너 등록
|
||||
useEffect(() => {
|
||||
const handleOpenEditModal = (event: CustomEvent) => {
|
||||
// console.log("🎭 편집 모달 열기 이벤트 수신:", event.detail);
|
||||
console.log("🎭 편집 모달 열기 이벤트 수신:", event.detail);
|
||||
|
||||
setEditModalConfig({
|
||||
screenId: event.detail.screenId,
|
||||
|
|
@ -346,10 +345,9 @@ function ScreenViewPage() {
|
|||
|
||||
{/* 절대 위치 기반 렌더링 (화면관리와 동일한 방식) */}
|
||||
{layoutReady && layout && layout.components.length > 0 ? (
|
||||
<ScreenMultiLangProvider components={layout.components} companyCode={companyCode}>
|
||||
<div
|
||||
className="bg-background relative"
|
||||
style={{
|
||||
<div
|
||||
className="bg-background relative"
|
||||
style={{
|
||||
width: `${screenWidth}px`,
|
||||
height: `${screenHeight}px`,
|
||||
minWidth: `${screenWidth}px`,
|
||||
|
|
@ -771,8 +769,7 @@ function ScreenViewPage() {
|
|||
</>
|
||||
);
|
||||
})()}
|
||||
</div>
|
||||
</ScreenMultiLangProvider>
|
||||
</div>
|
||||
) : (
|
||||
// 빈 화면일 때
|
||||
<div className="bg-background flex items-center justify-center" style={{ minHeight: screenHeight }}>
|
||||
|
|
|
|||
|
|
@ -388,237 +388,6 @@ select {
|
|||
border-spacing: 0 !important;
|
||||
}
|
||||
|
||||
/* ===== POP (Production Operation Panel) Styles ===== */
|
||||
|
||||
/* POP 전용 다크 테마 변수 */
|
||||
.pop-dark {
|
||||
/* 배경 색상 */
|
||||
--pop-bg-deepest: 8 12 21;
|
||||
--pop-bg-deep: 10 15 28;
|
||||
--pop-bg-primary: 13 19 35;
|
||||
--pop-bg-secondary: 18 26 47;
|
||||
--pop-bg-tertiary: 25 35 60;
|
||||
--pop-bg-elevated: 32 45 75;
|
||||
|
||||
/* 네온 강조색 */
|
||||
--pop-neon-cyan: 0 212 255;
|
||||
--pop-neon-cyan-bright: 0 240 255;
|
||||
--pop-neon-cyan-dim: 0 150 190;
|
||||
--pop-neon-pink: 255 0 102;
|
||||
--pop-neon-purple: 138 43 226;
|
||||
|
||||
/* 상태 색상 */
|
||||
--pop-success: 0 255 136;
|
||||
--pop-success-dim: 0 180 100;
|
||||
--pop-warning: 255 170 0;
|
||||
--pop-warning-dim: 200 130 0;
|
||||
--pop-danger: 255 51 51;
|
||||
--pop-danger-dim: 200 40 40;
|
||||
|
||||
/* 텍스트 색상 */
|
||||
--pop-text-primary: 255 255 255;
|
||||
--pop-text-secondary: 180 195 220;
|
||||
--pop-text-muted: 100 120 150;
|
||||
|
||||
/* 테두리 색상 */
|
||||
--pop-border: 40 55 85;
|
||||
--pop-border-light: 55 75 110;
|
||||
}
|
||||
|
||||
/* POP 전용 라이트 테마 변수 */
|
||||
.pop-light {
|
||||
--pop-bg-deepest: 245 247 250;
|
||||
--pop-bg-deep: 240 243 248;
|
||||
--pop-bg-primary: 250 251 253;
|
||||
--pop-bg-secondary: 255 255 255;
|
||||
--pop-bg-tertiary: 245 247 250;
|
||||
--pop-bg-elevated: 235 238 245;
|
||||
|
||||
--pop-neon-cyan: 0 122 204;
|
||||
--pop-neon-cyan-bright: 0 140 230;
|
||||
--pop-neon-cyan-dim: 0 100 170;
|
||||
--pop-neon-pink: 220 38 127;
|
||||
--pop-neon-purple: 118 38 200;
|
||||
|
||||
--pop-success: 22 163 74;
|
||||
--pop-success-dim: 21 128 61;
|
||||
--pop-warning: 245 158 11;
|
||||
--pop-warning-dim: 217 119 6;
|
||||
--pop-danger: 220 38 38;
|
||||
--pop-danger-dim: 185 28 28;
|
||||
|
||||
--pop-text-primary: 15 23 42;
|
||||
--pop-text-secondary: 71 85 105;
|
||||
--pop-text-muted: 148 163 184;
|
||||
|
||||
--pop-border: 226 232 240;
|
||||
--pop-border-light: 203 213 225;
|
||||
}
|
||||
|
||||
/* POP 배경 그리드 패턴 */
|
||||
.pop-bg-pattern::before {
|
||||
content: "";
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background:
|
||||
repeating-linear-gradient(90deg, rgba(0, 212, 255, 0.03) 0px, transparent 1px, transparent 60px),
|
||||
repeating-linear-gradient(0deg, rgba(0, 212, 255, 0.03) 0px, transparent 1px, transparent 60px),
|
||||
radial-gradient(ellipse 80% 50% at 50% 0%, rgba(0, 212, 255, 0.08) 0%, transparent 60%);
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.pop-light .pop-bg-pattern::before {
|
||||
background:
|
||||
repeating-linear-gradient(90deg, rgba(0, 122, 204, 0.02) 0px, transparent 1px, transparent 60px),
|
||||
repeating-linear-gradient(0deg, rgba(0, 122, 204, 0.02) 0px, transparent 1px, transparent 60px),
|
||||
radial-gradient(ellipse 80% 50% at 50% 0%, rgba(0, 122, 204, 0.05) 0%, transparent 60%);
|
||||
}
|
||||
|
||||
/* POP 글로우 효과 */
|
||||
.pop-glow-cyan {
|
||||
box-shadow:
|
||||
0 0 20px rgba(0, 212, 255, 0.5),
|
||||
0 0 40px rgba(0, 212, 255, 0.3);
|
||||
}
|
||||
|
||||
.pop-glow-cyan-strong {
|
||||
box-shadow:
|
||||
0 0 10px rgba(0, 212, 255, 0.8),
|
||||
0 0 30px rgba(0, 212, 255, 0.5),
|
||||
0 0 50px rgba(0, 212, 255, 0.3);
|
||||
}
|
||||
|
||||
.pop-glow-success {
|
||||
box-shadow: 0 0 15px rgba(0, 255, 136, 0.5);
|
||||
}
|
||||
|
||||
.pop-glow-warning {
|
||||
box-shadow: 0 0 15px rgba(255, 170, 0, 0.5);
|
||||
}
|
||||
|
||||
.pop-glow-danger {
|
||||
box-shadow: 0 0 15px rgba(255, 51, 51, 0.5);
|
||||
}
|
||||
|
||||
/* POP 펄스 글로우 애니메이션 */
|
||||
@keyframes pop-pulse-glow {
|
||||
0%,
|
||||
100% {
|
||||
box-shadow: 0 0 5px rgba(0, 212, 255, 0.5);
|
||||
}
|
||||
50% {
|
||||
box-shadow:
|
||||
0 0 20px rgba(0, 212, 255, 0.8),
|
||||
0 0 30px rgba(0, 212, 255, 0.4);
|
||||
}
|
||||
}
|
||||
|
||||
.pop-animate-pulse-glow {
|
||||
animation: pop-pulse-glow 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* POP 프로그레스 바 샤인 애니메이션 */
|
||||
@keyframes pop-progress-shine {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translateX(-20px);
|
||||
}
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
transform: translateX(20px);
|
||||
}
|
||||
}
|
||||
|
||||
.pop-progress-shine::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
width: 20px;
|
||||
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3));
|
||||
animation: pop-progress-shine 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* POP 스크롤바 스타일 */
|
||||
.pop-scrollbar::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
|
||||
.pop-scrollbar::-webkit-scrollbar-track {
|
||||
background: rgb(var(--pop-bg-secondary));
|
||||
}
|
||||
|
||||
.pop-scrollbar::-webkit-scrollbar-thumb {
|
||||
background: rgb(var(--pop-border-light));
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
.pop-scrollbar::-webkit-scrollbar-thumb:hover {
|
||||
background: rgb(var(--pop-neon-cyan-dim));
|
||||
}
|
||||
|
||||
/* POP 스크롤바 숨기기 */
|
||||
.pop-hide-scrollbar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.pop-hide-scrollbar {
|
||||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
/* ===== Marching Ants Animation (Excel Copy Border) ===== */
|
||||
@keyframes marching-ants-h {
|
||||
0% {
|
||||
background-position: 0 0;
|
||||
}
|
||||
100% {
|
||||
background-position: 16px 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes marching-ants-v {
|
||||
0% {
|
||||
background-position: 0 0;
|
||||
}
|
||||
100% {
|
||||
background-position: 0 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.animate-marching-ants-h {
|
||||
background: repeating-linear-gradient(
|
||||
90deg,
|
||||
hsl(var(--primary)) 0,
|
||||
hsl(var(--primary)) 4px,
|
||||
transparent 4px,
|
||||
transparent 8px
|
||||
);
|
||||
background-size: 16px 2px;
|
||||
animation: marching-ants-h 0.4s linear infinite;
|
||||
}
|
||||
|
||||
.animate-marching-ants-v {
|
||||
background: repeating-linear-gradient(
|
||||
180deg,
|
||||
hsl(var(--primary)) 0,
|
||||
hsl(var(--primary)) 4px,
|
||||
transparent 4px,
|
||||
transparent 8px
|
||||
);
|
||||
background-size: 2px 16px;
|
||||
animation: marching-ants-v 0.4s linear infinite;
|
||||
}
|
||||
|
||||
/* ===== 저장 테이블 막대기 애니메이션 ===== */
|
||||
@keyframes saveBarDrop {
|
||||
0% {
|
||||
|
|
|
|||
|
|
@ -309,17 +309,10 @@ export const EditModal: React.FC<EditModalProps> = ({ className }) => {
|
|||
// 🆕 그룹 데이터 조회 함수
|
||||
const loadGroupData = async () => {
|
||||
if (!modalState.tableName || !modalState.groupByColumns || modalState.groupByColumns.length === 0) {
|
||||
// console.warn("테이블명 또는 그룹핑 컬럼이 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// console.log("🔍 그룹 데이터 조회 시작:", {
|
||||
// tableName: modalState.tableName,
|
||||
// groupByColumns: modalState.groupByColumns,
|
||||
// editData: modalState.editData,
|
||||
// });
|
||||
|
||||
// 그룹핑 컬럼 값 추출 (예: order_no = "ORD-20251124-001")
|
||||
const groupValues: Record<string, any> = {};
|
||||
modalState.groupByColumns.forEach((column) => {
|
||||
|
|
@ -329,15 +322,9 @@ export const EditModal: React.FC<EditModalProps> = ({ className }) => {
|
|||
});
|
||||
|
||||
if (Object.keys(groupValues).length === 0) {
|
||||
// console.warn("그룹핑 컬럼 값이 없습니다:", modalState.groupByColumns);
|
||||
return;
|
||||
}
|
||||
|
||||
// console.log("🔍 그룹 조회 요청:", {
|
||||
// tableName: modalState.tableName,
|
||||
// groupValues,
|
||||
// });
|
||||
|
||||
// 같은 그룹의 모든 레코드 조회 (entityJoinApi 사용)
|
||||
const { entityJoinApi } = await import("@/lib/api/entityJoin");
|
||||
const response = await entityJoinApi.getTableDataWithJoins(modalState.tableName, {
|
||||
|
|
@ -347,23 +334,19 @@ export const EditModal: React.FC<EditModalProps> = ({ className }) => {
|
|||
enableEntityJoin: true,
|
||||
});
|
||||
|
||||
// console.log("🔍 그룹 조회 응답:", response);
|
||||
|
||||
// entityJoinApi는 배열 또는 { data: [] } 형식으로 반환
|
||||
const dataArray = Array.isArray(response) ? response : response?.data || [];
|
||||
|
||||
if (dataArray.length > 0) {
|
||||
// console.log("✅ 그룹 데이터 조회 성공:", dataArray.length, "건");
|
||||
setGroupData(dataArray);
|
||||
setOriginalGroupData(JSON.parse(JSON.stringify(dataArray))); // Deep copy
|
||||
toast.info(`${dataArray.length}개의 관련 품목을 불러왔습니다.`);
|
||||
} else {
|
||||
console.warn("그룹 데이터가 없습니다:", response);
|
||||
setGroupData([modalState.editData]); // 기본값: 선택된 행만
|
||||
setOriginalGroupData([JSON.parse(JSON.stringify(modalState.editData))]);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error("❌ 그룹 데이터 조회 오류:", error);
|
||||
console.error("그룹 데이터 조회 오류:", error);
|
||||
toast.error("관련 데이터를 불러오는 중 오류가 발생했습니다.");
|
||||
setGroupData([modalState.editData]); // 기본값: 선택된 행만
|
||||
setOriginalGroupData([JSON.parse(JSON.stringify(modalState.editData))]);
|
||||
|
|
@ -1043,17 +1026,18 @@ export const EditModal: React.FC<EditModalProps> = ({ className }) => {
|
|||
const groupedDataProp = groupData.length > 0 ? groupData : undefined;
|
||||
|
||||
// 🆕 UniversalFormModal이 있는지 확인 (자체 저장 로직 사용)
|
||||
// 최상위 컴포넌트 또는 조건부 컨테이너 내부 화면에 universal-form-modal이 있는지 확인
|
||||
// 최상위 컴포넌트에 universal-form-modal이 있는지 확인
|
||||
// ⚠️ 수정: conditional-container는 제외 (groupData가 있으면 EditModal.handleSave 사용)
|
||||
const hasUniversalFormModal = screenData.components.some(
|
||||
(c) => {
|
||||
// 최상위에 universal-form-modal이 있는 경우
|
||||
// 최상위에 universal-form-modal이 있는 경우만 자체 저장 로직 사용
|
||||
if (c.componentType === "universal-form-modal") return true;
|
||||
// 조건부 컨테이너 내부에 universal-form-modal이 있는 경우
|
||||
// (조건부 컨테이너가 있으면 내부 화면에서 universal-form-modal을 사용하는 것으로 가정)
|
||||
if (c.componentType === "conditional-container") return true;
|
||||
return false;
|
||||
}
|
||||
);
|
||||
|
||||
// 🆕 그룹 데이터가 있으면 EditModal.handleSave 사용 (일괄 저장)
|
||||
const shouldUseEditModalSave = groupData.length > 0 || !hasUniversalFormModal;
|
||||
|
||||
// 🔑 첨부파일 컴포넌트가 행(레코드) 단위로 파일을 저장할 수 있도록 tableName 추가
|
||||
const enrichedFormData = {
|
||||
|
|
@ -1095,9 +1079,9 @@ export const EditModal: React.FC<EditModalProps> = ({ className }) => {
|
|||
id: modalState.screenId!,
|
||||
tableName: screenData.screenInfo?.tableName,
|
||||
}}
|
||||
// 🆕 UniversalFormModal이 있으면 onSave 전달 안 함 (자체 저장 로직 사용)
|
||||
// ModalRepeaterTable만 있으면 기존대로 onSave 전달 (호환성 유지)
|
||||
onSave={hasUniversalFormModal ? undefined : handleSave}
|
||||
// 🆕 그룹 데이터가 있거나 UniversalFormModal이 없으면 EditModal.handleSave 사용
|
||||
// groupData가 있으면 일괄 저장을 위해 반드시 EditModal.handleSave 사용
|
||||
onSave={shouldUseEditModalSave ? handleSave : undefined}
|
||||
isInModal={true}
|
||||
// 🆕 그룹 데이터를 ModalRepeaterTable에 전달
|
||||
groupedData={groupedDataProp}
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -365,7 +365,6 @@ export const InteractiveScreenViewerDynamic: React.FC<InteractiveScreenViewerPro
|
|||
isInteractive={true}
|
||||
formData={formData}
|
||||
originalData={originalData || undefined}
|
||||
initialData={(originalData && Object.keys(originalData).length > 0) ? originalData : formData} // 🆕 originalData가 있으면 사용, 없으면 formData 사용 (생성 모드에서 부모 데이터 전달)
|
||||
onFormDataChange={handleFormDataChange}
|
||||
screenId={screenInfo?.id}
|
||||
tableName={screenInfo?.tableName}
|
||||
|
|
|
|||
|
|
@ -416,6 +416,10 @@ export function ScreenSettingModal({
|
|||
<Database className="h-3 w-3" />
|
||||
개요
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="table-setting" className="gap-1 text-xs px-2" disabled={!mainTable}>
|
||||
<Settings2 className="h-3 w-3" />
|
||||
테이블 설정
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="control-management" className="gap-1 text-xs px-2">
|
||||
<Zap className="h-3 w-3" />
|
||||
제어 관리
|
||||
|
|
@ -466,7 +470,22 @@ export function ScreenSettingModal({
|
|||
/>
|
||||
</TabsContent>
|
||||
|
||||
{/* 탭 2: 제어 관리 */}
|
||||
{/* 탭 2: 테이블 설정 */}
|
||||
<TabsContent value="table-setting" className="mt-0 min-h-0 flex-1 overflow-hidden p-0">
|
||||
{mainTable && (
|
||||
<TableSettingModal
|
||||
isOpen={true}
|
||||
onClose={() => {}} // 탭에서는 닫기 불필요
|
||||
tableName={mainTable}
|
||||
tableLabel={mainTableLabel}
|
||||
screenId={currentScreenId}
|
||||
onSaveSuccess={handleRefresh}
|
||||
isEmbedded={true} // 임베드 모드
|
||||
/>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
{/* 탭 3: 제어 관리 */}
|
||||
<TabsContent value="control-management" className="mt-0 min-h-0 flex-1 overflow-auto p-3">
|
||||
<ControlManagementTab
|
||||
screenId={currentScreenId}
|
||||
|
|
@ -2198,17 +2217,6 @@ function OverviewTab({
|
|||
<Database className="h-4 w-4 text-blue-500" />
|
||||
메인 테이블
|
||||
</h3>
|
||||
{mainTable && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 gap-1 text-xs"
|
||||
onClick={() => onOpenTableSetting?.(mainTable, mainTableLabel)}
|
||||
>
|
||||
<Settings2 className="h-3 w-3" />
|
||||
테이블 설정
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{mainTable ? (
|
||||
<TableColumnAccordion
|
||||
|
|
@ -3049,6 +3057,7 @@ interface ButtonControlInfo {
|
|||
// 버튼 스타일
|
||||
backgroundColor?: string;
|
||||
textColor?: string;
|
||||
borderRadius?: string;
|
||||
// 모달/네비게이션 관련
|
||||
modalScreenId?: number;
|
||||
navigateScreenId?: number;
|
||||
|
|
@ -3215,6 +3224,7 @@ function ControlManagementTab({
|
|||
// 버튼 스타일 (webTypeConfig 우선)
|
||||
backgroundColor: webTypeConfig.backgroundColor || config.backgroundColor || style.backgroundColor,
|
||||
textColor: webTypeConfig.textColor || config.textColor || style.color || style.labelColor,
|
||||
borderRadius: webTypeConfig.borderRadius || config.borderRadius || style.borderRadius,
|
||||
// 모달/네비게이션 관련 (화면 디자이너는 targetScreenId 사용)
|
||||
modalScreenId: action.targetScreenId || action.modalScreenId,
|
||||
navigateScreenId: action.navigateScreenId || action.targetScreenId,
|
||||
|
|
@ -3527,6 +3537,11 @@ function ControlManagementTab({
|
|||
comp.style.color = values.textColor;
|
||||
comp.style.labelColor = values.textColor;
|
||||
}
|
||||
if (values.borderRadius !== undefined) {
|
||||
comp.webTypeConfig.borderRadius = values.borderRadius;
|
||||
comp.componentConfig.borderRadius = values.borderRadius;
|
||||
comp.style.borderRadius = values.borderRadius;
|
||||
}
|
||||
|
||||
// 액션 타입 업데이트
|
||||
if (values.actionType) {
|
||||
|
|
@ -3735,6 +3750,7 @@ function ControlManagementTab({
|
|||
const currentLabel = editedValues[btn.id]?.label ?? btn.label;
|
||||
const currentBgColor = editedValues[btn.id]?.backgroundColor ?? btn.backgroundColor ?? "#3b82f6";
|
||||
const currentTextColor = editedValues[btn.id]?.textColor ?? btn.textColor ?? "#ffffff";
|
||||
const currentBorderRadius = editedValues[btn.id]?.borderRadius ?? btn.borderRadius ?? "4px";
|
||||
|
||||
return (
|
||||
<div key={btn.id} className="py-3 px-1">
|
||||
|
|
@ -3742,10 +3758,11 @@ function ControlManagementTab({
|
|||
<div className="flex items-center gap-3 mb-3">
|
||||
{/* 버튼 프리뷰 */}
|
||||
<div
|
||||
className="flex items-center justify-center px-3 py-1.5 rounded text-xs font-medium min-w-[60px] shrink-0"
|
||||
className="flex items-center justify-center px-3 py-1.5 text-xs font-medium min-w-[60px] shrink-0"
|
||||
style={{
|
||||
backgroundColor: currentBgColor,
|
||||
color: currentTextColor,
|
||||
borderRadius: currentBorderRadius,
|
||||
}}
|
||||
>
|
||||
{currentLabel || "버튼"}
|
||||
|
|
@ -3870,6 +3887,34 @@ function ControlManagementTab({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* 버튼 모서리 (borderRadius) */}
|
||||
<div className="grid grid-cols-[80px_1fr] items-center gap-2">
|
||||
<Label className="text-xs text-muted-foreground">모서리</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Select
|
||||
value={editedValues[btn.id]?.borderRadius ?? btn.borderRadius ?? "4px"}
|
||||
onValueChange={(val) => setEditedValues(prev => ({
|
||||
...prev,
|
||||
[btn.id]: { ...prev[btn.id], borderRadius: val }
|
||||
}))}
|
||||
>
|
||||
<SelectTrigger className="h-7 w-[100px] text-xs">
|
||||
<SelectValue placeholder="선택" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="0px" className="text-xs">없음 (0px)</SelectItem>
|
||||
<SelectItem value="2px" className="text-xs">약간 (2px)</SelectItem>
|
||||
<SelectItem value="4px" className="text-xs">기본 (4px)</SelectItem>
|
||||
<SelectItem value="6px" className="text-xs">둥글게 (6px)</SelectItem>
|
||||
<SelectItem value="8px" className="text-xs">더 둥글게 (8px)</SelectItem>
|
||||
<SelectItem value="12px" className="text-xs">많이 (12px)</SelectItem>
|
||||
<SelectItem value="9999px" className="text-xs">원형</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<span className="text-[10px] text-muted-foreground">버튼 모서리 둥글기</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 확인 메시지 설정 (save/delete 액션에서만 표시) */}
|
||||
{((editedValues[btn.id]?.actionType || btn.actionType) === "save" ||
|
||||
(editedValues[btn.id]?.actionType || btn.actionType) === "delete") && (
|
||||
|
|
|
|||
|
|
@ -129,6 +129,7 @@ interface TableSettingModalProps {
|
|||
columns?: ColumnInfo[];
|
||||
filterColumns?: string[];
|
||||
onSaveSuccess?: () => void;
|
||||
isEmbedded?: boolean; // 탭 안에 임베드 모드로 표시
|
||||
}
|
||||
|
||||
// 검색 가능한 Select 컴포넌트
|
||||
|
|
@ -256,6 +257,7 @@ export function TableSettingModal({
|
|||
columns = [],
|
||||
filterColumns = [],
|
||||
onSaveSuccess,
|
||||
isEmbedded = false,
|
||||
}: TableSettingModalProps) {
|
||||
const [activeTab, setActiveTab] = useState("columns");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
|
@ -304,9 +306,19 @@ export function TableSettingModal({
|
|||
// 초기 편집 상태 설정
|
||||
const initialEdits: Record<string, Partial<ColumnTypeInfo>> = {};
|
||||
columnsData.forEach((col) => {
|
||||
// referenceTable이 설정되어 있으면 inputType은 entity여야 함
|
||||
let effectiveInputType = col.inputType || "direct";
|
||||
if (col.referenceTable && effectiveInputType !== "entity") {
|
||||
effectiveInputType = "entity";
|
||||
}
|
||||
// codeCategory/codeValue가 설정되어 있으면 inputType은 code여야 함
|
||||
if (col.codeCategory && effectiveInputType !== "code") {
|
||||
effectiveInputType = "code";
|
||||
}
|
||||
|
||||
initialEdits[col.columnName] = {
|
||||
displayName: col.displayName,
|
||||
inputType: col.inputType || "direct",
|
||||
inputType: effectiveInputType,
|
||||
referenceTable: col.referenceTable,
|
||||
referenceColumn: col.referenceColumn,
|
||||
displayColumn: col.displayColumn,
|
||||
|
|
@ -343,10 +355,10 @@ export function TableSettingModal({
|
|||
try {
|
||||
// 모든 화면 조회
|
||||
const screensResponse = await screenApi.getScreens({ size: 1000 });
|
||||
if (screensResponse.items) {
|
||||
if (screensResponse.data) {
|
||||
const usingScreens: ScreenUsingTable[] = [];
|
||||
|
||||
screensResponse.items.forEach((screen: any) => {
|
||||
screensResponse.data.forEach((screen: any) => {
|
||||
// 메인 테이블로 사용하는 경우
|
||||
if (screen.tableName === tableName) {
|
||||
usingScreens.push({
|
||||
|
|
@ -418,6 +430,35 @@ export function TableSettingModal({
|
|||
},
|
||||
}));
|
||||
|
||||
// 입력 타입 변경 시 관련 필드 초기화
|
||||
if (field === "inputType") {
|
||||
// 엔티티가 아닌 다른 타입으로 변경하면 참조 설정 초기화
|
||||
if (value !== "entity") {
|
||||
setEditedColumns((prev) => ({
|
||||
...prev,
|
||||
[columnName]: {
|
||||
...prev[columnName],
|
||||
inputType: value,
|
||||
referenceTable: "",
|
||||
referenceColumn: "",
|
||||
displayColumn: "",
|
||||
},
|
||||
}));
|
||||
}
|
||||
// 코드가 아닌 다른 타입으로 변경하면 코드 설정 초기화
|
||||
if (value !== "code") {
|
||||
setEditedColumns((prev) => ({
|
||||
...prev,
|
||||
[columnName]: {
|
||||
...prev[columnName],
|
||||
inputType: value,
|
||||
codeCategory: "",
|
||||
codeValue: "",
|
||||
},
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// 참조 테이블 변경 시 참조 컬럼 초기화
|
||||
if (field === "referenceTable") {
|
||||
setEditedColumns((prev) => ({
|
||||
|
|
@ -452,8 +493,18 @@ export function TableSettingModal({
|
|||
|
||||
// detailSettings 처리 (Entity 타입인 경우)
|
||||
let finalDetailSettings = mergedColumn.detailSettings || "";
|
||||
|
||||
// referenceTable이 설정되어 있으면 inputType을 entity로 자동 설정
|
||||
let currentInputType = (mergedColumn.inputType || "") as string;
|
||||
if (mergedColumn.referenceTable && currentInputType !== "entity") {
|
||||
currentInputType = "entity";
|
||||
}
|
||||
// codeCategory가 설정되어 있으면 inputType을 code로 자동 설정
|
||||
if (mergedColumn.codeCategory && currentInputType !== "code") {
|
||||
currentInputType = "code";
|
||||
}
|
||||
|
||||
if (mergedColumn.inputType === "entity" && mergedColumn.referenceTable) {
|
||||
if (currentInputType === "entity" && mergedColumn.referenceTable) {
|
||||
// 기존 detailSettings를 파싱하거나 새로 생성
|
||||
let existingSettings: Record<string, unknown> = {};
|
||||
if (typeof mergedColumn.detailSettings === "string" && mergedColumn.detailSettings.trim().startsWith("{")) {
|
||||
|
|
@ -479,7 +530,7 @@ export function TableSettingModal({
|
|||
}
|
||||
|
||||
// Code 타입인 경우 hierarchyRole을 detailSettings에 포함
|
||||
if (mergedColumn.inputType === "code" && (mergedColumn as any).hierarchyRole) {
|
||||
if (currentInputType === "code" && (mergedColumn as any).hierarchyRole) {
|
||||
let existingSettings: Record<string, unknown> = {};
|
||||
if (typeof finalDetailSettings === "string" && finalDetailSettings.trim().startsWith("{")) {
|
||||
try {
|
||||
|
|
@ -502,7 +553,7 @@ export function TableSettingModal({
|
|||
const columnSetting: ColumnSettings = {
|
||||
columnName: columnName,
|
||||
columnLabel: mergedColumn.displayName || originalColumn.displayName || "",
|
||||
webType: mergedColumn.inputType || originalColumn.inputType || "text",
|
||||
inputType: currentInputType || "text", // referenceTable/codeCategory가 설정된 경우 자동 보정된 값 사용
|
||||
detailSettings: finalDetailSettings,
|
||||
codeCategory: mergedColumn.codeCategory || originalColumn.codeCategory || "",
|
||||
codeValue: mergedColumn.codeValue || originalColumn.codeValue || "",
|
||||
|
|
@ -593,6 +644,158 @@ export function TableSettingModal({
|
|||
];
|
||||
};
|
||||
|
||||
// 임베드 모드
|
||||
if (isEmbedded) {
|
||||
return (
|
||||
<>
|
||||
<div className="flex h-full flex-col">
|
||||
{/* 헤더 */}
|
||||
<div className="flex flex-shrink-0 items-center justify-between border-b pb-2 px-3 pt-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Table2 className="h-4 w-4 text-green-500" />
|
||||
<span className="text-sm font-medium">{tableLabel || tableName}</span>
|
||||
{tableName !== tableLabel && tableName !== (tableLabel || tableName) && (
|
||||
<span className="text-xs text-muted-foreground">({tableName})</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setShowTableManagementModal(true)}
|
||||
className="h-7 gap-1 text-xs"
|
||||
>
|
||||
<Settings className="h-3 w-3" />
|
||||
테이블 타입 관리
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleRefresh}
|
||||
className="h-7 w-7 p-0"
|
||||
disabled={loading}
|
||||
>
|
||||
<RefreshCw className={cn("h-3 w-3", loading && "animate-spin")} />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSaveAll}
|
||||
className="h-7 gap-1 text-xs"
|
||||
disabled={saving || loading}
|
||||
>
|
||||
{saving ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<Save className="h-3 w-3" />
|
||||
)}
|
||||
저장
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 gap-3 p-3">
|
||||
{/* 좌측: 탭 (40%) */}
|
||||
<div className="flex w-[40%] min-h-0 flex-col">
|
||||
<Tabs
|
||||
value={activeTab}
|
||||
onValueChange={setActiveTab}
|
||||
className="flex min-h-0 flex-1 flex-col"
|
||||
>
|
||||
<TabsList className="h-8 flex-shrink-0">
|
||||
<TabsTrigger value="columns" className="gap-1 text-xs">
|
||||
<Columns3 className="h-3 w-3" />
|
||||
컬럼 설정
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="screens" className="gap-1 text-xs">
|
||||
<Monitor className="h-3 w-3" />
|
||||
화면 연동
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="references" className="gap-1 text-xs">
|
||||
<Eye className="h-3 w-3" />
|
||||
참조 관계
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
<TabsContent value="columns" className="mt-2 min-h-0 flex-1 overflow-hidden">
|
||||
<ColumnListTab
|
||||
columns={tableColumns.map((col) => ({
|
||||
...col,
|
||||
isPK: col.columnName === "id" || col.columnName.endsWith("_id"),
|
||||
isFK: (col.inputType as string) === "entity",
|
||||
}))}
|
||||
editedColumns={editedColumns}
|
||||
selectedColumn={selectedColumn}
|
||||
onSelectColumn={setSelectedColumn}
|
||||
loading={loading}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="screens" className="mt-2 min-h-0 flex-1 overflow-hidden">
|
||||
<ScreensTab screensUsingTable={screensUsingTable} loading={loading} />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="references" className="mt-2 min-h-0 flex-1 overflow-hidden">
|
||||
<ReferenceTab
|
||||
tableName={tableName}
|
||||
tableLabel={tableLabel}
|
||||
referencedBy={referencedBy}
|
||||
joinColumnRefs={joinColumnRefs}
|
||||
loading={loading}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
{/* 우측: 상세 설정 (60%) */}
|
||||
<div className="flex w-[60%] min-h-0 flex-col rounded-lg border bg-muted/30 p-3">
|
||||
{selectedColumn && mergedColumns.find((c) => c.columnName === selectedColumn) ? (
|
||||
<ColumnDetailPanel
|
||||
columnInfo={mergedColumns.find((c) => c.columnName === selectedColumn)!}
|
||||
editedColumn={editedColumns[selectedColumn] || {}}
|
||||
tableOptions={tableOptions}
|
||||
inputTypeOptions={inputTypeOptions}
|
||||
getRefColumnOptions={getRefColumnOptions}
|
||||
loadingRefColumns={loadingRefColumns}
|
||||
onColumnChange={(field, value) => handleColumnChange(selectedColumn, field, value)}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center text-sm text-muted-foreground">
|
||||
<div className="text-center">
|
||||
<Columns3 className="mx-auto h-12 w-12 text-muted-foreground/30" />
|
||||
<p className="mt-2">왼쪽에서 컬럼을 선택하면</p>
|
||||
<p>상세 설정을 할 수 있습니다.</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 테이블 타입 관리 모달 */}
|
||||
<Dialog open={showTableManagementModal} onOpenChange={setShowTableManagementModal}>
|
||||
<DialogContent className="flex h-[90vh] max-h-[1000px] w-[95vw] max-w-[1400px] flex-col p-0">
|
||||
<div className="flex items-center justify-between border-b p-4">
|
||||
<h2 className="text-lg font-semibold">테이블 타입 관리</h2>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
setShowTableManagementModal(false);
|
||||
loadTableData();
|
||||
}}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<TableManagementPage />
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// 기존 모달 모드
|
||||
return (
|
||||
<>
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
|
|
@ -843,6 +1046,7 @@ function ColumnListTab({
|
|||
<div className="space-y-1 px-3 pb-3">
|
||||
{filteredColumns.map((col) => {
|
||||
const edited = editedColumns[col.columnName] || {};
|
||||
// editedColumns에서 inputType을 가져옴 (초기화 시 이미 보정됨)
|
||||
const inputType = (edited.inputType || col.inputType || "text") as string;
|
||||
const isSelected = selectedColumn === col.columnName;
|
||||
|
||||
|
|
@ -873,23 +1077,17 @@ function ColumnListTab({
|
|||
PK
|
||||
</Badge>
|
||||
)}
|
||||
{col.isFK && (
|
||||
<Badge variant="outline" className="bg-green-100 text-green-700 text-[10px] px-1.5">
|
||||
<Link2 className="mr-0.5 h-2.5 w-2.5" />
|
||||
FK
|
||||
</Badge>
|
||||
)}
|
||||
{(edited.referenceTable || col.referenceTable) && (
|
||||
{/* 엔티티 타입이거나 referenceTable이 설정되어 있으면 조인 배지 표시 (FK와 동일 의미) */}
|
||||
{(inputType === "entity" || edited.referenceTable || col.referenceTable) && (
|
||||
<Badge variant="outline" className="bg-blue-100 text-blue-700 text-[10px] px-1.5">
|
||||
<Link2 className="mr-0.5 h-2.5 w-2.5" />
|
||||
조인
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-1 flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<div className="mt-1 text-xs text-muted-foreground">
|
||||
<span className="font-mono">{col.columnName}</span>
|
||||
<span>•</span>
|
||||
<span>{col.dataType}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
@ -925,10 +1123,11 @@ function ColumnDetailPanel({
|
|||
onColumnChange,
|
||||
}: ColumnDetailPanelProps) {
|
||||
const currentLabel = editedColumn.displayName ?? columnInfo.displayName ?? "";
|
||||
const currentInputType = (editedColumn.inputType ?? columnInfo.inputType ?? "text") as string;
|
||||
const currentRefTable = editedColumn.referenceTable ?? columnInfo.referenceTable ?? "";
|
||||
const currentRefColumn = editedColumn.referenceColumn ?? columnInfo.referenceColumn ?? "";
|
||||
const currentDisplayColumn = editedColumn.displayColumn ?? columnInfo.displayColumn ?? "";
|
||||
// editedColumn에서 inputType을 가져옴 (초기화 시 이미 보정됨)
|
||||
const currentInputType = (editedColumn.inputType ?? columnInfo.inputType ?? "text") as string;
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
|
|
@ -948,9 +1147,10 @@ function ColumnDetailPanel({
|
|||
Primary Key
|
||||
</Badge>
|
||||
)}
|
||||
{columnInfo.isFK && (
|
||||
<Badge variant="outline" className="bg-green-100 text-green-700 text-[10px]">
|
||||
Foreign Key
|
||||
{/* 엔티티 타입이거나 referenceTable이 있으면 조인 배지 표시 */}
|
||||
{(currentInputType === "entity" || currentRefTable) && (
|
||||
<Badge variant="outline" className="bg-blue-100 text-blue-700 text-[10px]">
|
||||
조인
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -77,12 +77,6 @@ export const entityJoinApi = {
|
|||
filterColumn?: string;
|
||||
filterValue?: any;
|
||||
}; // 🆕 제외 필터 (다른 테이블에 이미 존재하는 데이터 제외)
|
||||
deduplication?: {
|
||||
enabled: boolean;
|
||||
groupByColumn: string;
|
||||
keepStrategy: "latest" | "earliest" | "base_price" | "current_date";
|
||||
sortColumn?: string;
|
||||
}; // 🆕 중복 제거 설정
|
||||
companyCodeOverride?: string; // 🆕 프리뷰용 회사 코드 오버라이드 (최고 관리자만 사용 가능)
|
||||
} = {},
|
||||
): Promise<EntityJoinResponse> => {
|
||||
|
|
@ -116,7 +110,6 @@ export const entityJoinApi = {
|
|||
autoFilter: JSON.stringify(autoFilter), // 🔒 멀티테넌시 필터링 (오버라이드 포함)
|
||||
dataFilter: params.dataFilter ? JSON.stringify(params.dataFilter) : undefined, // 🆕 데이터 필터
|
||||
excludeFilter: params.excludeFilter ? JSON.stringify(params.excludeFilter) : undefined, // 🆕 제외 필터
|
||||
deduplication: params.deduplication ? JSON.stringify(params.deduplication) : undefined, // 🆕 중복 제거 설정
|
||||
},
|
||||
});
|
||||
return response.data.data;
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ export interface ColumnTypeInfo {
|
|||
dataType: string;
|
||||
dbType: string;
|
||||
webType: string;
|
||||
inputType?: "direct" | "auto";
|
||||
inputType?: string; // text, number, entity, code, select, date, checkbox 등
|
||||
detailSettings: string;
|
||||
description?: string;
|
||||
isNullable: string;
|
||||
|
|
@ -39,11 +39,11 @@ export interface TableInfo {
|
|||
columnCount: number;
|
||||
}
|
||||
|
||||
// 컬럼 설정 타입
|
||||
// 컬럼 설정 타입 (백엔드 API와 동일한 필드명 사용)
|
||||
export interface ColumnSettings {
|
||||
columnName?: string;
|
||||
columnLabel: string;
|
||||
webType: string;
|
||||
inputType: string; // 백엔드에서 inputType으로 받음
|
||||
detailSettings: string;
|
||||
codeCategory: string;
|
||||
codeValue: string;
|
||||
|
|
|
|||
|
|
@ -27,7 +27,6 @@ import { useScreenContextOptional } from "@/contexts/ScreenContext";
|
|||
import { useSplitPanelContext, SplitPanelPosition } from "@/contexts/SplitPanelContext";
|
||||
import { applyMappingRules } from "@/lib/utils/dataMapping";
|
||||
import { apiClient } from "@/lib/api/client";
|
||||
import { useScreenMultiLang } from "@/contexts/ScreenMultiLangContext";
|
||||
|
||||
export interface ButtonPrimaryComponentProps extends ComponentRendererProps {
|
||||
config?: ButtonPrimaryConfig;
|
||||
|
|
@ -108,7 +107,6 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
|
|||
const { isPreviewMode } = useScreenPreview(); // 프리뷰 모드 확인
|
||||
const screenContext = useScreenContextOptional(); // 화면 컨텍스트
|
||||
const splitPanelContext = useSplitPanelContext(); // 분할 패널 컨텍스트
|
||||
const { getTranslatedText } = useScreenMultiLang(); // 다국어 컨텍스트
|
||||
// 🆕 ScreenContext에서 splitPanelPosition 가져오기 (중첩 화면에서도 작동)
|
||||
const splitPanelPosition = screenContext?.splitPanelPosition;
|
||||
|
||||
|
|
@ -301,20 +299,6 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
|
|||
// 🆕 modalDataStore에서 선택된 데이터 확인 (분할 패널 등에서 저장됨)
|
||||
const [modalStoreData, setModalStoreData] = useState<Record<string, any[]>>({});
|
||||
|
||||
// 🆕 splitPanelContext?.selectedLeftData를 로컬 상태로 추적 (리렌더링 보장)
|
||||
const [trackedSelectedLeftData, setTrackedSelectedLeftData] = useState<Record<string, any> | null>(null);
|
||||
|
||||
// splitPanelContext?.selectedLeftData 변경 감지 및 로컬 상태 동기화
|
||||
useEffect(() => {
|
||||
const newData = splitPanelContext?.selectedLeftData ?? null;
|
||||
setTrackedSelectedLeftData(newData);
|
||||
// console.log("🔄 [ButtonPrimary] selectedLeftData 변경 감지:", {
|
||||
// label: component.label,
|
||||
// hasData: !!newData,
|
||||
// dataKeys: newData ? Object.keys(newData) : [],
|
||||
// });
|
||||
}, [splitPanelContext?.selectedLeftData, component.label]);
|
||||
|
||||
// modalDataStore 상태 구독 (실시간 업데이트)
|
||||
useEffect(() => {
|
||||
const actionConfig = component.componentConfig?.action;
|
||||
|
|
@ -373,8 +357,8 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
|
|||
|
||||
// 2. 분할 패널 좌측 선택 데이터 확인
|
||||
if (rowSelectionSource === "auto" || rowSelectionSource === "splitPanelLeft") {
|
||||
// SplitPanelContext에서 확인 (trackedSelectedLeftData 사용으로 리렌더링 보장)
|
||||
if (trackedSelectedLeftData && Object.keys(trackedSelectedLeftData).length > 0) {
|
||||
// SplitPanelContext에서 확인
|
||||
if (splitPanelContext?.selectedLeftData && Object.keys(splitPanelContext.selectedLeftData).length > 0) {
|
||||
if (!hasSelection) {
|
||||
hasSelection = true;
|
||||
selectionCount = 1;
|
||||
|
|
@ -413,7 +397,7 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
|
|||
selectionCount,
|
||||
selectionSource,
|
||||
hasSplitPanelContext: !!splitPanelContext,
|
||||
trackedSelectedLeftData: trackedSelectedLeftData,
|
||||
selectedLeftData: splitPanelContext?.selectedLeftData,
|
||||
selectedRowsData: selectedRowsData?.length,
|
||||
selectedRows: selectedRows?.length,
|
||||
flowSelectedData: flowSelectedData?.length,
|
||||
|
|
@ -445,7 +429,7 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
|
|||
component.label,
|
||||
selectedRows,
|
||||
selectedRowsData,
|
||||
trackedSelectedLeftData,
|
||||
splitPanelContext?.selectedLeftData,
|
||||
flowSelectedData,
|
||||
splitPanelContext,
|
||||
modalStoreData,
|
||||
|
|
@ -737,99 +721,61 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
|
|||
return;
|
||||
}
|
||||
|
||||
if (!screenContext) {
|
||||
toast.error("화면 컨텍스트를 찾을 수 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
let sourceData: any[] = [];
|
||||
// 1. 소스 컴포넌트에서 데이터 가져오기
|
||||
let sourceProvider = screenContext.getDataProvider(dataTransferConfig.sourceComponentId);
|
||||
|
||||
// 1. ScreenContext에서 DataProvider를 통해 데이터 가져오기 시도
|
||||
if (screenContext) {
|
||||
let sourceProvider = screenContext.getDataProvider(dataTransferConfig.sourceComponentId);
|
||||
// 🆕 소스 컴포넌트를 찾을 수 없으면, 현재 화면에서 테이블 리스트 자동 탐색
|
||||
// (조건부 컨테이너의 다른 섹션으로 전환했을 때 이전 컴포넌트 ID가 남아있는 경우 대응)
|
||||
if (!sourceProvider) {
|
||||
console.log(`⚠️ [ButtonPrimary] 지정된 소스 컴포넌트를 찾을 수 없음: ${dataTransferConfig.sourceComponentId}`);
|
||||
console.log(`🔍 [ButtonPrimary] 현재 화면에서 DataProvider 자동 탐색...`);
|
||||
|
||||
const allProviders = screenContext.getAllDataProviders();
|
||||
|
||||
// 테이블 리스트 우선 탐색
|
||||
for (const [id, provider] of allProviders) {
|
||||
if (provider.componentType === "table-list") {
|
||||
sourceProvider = provider;
|
||||
console.log(`✅ [ButtonPrimary] 테이블 리스트 자동 발견: ${id}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 테이블 리스트가 없으면 첫 번째 DataProvider 사용
|
||||
if (!sourceProvider && allProviders.size > 0) {
|
||||
const firstEntry = allProviders.entries().next().value;
|
||||
if (firstEntry) {
|
||||
sourceProvider = firstEntry[1];
|
||||
console.log(
|
||||
`✅ [ButtonPrimary] 첫 번째 DataProvider 사용: ${firstEntry[0]} (${sourceProvider.componentType})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 소스 컴포넌트를 찾을 수 없으면, 현재 화면에서 테이블 리스트 자동 탐색
|
||||
if (!sourceProvider) {
|
||||
console.log(`⚠️ [ButtonPrimary] 지정된 소스 컴포넌트를 찾을 수 없음: ${dataTransferConfig.sourceComponentId}`);
|
||||
console.log(`🔍 [ButtonPrimary] 현재 화면에서 DataProvider 자동 탐색...`);
|
||||
|
||||
const allProviders = screenContext.getAllDataProviders();
|
||||
console.log(`📋 [ButtonPrimary] 등록된 DataProvider 목록:`, Array.from(allProviders.keys()));
|
||||
|
||||
// 테이블 리스트 우선 탐색
|
||||
for (const [id, provider] of allProviders) {
|
||||
if (provider.componentType === "table-list") {
|
||||
sourceProvider = provider;
|
||||
console.log(`✅ [ButtonPrimary] 테이블 리스트 자동 발견: ${id}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 테이블 리스트가 없으면 첫 번째 DataProvider 사용
|
||||
if (!sourceProvider && allProviders.size > 0) {
|
||||
const firstEntry = allProviders.entries().next().value;
|
||||
if (firstEntry) {
|
||||
sourceProvider = firstEntry[1];
|
||||
console.log(
|
||||
`✅ [ButtonPrimary] 첫 번째 DataProvider 사용: ${firstEntry[0]} (${sourceProvider.componentType})`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sourceProvider) {
|
||||
const rawSourceData = sourceProvider.getSelectedData();
|
||||
sourceData = Array.isArray(rawSourceData) ? rawSourceData : rawSourceData ? [rawSourceData] : [];
|
||||
console.log("📦 [ButtonPrimary] ScreenContext에서 소스 데이터 획득:", {
|
||||
rawSourceData,
|
||||
sourceData,
|
||||
count: sourceData.length
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.log("⚠️ [ButtonPrimary] ScreenContext가 없습니다. modalDataStore에서 데이터를 찾습니다.");
|
||||
}
|
||||
|
||||
// 2. ScreenContext에서 데이터를 찾지 못한 경우, modalDataStore에서 fallback 조회
|
||||
if (sourceData.length === 0) {
|
||||
console.log("🔍 [ButtonPrimary] modalDataStore에서 데이터 탐색 시도...");
|
||||
|
||||
try {
|
||||
const { useModalDataStore } = await import("@/stores/modalDataStore");
|
||||
const dataRegistry = useModalDataStore.getState().dataRegistry;
|
||||
|
||||
console.log("📋 [ButtonPrimary] modalDataStore 전체 키:", Object.keys(dataRegistry));
|
||||
|
||||
// sourceTableName이 지정되어 있으면 해당 테이블에서 조회
|
||||
const sourceTableName = dataTransferConfig.sourceTableName || tableName;
|
||||
|
||||
if (sourceTableName && dataRegistry[sourceTableName]) {
|
||||
const modalData = dataRegistry[sourceTableName];
|
||||
sourceData = modalData.map((item: any) => item.originalData || item);
|
||||
console.log(`✅ [ButtonPrimary] modalDataStore에서 데이터 발견 (${sourceTableName}):`, sourceData.length, "건");
|
||||
} else {
|
||||
// 테이블명으로 못 찾으면 첫 번째 데이터 사용
|
||||
const firstKey = Object.keys(dataRegistry)[0];
|
||||
if (firstKey && dataRegistry[firstKey]?.length > 0) {
|
||||
const modalData = dataRegistry[firstKey];
|
||||
sourceData = modalData.map((item: any) => item.originalData || item);
|
||||
console.log(`✅ [ButtonPrimary] modalDataStore 첫 번째 키에서 데이터 발견 (${firstKey}):`, sourceData.length, "건");
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn("⚠️ [ButtonPrimary] modalDataStore 접근 실패:", err);
|
||||
toast.error("데이터를 제공할 수 있는 컴포넌트를 찾을 수 없습니다.");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 여전히 데이터가 없으면 에러
|
||||
const rawSourceData = sourceProvider.getSelectedData();
|
||||
|
||||
// 🆕 배열이 아닌 경우 배열로 변환
|
||||
const sourceData = Array.isArray(rawSourceData) ? rawSourceData : rawSourceData ? [rawSourceData] : [];
|
||||
|
||||
console.log("📦 소스 데이터:", { rawSourceData, sourceData, isArray: Array.isArray(rawSourceData) });
|
||||
|
||||
if (!sourceData || sourceData.length === 0) {
|
||||
console.error("❌ [ButtonPrimary] 선택된 데이터를 찾을 수 없습니다.", {
|
||||
hasScreenContext: !!screenContext,
|
||||
sourceComponentId: dataTransferConfig.sourceComponentId,
|
||||
sourceTableName: dataTransferConfig.sourceTableName || tableName,
|
||||
});
|
||||
toast.warning("선택된 데이터가 없습니다. 항목을 먼저 선택해주세요.");
|
||||
toast.warning("선택된 데이터가 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("📦 [ButtonPrimary] 최종 소스 데이터:", { sourceData, count: sourceData.length });
|
||||
|
||||
// 1.5. 추가 데이터 소스 처리 (예: 조건부 컨테이너의 카테고리 값)
|
||||
let additionalData: Record<string, any> = {};
|
||||
|
||||
|
|
@ -1360,10 +1306,7 @@ export const ButtonPrimaryComponent: React.FC<ButtonPrimaryComponentProps> = ({
|
|||
...userStyle,
|
||||
};
|
||||
|
||||
// 다국어 적용: componentConfig.langKey가 있으면 번역 텍스트 사용
|
||||
const langKey = (component as any).componentConfig?.langKey;
|
||||
const originalButtonText = processedConfig.text !== undefined ? processedConfig.text : component.label || "버튼";
|
||||
const buttonContent = getTranslatedText(langKey, originalButtonText);
|
||||
const buttonContent = processedConfig.text !== undefined ? processedConfig.text : component.label || "버튼";
|
||||
|
||||
return (
|
||||
<>
|
||||
|
|
|
|||
|
|
@ -180,8 +180,11 @@ export function ModalRepeaterTableComponent({
|
|||
filterCondition: propFilterCondition,
|
||||
companyCode: propCompanyCode,
|
||||
|
||||
// 🆕 그룹 데이터 (EditModal에서 전달, 같은 그룹의 여러 품목)
|
||||
groupedData,
|
||||
|
||||
...props
|
||||
}: ModalRepeaterTableComponentProps) {
|
||||
}: ModalRepeaterTableComponentProps & { groupedData?: Record<string, any>[] }) {
|
||||
// ✅ config 또는 component.config 또는 개별 prop 우선순위로 병합
|
||||
const componentConfig = {
|
||||
...config,
|
||||
|
|
@ -208,9 +211,16 @@ export function ModalRepeaterTableComponent({
|
|||
// 모달 필터 설정
|
||||
const modalFilters = componentConfig?.modalFilters || [];
|
||||
|
||||
// ✅ value는 formData[columnName] 우선, 없으면 prop 사용
|
||||
// ✅ value는 groupedData 우선, 없으면 formData[columnName], 없으면 prop 사용
|
||||
const columnName = component?.columnName;
|
||||
const externalValue = (columnName && formData?.[columnName]) || componentConfig?.value || propValue || [];
|
||||
|
||||
// 🆕 groupedData가 전달되면 (EditModal에서 그룹 조회 결과) 우선 사용
|
||||
const externalValue = (() => {
|
||||
if (groupedData && groupedData.length > 0) {
|
||||
return groupedData;
|
||||
}
|
||||
return (columnName && formData?.[columnName]) || componentConfig?.value || propValue || [];
|
||||
})();
|
||||
|
||||
// 빈 객체 판단 함수 (수정 모달의 실제 데이터는 유지)
|
||||
const isEmptyRow = (item: any): boolean => {
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load Diff
|
|
@ -6,7 +6,6 @@ import { WebType } from "@/types/common";
|
|||
import { tableTypeApi } from "@/lib/api/screen";
|
||||
import { entityJoinApi } from "@/lib/api/entityJoin";
|
||||
import { codeCache } from "@/lib/caching/codeCache";
|
||||
import { getCategoryLabelsByCodes } from "@/lib/api/tableCategoryValue";
|
||||
import { useEntityJoinOptimization } from "@/lib/hooks/useEntityJoinOptimization";
|
||||
import { getFullImageUrl } from "@/lib/api/client";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
|
@ -67,7 +66,6 @@ import { useAuth } from "@/hooks/useAuth";
|
|||
import { useScreenContextOptional } from "@/contexts/ScreenContext";
|
||||
import { useSplitPanelContext, SplitPanelPosition } from "@/contexts/SplitPanelContext";
|
||||
import type { DataProvidable, DataReceivable, DataReceiverConfig } from "@/types/data-transfer";
|
||||
import { useScreenMultiLang } from "@/contexts/ScreenMultiLangContext";
|
||||
|
||||
// ========================================
|
||||
// 인터페이스
|
||||
|
|
@ -244,11 +242,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
parentTabsComponentId,
|
||||
companyCode,
|
||||
}) => {
|
||||
// ========================================
|
||||
// 다국어 번역 훅
|
||||
// ========================================
|
||||
const { getTranslatedText } = useScreenMultiLang();
|
||||
|
||||
// ========================================
|
||||
// 설정 및 스타일
|
||||
// ========================================
|
||||
|
|
@ -481,7 +474,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
}
|
||||
|
||||
// 2. 헤더 필터 적용 (joinColumnMapping 사용 안 함 - 직접 컬럼명 사용)
|
||||
// 🆕 다중 값 지원: 셀 값이 "A,B,C" 형태일 때, 필터에서 "A"를 선택하면 해당 행도 표시
|
||||
if (Object.keys(headerFilters).length > 0) {
|
||||
result = result.filter((row) => {
|
||||
return Object.entries(headerFilters).every(([columnName, values]) => {
|
||||
|
|
@ -491,16 +483,7 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
const cellValue = row[columnName] ?? row[columnName.toLowerCase()] ?? row[columnName.toUpperCase()];
|
||||
const cellStr = cellValue !== null && cellValue !== undefined ? String(cellValue) : "";
|
||||
|
||||
// 정확히 일치하는 경우
|
||||
if (values.has(cellStr)) return true;
|
||||
|
||||
// 다중 값인 경우: 콤마로 분리해서 하나라도 포함되면 true
|
||||
if (cellStr.includes(",")) {
|
||||
const cellValues = cellStr.split(",").map(v => v.trim());
|
||||
return cellValues.some(v => values.has(v));
|
||||
}
|
||||
|
||||
return false;
|
||||
return values.has(cellStr);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
@ -871,55 +854,17 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
};
|
||||
|
||||
// 화면 컨텍스트에 데이터 제공자/수신자로 등록
|
||||
// 🔧 dataProvider와 dataReceiver를 의존성에 포함하지 않고,
|
||||
// 대신 data와 selectedRows가 변경될 때마다 재등록하여 최신 클로저 참조
|
||||
useEffect(() => {
|
||||
if (screenContext && component.id) {
|
||||
// 🔧 매번 새로운 dataProvider를 등록하여 최신 selectedRows 참조
|
||||
const currentDataProvider: DataProvidable = {
|
||||
componentId: component.id,
|
||||
componentType: "table-list",
|
||||
getSelectedData: () => {
|
||||
const selectedData = filteredData.filter((row) => {
|
||||
const rowId = String(row.id || row[tableConfig.selectedTable + "_id"] || "");
|
||||
return selectedRows.has(rowId);
|
||||
});
|
||||
console.log("📊 [TableList] getSelectedData 호출:", {
|
||||
componentId: component.id,
|
||||
selectedRowsSize: selectedRows.size,
|
||||
filteredDataLength: filteredData.length,
|
||||
resultLength: selectedData.length,
|
||||
});
|
||||
return selectedData;
|
||||
},
|
||||
getAllData: () => filteredData,
|
||||
clearSelection: () => {
|
||||
setSelectedRows(new Set());
|
||||
setIsAllSelected(false);
|
||||
},
|
||||
};
|
||||
|
||||
const currentDataReceiver: DataReceivable = {
|
||||
componentId: component.id,
|
||||
componentType: "table",
|
||||
receiveData: dataReceiver.receiveData,
|
||||
getData: () => data,
|
||||
};
|
||||
|
||||
screenContext.registerDataProvider(component.id, currentDataProvider);
|
||||
screenContext.registerDataReceiver(component.id, currentDataReceiver);
|
||||
|
||||
console.log("✅ [TableList] ScreenContext에 등록:", {
|
||||
componentId: component.id,
|
||||
selectedRowsSize: selectedRows.size,
|
||||
});
|
||||
screenContext.registerDataProvider(component.id, dataProvider);
|
||||
screenContext.registerDataReceiver(component.id, dataReceiver);
|
||||
|
||||
return () => {
|
||||
screenContext.unregisterDataProvider(component.id);
|
||||
screenContext.unregisterDataReceiver(component.id);
|
||||
};
|
||||
}
|
||||
}, [screenContext, component.id, data, selectedRows, filteredData, tableConfig.selectedTable]);
|
||||
}, [screenContext, component.id, data, selectedRows]);
|
||||
|
||||
// 분할 패널 컨텍스트에 데이터 수신자로 등록
|
||||
// useSplitPanelPosition 훅으로 위치 가져오기 (중첩된 화면에서도 작동)
|
||||
|
|
@ -1086,16 +1031,14 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
onGroupSumChange: setGroupSumConfig, // 그룹별 합산 설정
|
||||
// 틀고정 컬럼 관련
|
||||
frozenColumnCount, // 현재 틀고정 컬럼 수
|
||||
onFrozenColumnCountChange: (count: number, updatedColumns?: Array<{ columnName: string; visible: boolean }>) => {
|
||||
onFrozenColumnCountChange: (count: number) => {
|
||||
setFrozenColumnCount(count);
|
||||
// 체크박스 컬럼은 항상 틀고정에 포함
|
||||
const checkboxColumn = (tableConfig.checkbox?.enabled ?? true) ? ["__checkbox__"] : [];
|
||||
// 표시 가능한 컬럼 중 처음 N개를 틀고정 컬럼으로 설정
|
||||
// updatedColumns가 전달되면 그것을 사용, 아니면 columnsToRegister 사용
|
||||
const colsToUse = updatedColumns || columnsToRegister;
|
||||
const visibleCols = colsToUse
|
||||
const visibleCols = columnsToRegister
|
||||
.filter((col) => col.visible !== false)
|
||||
.map((col) => col.columnName || (col as any).field);
|
||||
.map((col) => col.columnName || col.field);
|
||||
const newFrozenColumns = [...checkboxColumn, ...visibleCols.slice(0, count)];
|
||||
setFrozenColumns(newFrozenColumns);
|
||||
},
|
||||
|
|
@ -2106,7 +2049,7 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
return row.id || row.uuid || `row-${index}`;
|
||||
};
|
||||
|
||||
const handleRowSelection = (rowKey: string, checked: boolean, rowData?: any) => {
|
||||
const handleRowSelection = (rowKey: string, checked: boolean) => {
|
||||
const newSelectedRows = new Set(selectedRows);
|
||||
if (checked) {
|
||||
newSelectedRows.add(rowKey);
|
||||
|
|
@ -2149,31 +2092,6 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
});
|
||||
}
|
||||
|
||||
// 🆕 분할 패널 컨텍스트에 선택된 데이터 저장/해제 (체크박스 선택 시에도 작동)
|
||||
const effectiveSplitPosition = splitPanelPosition || currentSplitPosition;
|
||||
if (splitPanelContext && effectiveSplitPosition === "left" && !splitPanelContext.disableAutoDataTransfer) {
|
||||
if (checked && selectedRowsData.length > 0) {
|
||||
// 선택된 경우: 첫 번째 선택된 데이터 저장 (또는 전달된 rowData)
|
||||
const dataToStore = rowData || selectedRowsData[selectedRowsData.length - 1];
|
||||
splitPanelContext.setSelectedLeftData(dataToStore);
|
||||
console.log("🔗 [TableList] handleRowSelection - 분할 패널 좌측 데이터 저장:", {
|
||||
rowKey,
|
||||
dataToStore,
|
||||
});
|
||||
} else if (!checked && selectedRowsData.length === 0) {
|
||||
// 모든 선택이 해제된 경우: 데이터 초기화
|
||||
splitPanelContext.setSelectedLeftData(null);
|
||||
console.log("🔗 [TableList] handleRowSelection - 분할 패널 좌측 데이터 초기화");
|
||||
} else if (selectedRowsData.length > 0) {
|
||||
// 일부 선택 해제된 경우: 남은 첫 번째 데이터로 업데이트
|
||||
splitPanelContext.setSelectedLeftData(selectedRowsData[0]);
|
||||
console.log("🔗 [TableList] handleRowSelection - 분할 패널 좌측 데이터 업데이트:", {
|
||||
remainingCount: selectedRowsData.length,
|
||||
firstData: selectedRowsData[0],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const allRowsSelected = filteredData.every((row, index) => newSelectedRows.has(getRowKey(row, index)));
|
||||
setIsAllSelected(allRowsSelected && filteredData.length > 0);
|
||||
};
|
||||
|
|
@ -2243,8 +2161,35 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
const rowKey = getRowKey(row, index);
|
||||
const isCurrentlySelected = selectedRows.has(rowKey);
|
||||
|
||||
// handleRowSelection에서 분할 패널 데이터 처리도 함께 수행됨
|
||||
handleRowSelection(rowKey, !isCurrentlySelected, row);
|
||||
handleRowSelection(rowKey, !isCurrentlySelected);
|
||||
|
||||
// 🆕 분할 패널 컨텍스트에 선택된 데이터 저장 (좌측 화면인 경우)
|
||||
// disableAutoDataTransfer가 true이면 자동 전달 비활성화 (버튼 클릭으로만 전달)
|
||||
// currentSplitPosition을 사용하여 정확한 위치 확인 (splitPanelPosition이 없을 수 있음)
|
||||
const effectiveSplitPosition = splitPanelPosition || currentSplitPosition;
|
||||
|
||||
console.log("🔗 [TableList] 행 클릭 - 분할 패널 위치 확인:", {
|
||||
splitPanelPosition,
|
||||
currentSplitPosition,
|
||||
effectiveSplitPosition,
|
||||
hasSplitPanelContext: !!splitPanelContext,
|
||||
disableAutoDataTransfer: splitPanelContext?.disableAutoDataTransfer,
|
||||
});
|
||||
|
||||
if (splitPanelContext && effectiveSplitPosition === "left" && !splitPanelContext.disableAutoDataTransfer) {
|
||||
if (!isCurrentlySelected) {
|
||||
// 선택된 경우: 데이터 저장
|
||||
splitPanelContext.setSelectedLeftData(row);
|
||||
console.log("🔗 [TableList] 분할 패널 좌측 데이터 저장:", {
|
||||
row,
|
||||
parentDataMapping: splitPanelContext.parentDataMapping,
|
||||
});
|
||||
} else {
|
||||
// 선택 해제된 경우: 데이터 초기화
|
||||
splitPanelContext.setSelectedLeftData(null);
|
||||
console.log("🔗 [TableList] 분할 패널 좌측 데이터 초기화");
|
||||
}
|
||||
}
|
||||
|
||||
console.log("행 클릭:", { row, index, isSelected: !isCurrentlySelected });
|
||||
};
|
||||
|
|
@ -2311,176 +2256,30 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
// 🆕 편집 모드 진입 placeholder (실제 구현은 visibleColumns 정의 후)
|
||||
const startEditingRef = useRef<() => void>(() => {});
|
||||
|
||||
// 🆕 카테고리 라벨 매핑 (API에서 가져온 것)
|
||||
const [categoryLabelCache, setCategoryLabelCache] = useState<Record<string, string>>({});
|
||||
|
||||
// 🆕 각 컬럼의 고유값 목록 계산 (라벨 포함)
|
||||
// 🆕 각 컬럼의 고유값 목록 계산
|
||||
const columnUniqueValues = useMemo(() => {
|
||||
const result: Record<string, Array<{ value: string; label: string }>> = {};
|
||||
const result: Record<string, string[]> = {};
|
||||
|
||||
if (data.length === 0) return result;
|
||||
|
||||
// 🆕 전체 데이터에서 개별 값 -> 라벨 매핑 테이블 구축 (다중 값 처리용)
|
||||
const globalLabelMap: Record<string, Map<string, string>> = {};
|
||||
|
||||
(tableConfig.columns || []).forEach((column: { columnName: string }) => {
|
||||
if (column.columnName === "__checkbox__") return;
|
||||
|
||||
const mappedColumnName = joinColumnMapping[column.columnName] || column.columnName;
|
||||
// 라벨 컬럼 후보들 (백엔드에서 _name, _label, _value_label 등으로 반환할 수 있음)
|
||||
const labelColumnCandidates = [
|
||||
`${column.columnName}_name`, // 예: division_name
|
||||
`${column.columnName}_label`, // 예: division_label
|
||||
`${column.columnName}_value_label`, // 예: division_value_label
|
||||
];
|
||||
const valuesMap = new Map<string, string>(); // value -> label
|
||||
const singleValueLabelMap = new Map<string, string>(); // 개별 값 -> 라벨 (다중값 처리용)
|
||||
const values = new Set<string>();
|
||||
|
||||
// 1차: 모든 데이터에서 개별 값 -> 라벨 매핑 수집 (단일값 + 다중값 모두)
|
||||
data.forEach((row) => {
|
||||
const val = row[mappedColumnName];
|
||||
if (val !== null && val !== undefined && val !== "") {
|
||||
const valueStr = String(val);
|
||||
|
||||
// 라벨 컬럼에서 라벨 찾기
|
||||
let labelStr = "";
|
||||
for (const labelCol of labelColumnCandidates) {
|
||||
if (row[labelCol] && row[labelCol] !== "") {
|
||||
labelStr = String(row[labelCol]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 단일 값인 경우
|
||||
if (!valueStr.includes(",")) {
|
||||
if (labelStr) {
|
||||
singleValueLabelMap.set(valueStr, labelStr);
|
||||
}
|
||||
} else {
|
||||
// 다중 값인 경우: 값과 라벨을 각각 분리해서 매핑
|
||||
const individualValues = valueStr.split(",").map(v => v.trim());
|
||||
const individualLabels = labelStr ? labelStr.split(",").map(l => l.trim()) : [];
|
||||
|
||||
// 값과 라벨 개수가 같으면 1:1 매핑
|
||||
if (individualValues.length === individualLabels.length) {
|
||||
individualValues.forEach((v, idx) => {
|
||||
if (individualLabels[idx] && !singleValueLabelMap.has(v)) {
|
||||
singleValueLabelMap.set(v, individualLabels[idx]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
values.add(String(val));
|
||||
}
|
||||
});
|
||||
|
||||
// 2차: 모든 값 처리 (다중 값 포함) - 필터 목록용
|
||||
data.forEach((row) => {
|
||||
const val = row[mappedColumnName];
|
||||
if (val !== null && val !== undefined && val !== "") {
|
||||
const valueStr = String(val);
|
||||
|
||||
// 콤마로 구분된 다중 값인지 확인
|
||||
if (valueStr.includes(",")) {
|
||||
// 다중 값: 각각 분리해서 개별 라벨 찾기
|
||||
const individualValues = valueStr.split(",").map(v => v.trim());
|
||||
// 🆕 singleValueLabelMap → categoryLabelCache 순으로 라벨 찾기
|
||||
const individualLabels = individualValues.map(v =>
|
||||
singleValueLabelMap.get(v) || categoryLabelCache[v] || v
|
||||
);
|
||||
valuesMap.set(valueStr, individualLabels.join(", "));
|
||||
} else {
|
||||
// 단일 값: 매핑에서 찾거나 캐시에서 찾거나 원본 사용
|
||||
const label = singleValueLabelMap.get(valueStr) || categoryLabelCache[valueStr] || valueStr;
|
||||
valuesMap.set(valueStr, label);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
globalLabelMap[column.columnName] = singleValueLabelMap;
|
||||
|
||||
// value-label 쌍으로 저장하고 라벨 기준 정렬
|
||||
result[column.columnName] = Array.from(valuesMap.entries())
|
||||
.map(([value, label]) => ({ value, label }))
|
||||
.sort((a, b) => a.label.localeCompare(b.label));
|
||||
result[column.columnName] = Array.from(values).sort();
|
||||
});
|
||||
|
||||
return result;
|
||||
}, [data, tableConfig.columns, joinColumnMapping, categoryLabelCache]);
|
||||
|
||||
// 🆕 라벨을 못 찾은 CATEGORY_ 코드들을 API로 조회
|
||||
useEffect(() => {
|
||||
const unlabeledCodes = new Set<string>();
|
||||
|
||||
// columnUniqueValues에서 라벨이 코드 그대로인 항목 찾기
|
||||
Object.values(columnUniqueValues).forEach(items => {
|
||||
items.forEach(item => {
|
||||
// 라벨에 CATEGORY_가 포함되어 있으면 라벨을 못 찾은 것
|
||||
if (item.label.includes("CATEGORY_")) {
|
||||
// 콤마로 분리해서 개별 코드 추출
|
||||
const codes = item.label.split(",").map(c => c.trim());
|
||||
codes.forEach(code => {
|
||||
if (code.startsWith("CATEGORY_") && !categoryLabelCache[code]) {
|
||||
unlabeledCodes.add(code);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (unlabeledCodes.size === 0) return;
|
||||
|
||||
// API로 라벨 조회
|
||||
const fetchLabels = async () => {
|
||||
try {
|
||||
const response = await getCategoryLabelsByCodes(Array.from(unlabeledCodes));
|
||||
if (response.success && response.data) {
|
||||
setCategoryLabelCache(prev => ({ ...prev, ...response.data }));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("카테고리 라벨 조회 실패:", error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchLabels();
|
||||
}, [columnUniqueValues, categoryLabelCache]);
|
||||
|
||||
// 🆕 데이터에서 CATEGORY_ 코드를 찾아 라벨 미리 로드 (테이블 셀 렌더링용)
|
||||
useEffect(() => {
|
||||
if (data.length === 0) return;
|
||||
|
||||
const categoryCodesToFetch = new Set<string>();
|
||||
|
||||
// 모든 데이터 행에서 CATEGORY_ 코드 수집
|
||||
data.forEach((row) => {
|
||||
Object.entries(row).forEach(([key, value]) => {
|
||||
if (value && typeof value === "string") {
|
||||
// 콤마로 구분된 다중 값도 처리
|
||||
const codes = value.split(",").map((v) => v.trim());
|
||||
codes.forEach((code) => {
|
||||
if (code.startsWith("CATEGORY_") && !categoryLabelCache[code]) {
|
||||
categoryCodesToFetch.add(code);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if (categoryCodesToFetch.size === 0) return;
|
||||
|
||||
// API로 라벨 조회
|
||||
const fetchLabels = async () => {
|
||||
try {
|
||||
const response = await getCategoryLabelsByCodes(Array.from(categoryCodesToFetch));
|
||||
if (response.success && response.data && Object.keys(response.data).length > 0) {
|
||||
setCategoryLabelCache((prev) => ({ ...prev, ...response.data }));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("CATEGORY_ 라벨 조회 실패:", error);
|
||||
}
|
||||
};
|
||||
|
||||
fetchLabels();
|
||||
}, [data, categoryLabelCache]);
|
||||
}, [data, tableConfig.columns, joinColumnMapping]);
|
||||
|
||||
// 🆕 헤더 필터 토글
|
||||
const toggleHeaderFilter = useCallback((columnName: string, value: string) => {
|
||||
|
|
@ -4125,7 +3924,7 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
if (enterRow) {
|
||||
const rowKey = getRowKey(enterRow, rowIndex);
|
||||
const isCurrentlySelected = selectedRows.has(rowKey);
|
||||
handleRowSelection(rowKey, !isCurrentlySelected, enterRow);
|
||||
handleRowSelection(rowKey, !isCurrentlySelected);
|
||||
}
|
||||
break;
|
||||
case " ": // Space
|
||||
|
|
@ -4135,7 +3934,7 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
if (spaceRow) {
|
||||
const currentRowKey = getRowKey(spaceRow, rowIndex);
|
||||
const isChecked = selectedRows.has(currentRowKey);
|
||||
handleRowSelection(currentRowKey, !isChecked, spaceRow);
|
||||
handleRowSelection(currentRowKey, !isChecked);
|
||||
}
|
||||
break;
|
||||
case "F2":
|
||||
|
|
@ -4349,7 +4148,7 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
return (
|
||||
<Checkbox
|
||||
checked={isChecked}
|
||||
onCheckedChange={(checked) => handleRowSelection(rowKey, checked as boolean, row)}
|
||||
onCheckedChange={(checked) => handleRowSelection(rowKey, checked as boolean)}
|
||||
aria-label={`행 ${index + 1} 선택`}
|
||||
/>
|
||||
);
|
||||
|
|
@ -4638,36 +4437,10 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
case "boolean":
|
||||
return value ? "예" : "아니오";
|
||||
default:
|
||||
// 🆕 CATEGORY_ 코드 자동 변환 (inputType이 category가 아니어도)
|
||||
const strValue = String(value);
|
||||
if (strValue.startsWith("CATEGORY_")) {
|
||||
// rowData에서 _label 필드 찾기
|
||||
if (rowData) {
|
||||
const labelFieldCandidates = [
|
||||
`${column.columnName}_label`,
|
||||
`${column.columnName}_name`,
|
||||
`${column.columnName}_value_label`,
|
||||
];
|
||||
for (const labelField of labelFieldCandidates) {
|
||||
if (rowData[labelField] && rowData[labelField] !== "") {
|
||||
return String(rowData[labelField]);
|
||||
}
|
||||
}
|
||||
}
|
||||
// categoryMappings에서 찾기
|
||||
const mapping = categoryMappings[column.columnName];
|
||||
if (mapping && mapping[strValue]) {
|
||||
return mapping[strValue].label;
|
||||
}
|
||||
// categoryLabelCache에서 찾기 (필터용 캐시)
|
||||
if (categoryLabelCache[strValue]) {
|
||||
return categoryLabelCache[strValue];
|
||||
}
|
||||
}
|
||||
return strValue;
|
||||
return String(value);
|
||||
}
|
||||
},
|
||||
[columnMeta, joinedColumnMeta, optimizedConvertCode, categoryMappings, categoryLabelCache],
|
||||
[columnMeta, joinedColumnMeta, optimizedConvertCode, categoryMappings],
|
||||
);
|
||||
|
||||
// ========================================
|
||||
|
|
@ -4806,22 +4579,9 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
});
|
||||
setColumnWidths(newWidths);
|
||||
|
||||
// 틀고정 컬럼 업데이트 (보이는 컬럼 기준으로 처음 N개를 틀고정)
|
||||
// 기존 frozen 개수를 유지하면서, 숨겨진 컬럼을 제외한 보이는 컬럼 중 처음 N개를 틀고정
|
||||
const checkboxColumn = (tableConfig.checkbox?.enabled ?? true) ? ["__checkbox__"] : [];
|
||||
const visibleCols = config.columns
|
||||
.filter((col) => col.visible && col.columnName !== "__checkbox__")
|
||||
.map((col) => col.columnName);
|
||||
|
||||
// 현재 설정된 frozen 컬럼 개수 (체크박스 제외)
|
||||
const currentFrozenCount = config.columns.filter(
|
||||
(col) => col.frozen && col.columnName !== "__checkbox__"
|
||||
).length;
|
||||
|
||||
// 보이는 컬럼 중 처음 currentFrozenCount개를 틀고정으로 설정
|
||||
const newFrozenColumns = [...checkboxColumn, ...visibleCols.slice(0, currentFrozenCount)];
|
||||
// 틀고정 컬럼 업데이트
|
||||
const newFrozenColumns = config.columns.filter((col) => col.frozen).map((col) => col.columnName);
|
||||
setFrozenColumns(newFrozenColumns);
|
||||
setFrozenColumnCount(currentFrozenCount);
|
||||
|
||||
// 그리드선 표시 업데이트
|
||||
setShowGridLines(config.showGridLines);
|
||||
|
|
@ -5865,10 +5625,7 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
rowSpan={2}
|
||||
className="border-primary/10 border-r px-2 py-1 text-center text-xs font-semibold sm:px-4 sm:text-sm"
|
||||
>
|
||||
{/* langKey가 있으면 다국어 번역 사용 */}
|
||||
{(column as any).langKey
|
||||
? getTranslatedText((column as any).langKey, columnLabels[column.columnName] || column.columnName)
|
||||
: columnLabels[column.columnName] || column.columnName}
|
||||
{columnLabels[column.columnName] || column.columnName}
|
||||
</th>
|
||||
);
|
||||
}
|
||||
|
|
@ -5887,18 +5644,13 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
{visibleColumns.map((column, columnIndex) => {
|
||||
const columnWidth = columnWidths[column.columnName];
|
||||
const isFrozen = frozenColumns.includes(column.columnName);
|
||||
|
||||
// 틀고정된 컬럼의 left 위치 계산 (보이는 컬럼 기준으로 계산)
|
||||
// 숨겨진 컬럼은 제외하고 보이는 틀고정 컬럼만 포함
|
||||
const visibleFrozenColumns = visibleColumns
|
||||
.filter(col => frozenColumns.includes(col.columnName))
|
||||
.map(col => col.columnName);
|
||||
const frozenIndex = visibleFrozenColumns.indexOf(column.columnName);
|
||||
|
||||
const frozenIndex = frozenColumns.indexOf(column.columnName);
|
||||
|
||||
// 틀고정된 컬럼의 left 위치 계산
|
||||
let leftPosition = 0;
|
||||
if (isFrozen && frozenIndex > 0) {
|
||||
for (let i = 0; i < frozenIndex; i++) {
|
||||
const frozenCol = visibleFrozenColumns[i];
|
||||
const frozenCol = frozenColumns[i];
|
||||
// 체크박스 컬럼은 48px 고정
|
||||
const frozenColWidth = frozenCol === "__checkbox__" ? 48 : columnWidths[frozenCol] || 150;
|
||||
leftPosition += frozenColWidth;
|
||||
|
|
@ -5964,12 +5716,7 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
<Lock className="text-muted-foreground h-3 w-3" />
|
||||
</span>
|
||||
)}
|
||||
<span>
|
||||
{/* langKey가 있으면 다국어 번역 사용 */}
|
||||
{(column as any).langKey
|
||||
? getTranslatedText((column as any).langKey, columnLabels[column.columnName] || column.displayName || column.columnName)
|
||||
: columnLabels[column.columnName] || column.displayName}
|
||||
</span>
|
||||
<span>{columnLabels[column.columnName] || column.displayName}</span>
|
||||
{column.sortable !== false && sortColumn === column.columnName && (
|
||||
<span>{sortDirection === "asc" ? "↑" : "↓"}</span>
|
||||
)}
|
||||
|
|
@ -6017,16 +5764,16 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
)}
|
||||
</div>
|
||||
<div className="max-h-48 space-y-1 overflow-y-auto">
|
||||
{columnUniqueValues[column.columnName]?.slice(0, 50).map((item) => {
|
||||
const isSelected = headerFilters[column.columnName]?.has(item.value);
|
||||
{columnUniqueValues[column.columnName]?.slice(0, 50).map((val) => {
|
||||
const isSelected = headerFilters[column.columnName]?.has(val);
|
||||
return (
|
||||
<div
|
||||
key={item.value}
|
||||
key={val}
|
||||
className={cn(
|
||||
"hover:bg-muted flex cursor-pointer items-center gap-2 rounded px-2 py-1 text-xs",
|
||||
isSelected && "bg-primary/10",
|
||||
)}
|
||||
onClick={() => toggleHeaderFilter(column.columnName, item.value)}
|
||||
onClick={() => toggleHeaderFilter(column.columnName, val)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
|
|
@ -6036,7 +5783,7 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
>
|
||||
{isSelected && <Check className="text-primary-foreground h-3 w-3" />}
|
||||
</div>
|
||||
<span className="truncate">{item.label || "(빈 값)"}</span>
|
||||
<span className="truncate">{val || "(빈 값)"}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
|
@ -6209,17 +5956,13 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
const isNumeric = inputType === "number" || inputType === "decimal";
|
||||
|
||||
const isFrozen = frozenColumns.includes(column.columnName);
|
||||
|
||||
// 틀고정된 컬럼의 left 위치 계산 (보이는 컬럼 기준으로 계산)
|
||||
const visibleFrozenColumns = visibleColumns
|
||||
.filter(col => frozenColumns.includes(col.columnName))
|
||||
.map(col => col.columnName);
|
||||
const frozenIndex = visibleFrozenColumns.indexOf(column.columnName);
|
||||
const frozenIndex = frozenColumns.indexOf(column.columnName);
|
||||
|
||||
// 틀고정된 컬럼의 left 위치 계산
|
||||
let leftPosition = 0;
|
||||
if (isFrozen && frozenIndex > 0) {
|
||||
for (let i = 0; i < frozenIndex; i++) {
|
||||
const frozenCol = visibleFrozenColumns[i];
|
||||
const frozenCol = frozenColumns[i];
|
||||
// 체크박스 컬럼은 48px 고정
|
||||
const frozenColWidth =
|
||||
frozenCol === "__checkbox__" ? 48 : columnWidths[frozenCol] || 150;
|
||||
|
|
@ -6366,12 +6109,7 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
const isNumeric = inputType === "number" || inputType === "decimal";
|
||||
|
||||
const isFrozen = frozenColumns.includes(column.columnName);
|
||||
|
||||
// 틀고정된 컬럼의 left 위치 계산 (보이는 컬럼 기준으로 계산)
|
||||
const visibleFrozenColumns = visibleColumns
|
||||
.filter(col => frozenColumns.includes(col.columnName))
|
||||
.map(col => col.columnName);
|
||||
const frozenIndex = visibleFrozenColumns.indexOf(column.columnName);
|
||||
const frozenIndex = frozenColumns.indexOf(column.columnName);
|
||||
|
||||
// 셀 포커스 상태
|
||||
const isCellFocused = focusedCell?.rowIndex === index && focusedCell?.colIndex === colIndex;
|
||||
|
|
@ -6385,10 +6123,11 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
// 🆕 검색 하이라이트 여부
|
||||
const isSearchHighlighted = searchHighlights.has(`${index}-${colIndex}`);
|
||||
|
||||
// 틀고정된 컬럼의 left 위치 계산
|
||||
let leftPosition = 0;
|
||||
if (isFrozen && frozenIndex > 0) {
|
||||
for (let i = 0; i < frozenIndex; i++) {
|
||||
const frozenCol = visibleFrozenColumns[i];
|
||||
const frozenCol = frozenColumns[i];
|
||||
// 체크박스 컬럼은 48px 고정
|
||||
const frozenColWidth =
|
||||
frozenCol === "__checkbox__" ? 48 : columnWidths[frozenCol] || 150;
|
||||
|
|
@ -6548,17 +6287,13 @@ export const TableListComponent: React.FC<TableListComponentProps> = ({
|
|||
const summary = summaryData[column.columnName];
|
||||
const columnWidth = columnWidths[column.columnName];
|
||||
const isFrozen = frozenColumns.includes(column.columnName);
|
||||
|
||||
// 틀고정된 컬럼의 left 위치 계산 (보이는 컬럼 기준으로 계산)
|
||||
const visibleFrozenColumns = visibleColumns
|
||||
.filter(col => frozenColumns.includes(col.columnName))
|
||||
.map(col => col.columnName);
|
||||
const frozenIndex = visibleFrozenColumns.indexOf(column.columnName);
|
||||
const frozenIndex = frozenColumns.indexOf(column.columnName);
|
||||
|
||||
// 틀고정된 컬럼의 left 위치 계산
|
||||
let leftPosition = 0;
|
||||
if (isFrozen && frozenIndex > 0) {
|
||||
for (let i = 0; i < frozenIndex; i++) {
|
||||
const frozenCol = visibleFrozenColumns[i];
|
||||
const frozenCol = frozenColumns[i];
|
||||
// 체크박스 컬럼은 48px 고정
|
||||
const frozenColWidth = frozenCol === "__checkbox__" ? 48 : columnWidths[frozenCol] || 150;
|
||||
leftPosition += frozenColWidth;
|
||||
|
|
|
|||
|
|
@ -708,6 +708,47 @@ export class ButtonActionExecutor {
|
|||
if (repeaterJsonKeys.length > 0) {
|
||||
console.log("🔄 [handleSave] RepeaterFieldGroup JSON 문자열 감지:", repeaterJsonKeys);
|
||||
|
||||
// 🎯 채번 규칙 할당 처리 (RepeaterFieldGroup 저장 전에 실행)
|
||||
console.log("🔍 [handleSave-RepeaterFieldGroup] 채번 규칙 할당 체크 시작");
|
||||
|
||||
const fieldsWithNumberingRepeater: Record<string, string> = {};
|
||||
|
||||
// formData에서 채번 규칙이 설정된 필드 찾기
|
||||
for (const [key, value] of Object.entries(context.formData)) {
|
||||
if (key.endsWith("_numberingRuleId") && value) {
|
||||
const fieldName = key.replace("_numberingRuleId", "");
|
||||
fieldsWithNumberingRepeater[fieldName] = value as string;
|
||||
console.log(`🎯 [handleSave-RepeaterFieldGroup] 채번 필드 발견: ${fieldName} → 규칙 ${value}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log("📋 [handleSave-RepeaterFieldGroup] 채번 규칙이 설정된 필드:", fieldsWithNumberingRepeater);
|
||||
|
||||
// 채번 규칙이 있는 필드에 대해 allocateCode 호출
|
||||
if (Object.keys(fieldsWithNumberingRepeater).length > 0) {
|
||||
console.log("🎯 [handleSave-RepeaterFieldGroup] 채번 규칙 할당 시작 (allocateCode 호출)");
|
||||
const { allocateNumberingCode } = await import("@/lib/api/numberingRule");
|
||||
|
||||
for (const [fieldName, ruleId] of Object.entries(fieldsWithNumberingRepeater)) {
|
||||
try {
|
||||
console.log(`🔄 [handleSave-RepeaterFieldGroup] ${fieldName} 필드에 대해 allocateCode 호출: ${ruleId}`);
|
||||
const allocateResult = await allocateNumberingCode(ruleId);
|
||||
|
||||
if (allocateResult.success && allocateResult.data?.generatedCode) {
|
||||
const newCode = allocateResult.data.generatedCode;
|
||||
console.log(`✅ [handleSave-RepeaterFieldGroup] ${fieldName} 새 코드 할당: ${context.formData[fieldName]} → ${newCode}`);
|
||||
context.formData[fieldName] = newCode;
|
||||
} else {
|
||||
console.warn(`⚠️ [handleSave-RepeaterFieldGroup] ${fieldName} 코드 할당 실패:`, allocateResult.error);
|
||||
}
|
||||
} catch (allocateError) {
|
||||
console.error(`❌ [handleSave-RepeaterFieldGroup] ${fieldName} 코드 할당 오류:`, allocateError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log("✅ [handleSave-RepeaterFieldGroup] 채번 규칙 할당 완료");
|
||||
|
||||
// 🆕 상단 폼 데이터(마스터 정보) 추출
|
||||
// RepeaterFieldGroup JSON과 컴포넌트 키를 제외한 나머지가 마스터 정보
|
||||
const masterFields: Record<string, any> = {};
|
||||
|
|
|
|||
Loading…
Reference in New Issue