From 4f6d9a689d62d734fe62f58c544da5fc14e24fd4 Mon Sep 17 00:00:00 2001 From: kjs Date: Tue, 24 Feb 2026 12:37:33 +0900 Subject: [PATCH] feat: Implement process work standard routes and controller - Added a new controller for managing process work standards, including CRUD operations for work items and routing processes. - Introduced routes for fetching items with routing, retrieving routings with processes, and managing work items. - Integrated the new process work standard routes into the main application file for API accessibility. - Created a migration script for exporting data related to the new process work standard feature. - Updated frontend components to support the new process work standard functionality, enhancing the overall user experience. --- backend-node/src/app.ts | 2 + .../processWorkStandardController.ts | 573 ++++++++++++++++++ .../src/routes/processWorkStandardRoutes.ts | 29 + db/migrate_company13_export.sh | 149 +++++ docker/deploy/docker-compose.yml | 2 +- docs/formdata-console-log-test-guide.md | 78 +++ frontend/components/common/ScreenModal.tsx | 15 +- frontend/lib/registry/components/index.ts | 1 + .../SplitPanelLayoutComponent.tsx | 51 ++ .../ButtonPrimaryComponent.tsx | 9 + .../ProcessWorkStandardComponent.tsx | 241 ++++++++ .../ProcessWorkStandardConfigPanel.tsx | 282 +++++++++ .../ProcessWorkStandardRenderer.tsx | 32 + .../components/ItemProcessSelector.tsx | 167 +++++ .../components/WorkItemAddModal.tsx | 337 ++++++++++ .../components/WorkItemCard.tsx | 88 +++ .../components/WorkItemDetailList.tsx | 380 ++++++++++++ .../components/WorkPhaseSection.tsx | 123 ++++ .../v2-process-work-standard/config.ts | 33 + .../hooks/useProcessWorkStandard.ts | 336 ++++++++++ .../v2-process-work-standard/index.ts | 59 ++ .../v2-process-work-standard/types.ts | 111 ++++ .../lib/utils/getComponentConfigPanel.tsx | 1 + frontend/package-lock.json | 48 ++ frontend/package.json | 1 + frontend/scripts/test-formdata-logs.ts | 135 +++++ 26 files changed, 3279 insertions(+), 4 deletions(-) create mode 100644 backend-node/src/controllers/processWorkStandardController.ts create mode 100644 backend-node/src/routes/processWorkStandardRoutes.ts create mode 100755 db/migrate_company13_export.sh create mode 100644 docs/formdata-console-log-test-guide.md create mode 100644 frontend/lib/registry/components/v2-process-work-standard/ProcessWorkStandardComponent.tsx create mode 100644 frontend/lib/registry/components/v2-process-work-standard/ProcessWorkStandardConfigPanel.tsx create mode 100644 frontend/lib/registry/components/v2-process-work-standard/ProcessWorkStandardRenderer.tsx create mode 100644 frontend/lib/registry/components/v2-process-work-standard/components/ItemProcessSelector.tsx create mode 100644 frontend/lib/registry/components/v2-process-work-standard/components/WorkItemAddModal.tsx create mode 100644 frontend/lib/registry/components/v2-process-work-standard/components/WorkItemCard.tsx create mode 100644 frontend/lib/registry/components/v2-process-work-standard/components/WorkItemDetailList.tsx create mode 100644 frontend/lib/registry/components/v2-process-work-standard/components/WorkPhaseSection.tsx create mode 100644 frontend/lib/registry/components/v2-process-work-standard/config.ts create mode 100644 frontend/lib/registry/components/v2-process-work-standard/hooks/useProcessWorkStandard.ts create mode 100644 frontend/lib/registry/components/v2-process-work-standard/index.ts create mode 100644 frontend/lib/registry/components/v2-process-work-standard/types.ts create mode 100644 frontend/scripts/test-formdata-logs.ts diff --git a/backend-node/src/app.ts b/backend-node/src/app.ts index 30e684d5..e454742a 100644 --- a/backend-node/src/app.ts +++ b/backend-node/src/app.ts @@ -123,6 +123,7 @@ import cascadingMutualExclusionRoutes from "./routes/cascadingMutualExclusionRou import cascadingHierarchyRoutes from "./routes/cascadingHierarchyRoutes"; // 다단계 계층 관리 import categoryValueCascadingRoutes from "./routes/categoryValueCascadingRoutes"; // 카테고리 값 연쇄관계 import categoryTreeRoutes from "./routes/categoryTreeRoutes"; // 카테고리 트리 (테스트) +import processWorkStandardRoutes from "./routes/processWorkStandardRoutes"; // 공정 작업기준 import { BatchSchedulerService } from "./services/batchSchedulerService"; // import collectionRoutes from "./routes/collectionRoutes"; // 임시 주석 // import batchRoutes from "./routes/batchRoutes"; // 임시 주석 @@ -304,6 +305,7 @@ app.use("/api/cascading-exclusions", cascadingMutualExclusionRoutes); // 상호 app.use("/api/cascading-hierarchy", cascadingHierarchyRoutes); // 다단계 계층 관리 app.use("/api/category-value-cascading", categoryValueCascadingRoutes); // 카테고리 값 연쇄관계 app.use("/api/category-tree", categoryTreeRoutes); // 카테고리 트리 (테스트) +app.use("/api/process-work-standard", processWorkStandardRoutes); // 공정 작업기준 app.use("/api", screenEmbeddingRoutes); // 화면 임베딩 및 데이터 전달 app.use("/api/vehicle", vehicleTripRoutes); // 차량 운행 이력 관리 // app.use("/api/collections", collectionRoutes); // 임시 주석 diff --git a/backend-node/src/controllers/processWorkStandardController.ts b/backend-node/src/controllers/processWorkStandardController.ts new file mode 100644 index 00000000..6b663e2b --- /dev/null +++ b/backend-node/src/controllers/processWorkStandardController.ts @@ -0,0 +1,573 @@ +/** + * 공정 작업기준 컨트롤러 + * 품목별 라우팅/공정에 대한 작업 항목 및 상세 관리 + */ + +import { Request, Response } from "express"; +import { getPool } from "../database/db"; +import { logger } from "../utils/logger"; + +// ============================================================ +// 품목/라우팅/공정 조회 (좌측 트리 데이터) +// ============================================================ + +/** + * 라우팅이 있는 품목 목록 조회 + * 요청 쿼리: tableName(품목테이블), nameColumn, codeColumn + */ +export async function getItemsWithRouting(req: Request, res: Response) { + try { + const companyCode = req.user?.companyCode; + if (!companyCode) { + return res.status(401).json({ success: false, message: "인증 필요" }); + } + + const { + tableName = "item_info", + nameColumn = "item_name", + codeColumn = "item_number", + routingTable = "item_routing_version", + routingFkColumn = "item_code", + search = "", + } = req.query as Record; + + const searchCondition = search + ? `AND (i.${nameColumn} ILIKE $2 OR i.${codeColumn} ILIKE $2)` + : ""; + const params: any[] = [companyCode]; + if (search) params.push(`%${search}%`); + + const query = ` + SELECT DISTINCT + i.id, + i.${nameColumn} AS item_name, + i.${codeColumn} AS item_code + FROM ${tableName} i + INNER JOIN ${routingTable} rv ON rv.${routingFkColumn} = i.${codeColumn} + AND rv.company_code = i.company_code + WHERE i.company_code = $1 + ${searchCondition} + ORDER BY i.${codeColumn} + `; + + const result = await getPool().query(query, params); + + return res.json({ success: true, data: result.rows }); + } catch (error: any) { + logger.error("품목 목록 조회 실패", { error: error.message }); + return res.status(500).json({ success: false, message: error.message }); + } +} + +/** + * 품목별 라우팅 버전 + 공정 목록 조회 (트리 하위 데이터) + */ +export async function getRoutingsWithProcesses(req: Request, res: Response) { + try { + const companyCode = req.user?.companyCode; + if (!companyCode) { + return res.status(401).json({ success: false, message: "인증 필요" }); + } + + const { itemCode } = req.params; + const { + routingVersionTable = "item_routing_version", + routingDetailTable = "item_routing_detail", + routingFkColumn = "item_code", + processTable = "process_mng", + processNameColumn = "process_name", + processCodeColumn = "process_code", + } = req.query as Record; + + // 라우팅 버전 목록 + const versionsQuery = ` + SELECT id, version_name, description, created_date + FROM ${routingVersionTable} + WHERE ${routingFkColumn} = $1 AND company_code = $2 + ORDER BY created_date DESC + `; + const versionsResult = await getPool().query(versionsQuery, [ + itemCode, + companyCode, + ]); + + // 각 버전별 공정 목록 + const routings = []; + for (const version of versionsResult.rows) { + const detailsQuery = ` + SELECT + rd.id AS routing_detail_id, + rd.seq_no, + rd.process_code, + rd.is_required, + rd.work_type, + p.${processNameColumn} AS process_name + FROM ${routingDetailTable} rd + LEFT JOIN ${processTable} p ON p.${processCodeColumn} = rd.process_code + AND p.company_code = rd.company_code + WHERE rd.routing_version_id = $1 AND rd.company_code = $2 + ORDER BY rd.seq_no::integer + `; + const detailsResult = await getPool().query(detailsQuery, [ + version.id, + companyCode, + ]); + + routings.push({ + ...version, + processes: detailsResult.rows, + }); + } + + return res.json({ success: true, data: routings }); + } catch (error: any) { + logger.error("라우팅/공정 조회 실패", { error: error.message }); + return res.status(500).json({ success: false, message: error.message }); + } +} + +// ============================================================ +// 작업 항목 CRUD +// ============================================================ + +/** + * 공정별 작업 항목 목록 조회 (phase별 그룹) + */ +export async function getWorkItems(req: Request, res: Response) { + try { + const companyCode = req.user?.companyCode; + if (!companyCode) { + return res.status(401).json({ success: false, message: "인증 필요" }); + } + + const { routingDetailId } = req.params; + + const query = ` + SELECT + wi.id, + wi.routing_detail_id, + wi.work_phase, + wi.title, + wi.is_required, + wi.sort_order, + wi.description, + wi.created_date, + (SELECT COUNT(*) FROM process_work_item_detail d + WHERE d.work_item_id = wi.id AND d.company_code = wi.company_code + )::integer AS detail_count + FROM process_work_item wi + WHERE wi.routing_detail_id = $1 AND wi.company_code = $2 + ORDER BY wi.work_phase, wi.sort_order, wi.created_date + `; + + const result = await getPool().query(query, [routingDetailId, companyCode]); + + // phase별 그룹핑 + const grouped: Record = {}; + for (const row of result.rows) { + const phase = row.work_phase; + if (!grouped[phase]) grouped[phase] = []; + grouped[phase].push(row); + } + + return res.json({ success: true, data: grouped, items: result.rows }); + } catch (error: any) { + logger.error("작업 항목 조회 실패", { error: error.message }); + return res.status(500).json({ success: false, message: error.message }); + } +} + +/** + * 작업 항목 추가 + */ +export async function createWorkItem(req: Request, res: Response) { + try { + const companyCode = req.user?.companyCode; + const writer = req.user?.userId; + if (!companyCode) { + return res.status(401).json({ success: false, message: "인증 필요" }); + } + + const { routing_detail_id, work_phase, title, is_required, sort_order, description } = req.body; + + if (!routing_detail_id || !work_phase || !title) { + return res.status(400).json({ + success: false, + message: "routing_detail_id, work_phase, title은 필수입니다", + }); + } + + const query = ` + INSERT INTO process_work_item + (company_code, routing_detail_id, work_phase, title, is_required, sort_order, description, writer) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + RETURNING * + `; + + const result = await getPool().query(query, [ + companyCode, + routing_detail_id, + work_phase, + title, + is_required || "N", + sort_order || 0, + description || null, + writer, + ]); + + logger.info("작업 항목 생성", { companyCode, id: result.rows[0].id }); + return res.json({ success: true, data: result.rows[0] }); + } catch (error: any) { + logger.error("작업 항목 생성 실패", { error: error.message }); + return res.status(500).json({ success: false, message: error.message }); + } +} + +/** + * 작업 항목 수정 + */ +export async function updateWorkItem(req: Request, res: Response) { + try { + const companyCode = req.user?.companyCode; + if (!companyCode) { + return res.status(401).json({ success: false, message: "인증 필요" }); + } + + const { id } = req.params; + const { title, is_required, sort_order, description } = req.body; + + const query = ` + UPDATE process_work_item + SET title = COALESCE($1, title), + is_required = COALESCE($2, is_required), + sort_order = COALESCE($3, sort_order), + description = COALESCE($4, description), + updated_date = NOW() + WHERE id = $5 AND company_code = $6 + RETURNING * + `; + + const result = await getPool().query(query, [ + title, + is_required, + sort_order, + description, + id, + companyCode, + ]); + + if (result.rowCount === 0) { + return res.status(404).json({ success: false, message: "항목을 찾을 수 없습니다" }); + } + + logger.info("작업 항목 수정", { companyCode, id }); + return res.json({ success: true, data: result.rows[0] }); + } catch (error: any) { + logger.error("작업 항목 수정 실패", { error: error.message }); + return res.status(500).json({ success: false, message: error.message }); + } +} + +/** + * 작업 항목 삭제 (상세도 함께 삭제) + */ +export async function deleteWorkItem(req: Request, res: Response) { + const client = await getPool().connect(); + try { + const companyCode = req.user?.companyCode; + if (!companyCode) { + return res.status(401).json({ success: false, message: "인증 필요" }); + } + + const { id } = req.params; + + await client.query("BEGIN"); + + // 상세 먼저 삭제 + await client.query( + "DELETE FROM process_work_item_detail WHERE work_item_id = $1 AND company_code = $2", + [id, companyCode] + ); + + // 항목 삭제 + const result = await client.query( + "DELETE FROM process_work_item WHERE id = $1 AND company_code = $2 RETURNING id", + [id, companyCode] + ); + + if (result.rowCount === 0) { + await client.query("ROLLBACK"); + return res.status(404).json({ success: false, message: "항목을 찾을 수 없습니다" }); + } + + await client.query("COMMIT"); + logger.info("작업 항목 삭제", { companyCode, id }); + return res.json({ success: true }); + } catch (error: any) { + await client.query("ROLLBACK"); + logger.error("작업 항목 삭제 실패", { error: error.message }); + return res.status(500).json({ success: false, message: error.message }); + } finally { + client.release(); + } +} + +// ============================================================ +// 작업 항목 상세 CRUD +// ============================================================ + +/** + * 작업 항목 상세 목록 조회 + */ +export async function getWorkItemDetails(req: Request, res: Response) { + try { + const companyCode = req.user?.companyCode; + if (!companyCode) { + return res.status(401).json({ success: false, message: "인증 필요" }); + } + + const { workItemId } = req.params; + + const query = ` + SELECT id, work_item_id, detail_type, content, is_required, sort_order, remark, created_date + FROM process_work_item_detail + WHERE work_item_id = $1 AND company_code = $2 + ORDER BY sort_order, created_date + `; + + const result = await getPool().query(query, [workItemId, companyCode]); + return res.json({ success: true, data: result.rows }); + } catch (error: any) { + logger.error("작업 항목 상세 조회 실패", { error: error.message }); + return res.status(500).json({ success: false, message: error.message }); + } +} + +/** + * 작업 항목 상세 추가 + */ +export async function createWorkItemDetail(req: Request, res: Response) { + try { + const companyCode = req.user?.companyCode; + const writer = req.user?.userId; + if (!companyCode) { + return res.status(401).json({ success: false, message: "인증 필요" }); + } + + const { work_item_id, detail_type, content, is_required, sort_order, remark } = req.body; + + if (!work_item_id || !content) { + return res.status(400).json({ + success: false, + message: "work_item_id, content는 필수입니다", + }); + } + + // work_item이 같은 company_code인지 검증 + const ownerCheck = await getPool().query( + "SELECT id FROM process_work_item WHERE id = $1 AND company_code = $2", + [work_item_id, companyCode] + ); + if (ownerCheck.rowCount === 0) { + return res.status(403).json({ success: false, message: "권한이 없습니다" }); + } + + const query = ` + INSERT INTO process_work_item_detail + (company_code, work_item_id, detail_type, content, is_required, sort_order, remark, writer) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + RETURNING * + `; + + const result = await getPool().query(query, [ + companyCode, + work_item_id, + detail_type || null, + content, + is_required || "N", + sort_order || 0, + remark || null, + writer, + ]); + + logger.info("작업 항목 상세 생성", { companyCode, id: result.rows[0].id }); + return res.json({ success: true, data: result.rows[0] }); + } catch (error: any) { + logger.error("작업 항목 상세 생성 실패", { error: error.message }); + return res.status(500).json({ success: false, message: error.message }); + } +} + +/** + * 작업 항목 상세 수정 + */ +export async function updateWorkItemDetail(req: Request, res: Response) { + try { + const companyCode = req.user?.companyCode; + if (!companyCode) { + return res.status(401).json({ success: false, message: "인증 필요" }); + } + + const { id } = req.params; + const { detail_type, content, is_required, sort_order, remark } = req.body; + + const query = ` + UPDATE process_work_item_detail + SET detail_type = COALESCE($1, detail_type), + content = COALESCE($2, content), + is_required = COALESCE($3, is_required), + sort_order = COALESCE($4, sort_order), + remark = COALESCE($5, remark), + updated_date = NOW() + WHERE id = $6 AND company_code = $7 + RETURNING * + `; + + const result = await getPool().query(query, [ + detail_type, + content, + is_required, + sort_order, + remark, + id, + companyCode, + ]); + + if (result.rowCount === 0) { + return res.status(404).json({ success: false, message: "상세를 찾을 수 없습니다" }); + } + + logger.info("작업 항목 상세 수정", { companyCode, id }); + return res.json({ success: true, data: result.rows[0] }); + } catch (error: any) { + logger.error("작업 항목 상세 수정 실패", { error: error.message }); + return res.status(500).json({ success: false, message: error.message }); + } +} + +/** + * 작업 항목 상세 삭제 + */ +export async function deleteWorkItemDetail(req: Request, res: Response) { + try { + const companyCode = req.user?.companyCode; + if (!companyCode) { + return res.status(401).json({ success: false, message: "인증 필요" }); + } + + const { id } = req.params; + + const result = await getPool().query( + "DELETE FROM process_work_item_detail WHERE id = $1 AND company_code = $2 RETURNING id", + [id, companyCode] + ); + + if (result.rowCount === 0) { + return res.status(404).json({ success: false, message: "상세를 찾을 수 없습니다" }); + } + + logger.info("작업 항목 상세 삭제", { companyCode, id }); + return res.json({ success: true }); + } catch (error: any) { + logger.error("작업 항목 상세 삭제 실패", { error: error.message }); + return res.status(500).json({ success: false, message: error.message }); + } +} + +// ============================================================ +// 전체 저장 (일괄) +// ============================================================ + +/** + * 전체 저장: 작업 항목 + 상세를 일괄 저장 + * 기존 데이터를 삭제하고 새로 삽입하는 replace 방식 + */ +export async function saveAll(req: Request, res: Response) { + const client = await getPool().connect(); + try { + const companyCode = req.user?.companyCode; + const writer = req.user?.userId; + if (!companyCode) { + return res.status(401).json({ success: false, message: "인증 필요" }); + } + + const { routing_detail_id, items } = req.body; + + if (!routing_detail_id || !Array.isArray(items)) { + return res.status(400).json({ + success: false, + message: "routing_detail_id와 items 배열이 필요합니다", + }); + } + + await client.query("BEGIN"); + + // 기존 상세 삭제 + await client.query( + `DELETE FROM process_work_item_detail + WHERE work_item_id IN ( + SELECT id FROM process_work_item + WHERE routing_detail_id = $1 AND company_code = $2 + )`, + [routing_detail_id, companyCode] + ); + + // 기존 항목 삭제 + await client.query( + "DELETE FROM process_work_item WHERE routing_detail_id = $1 AND company_code = $2", + [routing_detail_id, companyCode] + ); + + // 새 항목 + 상세 삽입 + for (const item of items) { + const itemResult = await client.query( + `INSERT INTO process_work_item + (company_code, routing_detail_id, work_phase, title, is_required, sort_order, description, writer) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + RETURNING id`, + [ + companyCode, + routing_detail_id, + item.work_phase, + item.title, + item.is_required || "N", + item.sort_order || 0, + item.description || null, + writer, + ] + ); + + const workItemId = itemResult.rows[0].id; + + if (Array.isArray(item.details)) { + for (const detail of item.details) { + await client.query( + `INSERT INTO process_work_item_detail + (company_code, work_item_id, detail_type, content, is_required, sort_order, remark, writer) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`, + [ + companyCode, + workItemId, + detail.detail_type || null, + detail.content, + detail.is_required || "N", + detail.sort_order || 0, + detail.remark || null, + writer, + ] + ); + } + } + } + + await client.query("COMMIT"); + logger.info("작업기준 전체 저장", { companyCode, routing_detail_id, itemCount: items.length }); + return res.json({ success: true, message: "저장 완료" }); + } catch (error: any) { + await client.query("ROLLBACK"); + logger.error("작업기준 전체 저장 실패", { error: error.message }); + return res.status(500).json({ success: false, message: error.message }); + } finally { + client.release(); + } +} diff --git a/backend-node/src/routes/processWorkStandardRoutes.ts b/backend-node/src/routes/processWorkStandardRoutes.ts new file mode 100644 index 00000000..087f08c0 --- /dev/null +++ b/backend-node/src/routes/processWorkStandardRoutes.ts @@ -0,0 +1,29 @@ +/** + * 공정 작업기준 라우트 + */ + +import express from "express"; +import * as ctrl from "../controllers/processWorkStandardController"; + +const router = express.Router(); + +// 품목/라우팅/공정 조회 (좌측 트리) +router.get("/items", ctrl.getItemsWithRouting); +router.get("/items/:itemCode/routings", ctrl.getRoutingsWithProcesses); + +// 작업 항목 CRUD +router.get("/routing-detail/:routingDetailId/work-items", ctrl.getWorkItems); +router.post("/work-items", ctrl.createWorkItem); +router.put("/work-items/:id", ctrl.updateWorkItem); +router.delete("/work-items/:id", ctrl.deleteWorkItem); + +// 작업 항목 상세 CRUD +router.get("/work-items/:workItemId/details", ctrl.getWorkItemDetails); +router.post("/work-item-details", ctrl.createWorkItemDetail); +router.put("/work-item-details/:id", ctrl.updateWorkItemDetail); +router.delete("/work-item-details/:id", ctrl.deleteWorkItemDetail); + +// 전체 저장 (일괄) +router.put("/save-all", ctrl.saveAll); + +export default router; diff --git a/db/migrate_company13_export.sh b/db/migrate_company13_export.sh new file mode 100755 index 00000000..fc96f04a --- /dev/null +++ b/db/migrate_company13_export.sh @@ -0,0 +1,149 @@ +#!/bin/bash +# ============================================================ +# 엘에스티라유텍(주) - 동부지사 (COMPANY_13) 전체 데이터 Export +# +# 사용법: +# 1. SOURCE_* / TARGET_* 변수를 수정 +# 2. chmod +x migrate_company13_export.sh +# 3. ./migrate_company13_export.sh export → SQL 파일 생성 +# 4. ./migrate_company13_export.sh import → 대상 DB에 적재 +# ============================================================ + +SOURCE_HOST="localhost" +SOURCE_PORT="5432" +SOURCE_DB="vexplor" +SOURCE_USER="postgres" + +TARGET_HOST="대상_호스트" +TARGET_PORT="5432" +TARGET_DB="대상_DB명" +TARGET_USER="postgres" + +OUTPUT_FILE="company13_migration_$(date '+%Y%m%d_%H%M%S').sql" + +# 데이터가 있는 테이블 (의존성 순서) +TABLES=( + "company_mng" + "user_info" + "authority_master" + "menu_info" + "external_db_connections" + "external_rest_api_connections" + "screen_definitions" + "screen_groups" + "screen_layouts_v1" + "screen_layouts_v2" + "screen_layouts_v3" + "screen_menu_assignments" + "dashboards" + "dashboard_elements" + "flow_definition" + "node_flows" + "table_column_category_values" + "attach_file_info" + "tax_invoice" + "auth_tokens" + "batch_configs" + "batch_execution_logs" + "batch_mappings" + "digital_twin_layout" + "digital_twin_layout_template" + "dtg_management" + "transport_statistics" + "vehicles" + "vehicle_location_history" +) + +do_export() { + echo "==========================================" + echo " COMPANY_13 데이터 Export 시작" + echo "==========================================" + + cat > "$OUTPUT_FILE" <<'HEADER' +-- ============================================================ +-- 엘에스티라유텍(주) - 동부지사 (COMPANY_13) 전체 데이터 마이그레이션 +-- +-- 총 29개 테이블, 약 11,500건 데이터 +-- +-- 실행 방법: +-- psql -h HOST -U USER -d DATABASE -f 이_파일명.sql +-- ============================================================ + +SET client_encoding TO 'UTF8'; +SET standard_conforming_strings = on; + +BEGIN; + +HEADER + + for TABLE in "${TABLES[@]}"; do + COUNT=$(psql -h "$SOURCE_HOST" -p "$SOURCE_PORT" -U "$SOURCE_USER" -d "$SOURCE_DB" \ + -t -A -c "SELECT COUNT(*) FROM $TABLE WHERE company_code = 'COMPANY_13'") + COUNT=$(echo "$COUNT" | tr -d '[:space:]') + + if [ "$COUNT" -gt 0 ]; then + echo " $TABLE: ${COUNT}건 추출 중..." + + echo "-- ----------------------------------------" >> "$OUTPUT_FILE" + echo "-- $TABLE (${COUNT}건)" >> "$OUTPUT_FILE" + echo "-- ----------------------------------------" >> "$OUTPUT_FILE" + echo "COPY $TABLE FROM stdin;" >> "$OUTPUT_FILE" + + psql -h "$SOURCE_HOST" -p "$SOURCE_PORT" -U "$SOURCE_USER" -d "$SOURCE_DB" \ + -t -A -c "COPY (SELECT * FROM $TABLE WHERE company_code = 'COMPANY_13') TO STDOUT" >> "$OUTPUT_FILE" + + echo "\\." >> "$OUTPUT_FILE" + echo "" >> "$OUTPUT_FILE" + else + echo " $TABLE: 데이터 없음 (건너뜀)" + fi + done + + echo "" >> "$OUTPUT_FILE" + echo "COMMIT;" >> "$OUTPUT_FILE" + echo "" >> "$OUTPUT_FILE" + echo "-- 마이그레이션 완료" >> "$OUTPUT_FILE" + + echo "" + echo "==========================================" + echo " Export 완료: $OUTPUT_FILE" + echo "==========================================" + echo "" + echo "대상 DB에서 실행:" + echo " psql -h $TARGET_HOST -p $TARGET_PORT -U $TARGET_USER -d $TARGET_DB -f $OUTPUT_FILE" +} + +do_import() { + SQL_FILE=$(ls -t company13_migration_*.sql 2>/dev/null | head -1) + + if [ -z "$SQL_FILE" ]; then + echo "마이그레이션 SQL 파일을 찾을 수 없습니다. 먼저 export를 실행하세요." + exit 1 + fi + + echo "==========================================" + echo " COMPANY_13 데이터 Import 시작" + echo " 파일: $SQL_FILE" + echo " 대상: $TARGET_HOST:$TARGET_PORT/$TARGET_DB" + echo "==========================================" + + psql -h "$TARGET_HOST" -p "$TARGET_PORT" -U "$TARGET_USER" -d "$TARGET_DB" -f "$SQL_FILE" + + echo "" + echo "==========================================" + echo " Import 완료" + echo "==========================================" +} + +case "${1:-export}" in + export) + do_export + ;; + import) + do_import + ;; + *) + echo "사용법: $0 {export|import}" + exit 1 + ;; +esac diff --git a/docker/deploy/docker-compose.yml b/docker/deploy/docker-compose.yml index b3cc4996..efd1b961 100644 --- a/docker/deploy/docker-compose.yml +++ b/docker/deploy/docker-compose.yml @@ -12,7 +12,7 @@ services: NODE_ENV: production PORT: "3001" HOST: 0.0.0.0 - DATABASE_URL: postgresql://postgres:vexplor0909!!@211.115.91.141:11134/plm + DATABASE_URL: postgresql://postgres:vexplor0909!!@211.115.91.141:11134/vexplor JWT_SECRET: ilshin-plm-super-secret-jwt-key-2024 JWT_EXPIRES_IN: 24h CORS_ORIGIN: https://v1.vexplor.com,https://api.vexplor.com diff --git a/docs/formdata-console-log-test-guide.md b/docs/formdata-console-log-test-guide.md new file mode 100644 index 00000000..81a47486 --- /dev/null +++ b/docs/formdata-console-log-test-guide.md @@ -0,0 +1,78 @@ +# formData 콘솔 로그 수동 테스트 가이드 + +## 테스트 시나리오 + +1. http://localhost:9771/screens/1599?menuObjid=1762422235300 접속 +2. 로그인 필요 시: `topseal_admin` / `1234` +3. 5초 대기 (페이지 로드) +4. 첫 번째 탭 "공정 마스터" 확인 +5. 좌측 패널에서 **P003** 행 클릭 +6. 우측 패널에서 **추가** 버튼 클릭 +7. 모달에서 설비(equipment) 드롭다운에서 항목 선택 +8. **저장** 버튼 클릭 **전** 콘솔 스냅샷 확인 +9. **저장** 버튼 클릭 **후** 콘솔 로그 확인 + +## 확인할 콘솔 로그 + +### 1. ADD 모드 formData 설정 (ScreenModal) + +``` +🔵 [ScreenModal] ADD모드 formData 설정: {...} +``` + +- **위치**: `frontend/components/common/ScreenModal.tsx` 358행 +- **의미**: 모달이 ADD 모드로 열릴 때 부모 데이터(splitPanelParentData)로 설정된 초기 formData +- **확인**: `process_code`가 P003으로 포함되어 있는지 + +### 2. formData 변경 시 (ScreenModal) + +``` +🟡 [ScreenModal] onFormDataChange: equipment_code → E001 | formData keys: [...] | process_code: P003 +``` + +- **위치**: `frontend/components/common/ScreenModal.tsx` 1184행 +- **의미**: 사용자가 설비를 선택할 때마다 발생 +- **확인**: `process_code`가 유지되는지, `equipment_code`가 추가되는지 + +### 3. 저장 시 formData 디버그 (ButtonPrimary) + +``` +🔴 [ButtonPrimary] 저장 시 formData 디버그: { + propsFormDataKeys: [...], + screenContextFormDataKeys: [...], + effectiveFormDataKeys: [...], + process_code: "P003", + equipment_code: "E001", + fullData: "{...}" +} +``` + +- **위치**: `frontend/lib/registry/components/v2-button-primary/ButtonPrimaryComponent.tsx` 1110행 +- **의미**: 저장 버튼 클릭 시 실제로 API에 전달되는 formData +- **확인**: `process_code`, `equipment_code`가 모두 포함되어 있는지 + +## 추가로 확인할 로그 + +- `process_code` 포함 로그 +- `splitPanelParentData` 포함 로그 +- `🆕 [추가모달] screenId 기반 모달 열기:` (SplitPanelLayoutComponent 1639행) + +## 에러 확인 + +콘솔에 빨간색으로 표시되는 에러 메시지가 있는지 확인하세요. + +## 사전 조건 + +- **process_mng** 테이블에 P003 데이터가 있어야 함 (company_code = 로그인 사용자 회사) +- **equipment_mng** 테이블에 설비 데이터가 있어야 함 +- 로그인 사용자가 해당 회사(COMPANY_7 등) 권한이 있어야 함 + +## 자동 테스트 스크립트 + +데이터가 준비된 환경에서: + +```bash +cd frontend && npx tsx scripts/test-formdata-logs.ts +``` + +데이터가 없으면 "좌측 테이블에 데이터가 없습니다" 오류가 발생합니다. diff --git a/frontend/components/common/ScreenModal.tsx b/frontend/components/common/ScreenModal.tsx index b6660709..86348d23 100644 --- a/frontend/components/common/ScreenModal.tsx +++ b/frontend/components/common/ScreenModal.tsx @@ -178,10 +178,17 @@ export const ScreenModal: React.FC = ({ className }) => { splitPanelParentData, selectedData: eventSelectedData, selectedIds, - isCreateMode, // 🆕 복사 모드 플래그 (true면 editData가 있어도 originalData 설정 안 함) - fieldMappings, // 🆕 필드 매핑 정보 (명시적 매핑이 있으면 모든 매핑된 필드 전달) + isCreateMode, + fieldMappings, } = event.detail; + console.log("🟣 [ScreenModal] openScreenModal 이벤트 수신:", { + screenId, + splitPanelParentData: JSON.stringify(splitPanelParentData), + editData: !!editData, + isCreateMode, + }); + // 🆕 모달 열린 시간 기록 modalOpenedAtRef.current = Date.now(); @@ -355,8 +362,10 @@ export const ScreenModal: React.FC = ({ className }) => { } if (Object.keys(parentData).length > 0) { + console.log("🔵 [ScreenModal] ADD모드 formData 설정:", JSON.stringify(parentData)); setFormData(parentData); } else { + console.log("🔵 [ScreenModal] ADD모드 formData 비어있음"); setFormData({}); } setOriginalData(null); // 신규 등록 모드 @@ -1173,13 +1182,13 @@ export const ScreenModal: React.FC = ({ className }) => { formData={formData} originalData={originalData} // 🆕 원본 데이터 전달 (UPDATE 판단용) onFormDataChange={(fieldName, value) => { - // 사용자가 실제로 데이터를 변경한 것으로 표시 formDataChangedRef.current = true; setFormData((prev) => { const newFormData = { ...prev, [fieldName]: value, }; + console.log("🟡 [ScreenModal] onFormDataChange:", fieldName, "→", value, "| formData keys:", Object.keys(newFormData), "| process_code:", newFormData.process_code); return newFormData; }); }} diff --git a/frontend/lib/registry/components/index.ts b/frontend/lib/registry/components/index.ts index 172f0067..910f3a0b 100644 --- a/frontend/lib/registry/components/index.ts +++ b/frontend/lib/registry/components/index.ts @@ -112,6 +112,7 @@ import "./v2-input/V2InputRenderer"; // V2 통합 입력 컴포넌트 import "./v2-select/V2SelectRenderer"; // V2 통합 선택 컴포넌트 import "./v2-date/V2DateRenderer"; // V2 통합 날짜 컴포넌트 import "./v2-file-upload/V2FileUploadRenderer"; // V2 파일 업로드 컴포넌트 +import "./v2-process-work-standard/ProcessWorkStandardRenderer"; // 공정 작업기준 /** * 컴포넌트 초기화 함수 diff --git a/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutComponent.tsx b/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutComponent.tsx index 6264a757..e94b6cce 100644 --- a/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutComponent.tsx +++ b/frontend/lib/registry/components/split-panel-layout/SplitPanelLayoutComponent.tsx @@ -1603,6 +1603,57 @@ export const SplitPanelLayoutComponent: React.FC const handleAddClick = useCallback( (panel: "left" | "right") => { console.log("🆕 [추가모달] handleAddClick 호출:", { panel, activeTabIndex }); + + // screenId 기반 모달 확인 + const panelConfig = panel === "left" ? componentConfig.leftPanel : componentConfig.rightPanel; + const addModalConfig = panelConfig?.addModal; + + if (addModalConfig?.screenId) { + if (panel === "right" && !selectedLeftItem) { + toast({ + title: "항목을 선택해주세요", + description: "좌측 패널에서 항목을 먼저 선택한 후 추가해주세요.", + variant: "destructive", + }); + return; + } + + const tableName = panelConfig?.tableName || ""; + const urlParams: Record = { + mode: "add", + tableName, + }; + + const parentData: Record = {}; + if (panel === "right" && selectedLeftItem) { + const relation = componentConfig.rightPanel?.relation; + console.log("🟢 [추가모달] selectedLeftItem:", JSON.stringify(selectedLeftItem)); + console.log("🟢 [추가모달] relation:", JSON.stringify(relation)); + if (relation?.keys && Array.isArray(relation.keys)) { + for (const key of relation.keys) { + console.log("🟢 [추가모달] key:", key, "leftValue:", selectedLeftItem[key.leftColumn]); + if (key.leftColumn && key.rightColumn && selectedLeftItem[key.leftColumn] != null) { + parentData[key.rightColumn] = selectedLeftItem[key.leftColumn]; + } + } + } + } + + console.log("🆕 [추가모달] screenId 기반 모달 열기:", { screenId: addModalConfig.screenId, tableName, parentData, parentDataStr: JSON.stringify(parentData) }); + + window.dispatchEvent( + new CustomEvent("openScreenModal", { + detail: { + screenId: addModalConfig.screenId, + urlParams, + splitPanelParentData: parentData, + }, + }), + ); + return; + } + + // 기존 인라인 모달 방식 setAddModalPanel(panel); // 우측 패널 추가 시, 좌측에서 선택된 항목의 조인 컬럼 값을 자동으로 채움 diff --git a/frontend/lib/registry/components/v2-button-primary/ButtonPrimaryComponent.tsx b/frontend/lib/registry/components/v2-button-primary/ButtonPrimaryComponent.tsx index 5516a4bf..01461660 100644 --- a/frontend/lib/registry/components/v2-button-primary/ButtonPrimaryComponent.tsx +++ b/frontend/lib/registry/components/v2-button-primary/ButtonPrimaryComponent.tsx @@ -1107,6 +1107,15 @@ export const ButtonPrimaryComponent: React.FC = ({ effectiveFormData = { ...splitPanelParentData }; } + console.log("🔴 [ButtonPrimary] 저장 시 formData 디버그:", { + propsFormDataKeys: Object.keys(propsFormData), + screenContextFormDataKeys: Object.keys(screenContextFormData), + effectiveFormDataKeys: Object.keys(effectiveFormData), + process_code: effectiveFormData.process_code, + equipment_code: effectiveFormData.equipment_code, + fullData: JSON.stringify(effectiveFormData), + }); + const context: ButtonActionContext = { formData: effectiveFormData, originalData: originalData, // 🔧 빈 객체 대신 undefined 유지 (UPDATE 판단에 사용) diff --git a/frontend/lib/registry/components/v2-process-work-standard/ProcessWorkStandardComponent.tsx b/frontend/lib/registry/components/v2-process-work-standard/ProcessWorkStandardComponent.tsx new file mode 100644 index 00000000..c859f108 --- /dev/null +++ b/frontend/lib/registry/components/v2-process-work-standard/ProcessWorkStandardComponent.tsx @@ -0,0 +1,241 @@ +"use client"; + +import React, { useState, useMemo, useCallback } from "react"; +import { Save, Loader2, ClipboardCheck } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Badge } from "@/components/ui/badge"; +import { cn } from "@/lib/utils"; +import { ProcessWorkStandardConfig, WorkItem } from "./types"; +import { defaultConfig } from "./config"; +import { useProcessWorkStandard } from "./hooks/useProcessWorkStandard"; +import { ItemProcessSelector } from "./components/ItemProcessSelector"; +import { WorkPhaseSection } from "./components/WorkPhaseSection"; +import { WorkItemAddModal } from "./components/WorkItemAddModal"; + +interface ProcessWorkStandardComponentProps { + config?: Partial; + formData?: Record; + isPreview?: boolean; + tableName?: string; +} + +export function ProcessWorkStandardComponent({ + config: configProp, + isPreview, +}: ProcessWorkStandardComponentProps) { + const config: ProcessWorkStandardConfig = useMemo( + () => ({ + ...defaultConfig, + ...configProp, + dataSource: { ...defaultConfig.dataSource, ...configProp?.dataSource }, + phases: configProp?.phases?.length + ? configProp.phases + : defaultConfig.phases, + detailTypes: configProp?.detailTypes?.length + ? configProp.detailTypes + : defaultConfig.detailTypes, + }), + [configProp] + ); + + const { + items, + routings, + workItems, + selectedWorkItemDetails, + selectedWorkItemId, + selection, + loading, + fetchItems, + selectItem, + selectProcess, + fetchWorkItemDetails, + createWorkItem, + updateWorkItem, + deleteWorkItem, + createDetail, + updateDetail, + deleteDetail, + } = useProcessWorkStandard(config); + + // 모달 상태 + const [modalOpen, setModalOpen] = useState(false); + const [modalPhaseKey, setModalPhaseKey] = useState(""); + const [editingItem, setEditingItem] = useState(null); + + // phase별 작업 항목 그룹핑 + const workItemsByPhase = useMemo(() => { + const map: Record = {}; + for (const phase of config.phases) { + map[phase.key] = workItems.filter((wi) => wi.work_phase === phase.key); + } + return map; + }, [workItems, config.phases]); + + const sortedPhases = useMemo( + () => [...config.phases].sort((a, b) => a.sortOrder - b.sortOrder), + [config.phases] + ); + + const handleAddWorkItem = useCallback((phaseKey: string) => { + setModalPhaseKey(phaseKey); + setEditingItem(null); + setModalOpen(true); + }, []); + + const handleEditWorkItem = useCallback((item: WorkItem) => { + setModalPhaseKey(item.work_phase); + setEditingItem(item); + setModalOpen(true); + }, []); + + const handleModalSave = useCallback( + async (data: Parameters[0]) => { + if (editingItem) { + await updateWorkItem(editingItem.id, { + title: data.title, + is_required: data.is_required, + description: data.description, + } as any); + } else { + await createWorkItem(data); + } + }, + [editingItem, createWorkItem, updateWorkItem] + ); + + const handleSelectWorkItem = useCallback( + (workItemId: string) => { + fetchWorkItemDetails(workItemId); + }, + [fetchWorkItemDetails] + ); + + const handleInit = useCallback(() => { + fetchItems(); + }, [fetchItems]); + + const splitRatio = config.splitRatio || 30; + + if (isPreview) { + return ( +
+
+ +

+ 공정 작업기준 +

+

+ {sortedPhases.map((p) => p.label).join(" / ")} +

+
+
+ ); + } + + return ( +
+ {/* 메인 콘텐츠 */} +
+ {/* 좌측 패널 */} +
+ fetchItems(keyword)} + onSelectItem={selectItem} + onSelectProcess={selectProcess} + onInit={handleInit} + /> +
+ + {/* 우측 패널 */} +
+ {/* 우측 헤더 */} + {selection.routingDetailId ? ( + <> +
+
+

+ {selection.itemName} - {selection.processName} +

+
+ 품목: {selection.itemCode} + 공정: {selection.processName} + 버전: {selection.routingVersionName} +
+
+ {!config.readonly && ( + + )} +
+ + {/* 작업 단계별 섹션 */} +
+ {sortedPhases.map((phase) => ( + + ))} +
+ + ) : ( +
+ +

+ 좌측에서 품목과 공정을 선택하세요 +

+

+ 품목을 펼쳐 라우팅별 공정을 선택하면 작업기준을 관리할 수 + 있습니다 +

+
+ )} +
+
+ + {/* 작업 항목 추가/수정 모달 */} + { + setModalOpen(false); + setEditingItem(null); + }} + onSave={handleModalSave} + phaseKey={modalPhaseKey} + phaseLabel={ + config.phases.find((p) => p.key === modalPhaseKey)?.label || "" + } + detailTypes={config.detailTypes} + editItem={editingItem} + /> +
+ ); +} diff --git a/frontend/lib/registry/components/v2-process-work-standard/ProcessWorkStandardConfigPanel.tsx b/frontend/lib/registry/components/v2-process-work-standard/ProcessWorkStandardConfigPanel.tsx new file mode 100644 index 00000000..21a5d69f --- /dev/null +++ b/frontend/lib/registry/components/v2-process-work-standard/ProcessWorkStandardConfigPanel.tsx @@ -0,0 +1,282 @@ +"use client"; + +import React from "react"; +import { Plus, Trash2, GripVertical } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Switch } from "@/components/ui/switch"; +import { ProcessWorkStandardConfig, WorkPhaseDefinition, DetailTypeDefinition } from "./types"; +import { defaultConfig } from "./config"; + +interface ConfigPanelProps { + config: Partial; + onChange: (config: Partial) => void; +} + +export function ProcessWorkStandardConfigPanel({ + config: configProp, + onChange, +}: ConfigPanelProps) { + const config: ProcessWorkStandardConfig = { + ...defaultConfig, + ...configProp, + dataSource: { ...defaultConfig.dataSource, ...configProp?.dataSource }, + phases: configProp?.phases?.length ? configProp.phases : defaultConfig.phases, + detailTypes: configProp?.detailTypes?.length ? configProp.detailTypes : defaultConfig.detailTypes, + }; + + const update = (partial: Partial) => { + onChange({ ...configProp, ...partial }); + }; + + const updateDataSource = (field: string, value: string) => { + update({ + dataSource: { ...config.dataSource, [field]: value }, + }); + }; + + // 작업 단계 관리 + const addPhase = () => { + const nextOrder = config.phases.length + 1; + update({ + phases: [ + ...config.phases, + { key: `PHASE_${nextOrder}`, label: `단계 ${nextOrder}`, sortOrder: nextOrder }, + ], + }); + }; + + const removePhase = (idx: number) => { + update({ phases: config.phases.filter((_, i) => i !== idx) }); + }; + + const updatePhase = (idx: number, field: keyof WorkPhaseDefinition, value: string | number) => { + const next = [...config.phases]; + next[idx] = { ...next[idx], [field]: value }; + update({ phases: next }); + }; + + // 상세 유형 관리 + const addDetailType = () => { + update({ + detailTypes: [ + ...config.detailTypes, + { value: `TYPE_${config.detailTypes.length + 1}`, label: "신규 유형" }, + ], + }); + }; + + const removeDetailType = (idx: number) => { + update({ detailTypes: config.detailTypes.filter((_, i) => i !== idx) }); + }; + + const updateDetailType = (idx: number, field: keyof DetailTypeDefinition, value: string) => { + const next = [...config.detailTypes]; + next[idx] = { ...next[idx], [field]: value }; + update({ detailTypes: next }); + }; + + return ( +
+

공정 작업기준 설정

+ + {/* 데이터 소스 설정 */} +
+

데이터 소스 설정

+ +
+ + updateDataSource("itemTable", e.target.value)} + className="mt-1 h-8 text-xs" + /> +
+
+
+ + updateDataSource("itemNameColumn", e.target.value)} + className="mt-1 h-8 text-xs" + /> +
+
+ + updateDataSource("itemCodeColumn", e.target.value)} + className="mt-1 h-8 text-xs" + /> +
+
+ +
+ + updateDataSource("routingVersionTable", e.target.value)} + className="mt-1 h-8 text-xs" + /> +
+
+ + updateDataSource("routingFkColumn", e.target.value)} + className="mt-1 h-8 text-xs" + /> +
+ +
+ + updateDataSource("processTable", e.target.value)} + className="mt-1 h-8 text-xs" + /> +
+
+
+ + updateDataSource("processNameColumn", e.target.value)} + className="mt-1 h-8 text-xs" + /> +
+
+ + updateDataSource("processCodeColumn", e.target.value)} + className="mt-1 h-8 text-xs" + /> +
+
+
+ + {/* 작업 단계 설정 */} +
+
+

작업 단계 설정

+ +
+ +
+ {config.phases.map((phase, idx) => ( +
+ + updatePhase(idx, "key", e.target.value)} + className="h-7 w-20 text-[10px]" + placeholder="키" + /> + updatePhase(idx, "label", e.target.value)} + className="h-7 flex-1 text-[10px]" + placeholder="표시명" + /> + +
+ ))} +
+
+ + {/* 상세 유형 옵션 */} +
+
+

상세 유형 옵션

+ +
+ +
+ {config.detailTypes.map((dt, idx) => ( +
+ updateDetailType(idx, "value", e.target.value)} + className="h-7 w-24 text-[10px]" + placeholder="값" + /> + updateDetailType(idx, "label", e.target.value)} + className="h-7 flex-1 text-[10px]" + placeholder="표시명" + /> + +
+ ))} +
+
+ + {/* UI 설정 */} +
+

UI 설정

+ +
+ + update({ splitRatio: Number(e.target.value) })} + min={15} + max={50} + className="mt-1 h-8 w-20 text-xs" + /> +
+ +
+ + update({ leftPanelTitle: e.target.value })} + className="mt-1 h-8 text-xs" + /> +
+ +
+ update({ readonly: v })} + /> + +
+
+
+ ); +} diff --git a/frontend/lib/registry/components/v2-process-work-standard/ProcessWorkStandardRenderer.tsx b/frontend/lib/registry/components/v2-process-work-standard/ProcessWorkStandardRenderer.tsx new file mode 100644 index 00000000..cb1e0e85 --- /dev/null +++ b/frontend/lib/registry/components/v2-process-work-standard/ProcessWorkStandardRenderer.tsx @@ -0,0 +1,32 @@ +"use client"; + +import React from "react"; +import { AutoRegisteringComponentRenderer } from "../../AutoRegisteringComponentRenderer"; +import { V2ProcessWorkStandardDefinition } from "./index"; +import { ProcessWorkStandardComponent } from "./ProcessWorkStandardComponent"; + +export class ProcessWorkStandardRenderer extends AutoRegisteringComponentRenderer { + static componentDefinition = V2ProcessWorkStandardDefinition; + + render(): React.ReactElement { + const { formData, isPreview, config, tableName } = this.props as Record< + string, + unknown + >; + + return ( + } + tableName={tableName as string} + isPreview={isPreview as boolean} + /> + ); + } +} + +ProcessWorkStandardRenderer.registerSelf(); + +if (process.env.NODE_ENV === "development") { + ProcessWorkStandardRenderer.enableHotReload(); +} diff --git a/frontend/lib/registry/components/v2-process-work-standard/components/ItemProcessSelector.tsx b/frontend/lib/registry/components/v2-process-work-standard/components/ItemProcessSelector.tsx new file mode 100644 index 00000000..59ea4f71 --- /dev/null +++ b/frontend/lib/registry/components/v2-process-work-standard/components/ItemProcessSelector.tsx @@ -0,0 +1,167 @@ +"use client"; + +import React, { useEffect, useState } from "react"; +import { Search, ChevronDown, ChevronRight, Package, GitBranch, Settings2, Star } from "lucide-react"; +import { Input } from "@/components/ui/input"; +import { cn } from "@/lib/utils"; +import { ItemData, RoutingVersion, SelectionState } from "../types"; + +interface ItemProcessSelectorProps { + title: string; + items: ItemData[]; + routings: RoutingVersion[]; + selection: SelectionState; + onSearch: (keyword: string) => void; + onSelectItem: (itemCode: string, itemName: string) => void; + onSelectProcess: ( + routingDetailId: string, + processName: string, + routingVersionId: string, + routingVersionName: string + ) => void; + onInit: () => void; +} + +export function ItemProcessSelector({ + title, + items, + routings, + selection, + onSearch, + onSelectItem, + onSelectProcess, + onInit, +}: ItemProcessSelectorProps) { + const [searchKeyword, setSearchKeyword] = useState(""); + const [expandedItems, setExpandedItems] = useState>(new Set()); + + useEffect(() => { + onInit(); + }, [onInit]); + + const handleSearch = (value: string) => { + setSearchKeyword(value); + onSearch(value); + }; + + const toggleItem = (itemCode: string, itemName: string) => { + const next = new Set(expandedItems); + if (next.has(itemCode)) { + next.delete(itemCode); + } else { + next.add(itemCode); + onSelectItem(itemCode, itemName); + } + setExpandedItems(next); + }; + + const isItemExpanded = (itemCode: string) => expandedItems.has(itemCode); + + return ( +
+ {/* 헤더 */} +
+
+ + {title} +
+
+ + handleSearch(e.target.value)} + className="h-8 pl-8 text-xs" + /> +
+
+ + {/* 트리 목록 */} +
+ {items.length === 0 ? ( +
+ +

+ 라우팅이 등록된 품목이 없습니다 +

+
+ ) : ( + items.map((item) => ( +
+ {/* 품목 헤더 */} + + + {/* 라우팅 + 공정 */} + {isItemExpanded(item.item_code) && + selection.itemCode === item.item_code && ( +
+ {routings.length === 0 ? ( +

+ 등록된 공정이 없습니다 +

+ ) : ( + routings.map((routing) => ( +
+ {/* 라우팅 버전 */} +
+ + + {routing.version_name || "기본 라우팅"} + +
+ + {/* 공정 목록 */} + {routing.processes.map((proc) => ( + + ))} +
+ )) + )} +
+ )} +
+ )) + )} +
+
+ ); +} diff --git a/frontend/lib/registry/components/v2-process-work-standard/components/WorkItemAddModal.tsx b/frontend/lib/registry/components/v2-process-work-standard/components/WorkItemAddModal.tsx new file mode 100644 index 00000000..6a907f58 --- /dev/null +++ b/frontend/lib/registry/components/v2-process-work-standard/components/WorkItemAddModal.tsx @@ -0,0 +1,337 @@ +"use client"; + +import React, { useState } from "react"; +import { Plus, Trash2 } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Textarea } from "@/components/ui/textarea"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { DetailTypeDefinition, WorkItem } from "../types"; + +interface ModalDetail { + id: string; + detail_type: string; + content: string; + is_required: string; + sort_order: number; +} + +interface WorkItemAddModalProps { + open: boolean; + onClose: () => void; + onSave: (data: { + work_phase: string; + title: string; + is_required: string; + description?: string; + details?: Array<{ + detail_type?: string; + content: string; + is_required: string; + sort_order: number; + }>; + }) => void; + phaseKey: string; + phaseLabel: string; + detailTypes: DetailTypeDefinition[]; + editItem?: WorkItem | null; +} + +export function WorkItemAddModal({ + open, + onClose, + onSave, + phaseKey, + phaseLabel, + detailTypes, + editItem, +}: WorkItemAddModalProps) { + const [title, setTitle] = useState(editItem?.title || ""); + const [isRequired, setIsRequired] = useState(editItem?.is_required || "Y"); + const [description, setDescription] = useState(editItem?.description || ""); + const [details, setDetails] = useState([]); + + const resetForm = () => { + setTitle(""); + setIsRequired("Y"); + setDescription(""); + setDetails([]); + }; + + const handleSave = () => { + if (!title.trim()) return; + onSave({ + work_phase: phaseKey, + title: title.trim(), + is_required: isRequired, + description: description.trim() || undefined, + details: details + .filter((d) => d.content.trim()) + .map((d, idx) => ({ + detail_type: d.detail_type || undefined, + content: d.content.trim(), + is_required: d.is_required, + sort_order: idx + 1, + })), + }); + resetForm(); + onClose(); + }; + + const addDetail = () => { + setDetails((prev) => [ + ...prev, + { + id: crypto.randomUUID(), + detail_type: detailTypes[0]?.value || "", + content: "", + is_required: "N", + sort_order: prev.length + 1, + }, + ]); + }; + + const removeDetail = (id: string) => { + setDetails((prev) => prev.filter((d) => d.id !== id)); + }; + + const updateDetailField = ( + id: string, + field: keyof ModalDetail, + value: string | number + ) => { + setDetails((prev) => + prev.map((d) => (d.id === id ? { ...d, [field]: value } : d)) + ); + }; + + return ( + { + if (!v) { + resetForm(); + onClose(); + } + }} + > + + + + 작업 항목 {editItem ? "수정" : "추가"} + + + {phaseLabel} 단계에 {editItem ? "항목을 수정" : "새 항목을 추가"}합니다. + + + +
+ {/* 기본 정보 */} +
+

+ 기본 정보 +

+
+
+ + setTitle(e.target.value)} + placeholder="예: 장비 점검, 품질 검사" + className="mt-1 h-8 text-xs sm:h-10 sm:text-sm" + /> +
+
+ + +
+
+
+ +