feat(WEB): 절곡 중간검사 성적서 DATA 테이블 레거시 PHP 동기화

- TemplateInspectionContent에 bending DATA 렌더링 추가
  - 제품별(가이드레일/하단마감재/케이스/연기차단재) 다중 POINT 행 확장
  - 간격 외 컬럼(분류, 타입, 절곡상태, 길이, 너비, 판정) rowSpan 병합
  - DEFAULT_GAP_PROFILES 상수로 제품별 간격 도면치수 정의
  - bending_info JSON에서 제품 목록 동적 생성 (buildBendingProducts)
- InspectionReportModal에서 node_groups 기반 개소 단위 변환 추가
  - buildFromReportData()로 node_groups → WorkItemData[] 매핑
- 다단계 헤더(group_name "/" 구분자), check 라벨, POINT sub_label 지원
This commit is contained in:
2026-02-21 16:27:35 +09:00
parent b5f5ce591f
commit 80ed9803be
4 changed files with 612 additions and 948 deletions

View File

@@ -103,3 +103,7 @@ default_modes:
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
# This cannot be combined with non-empty excluded_tools or included_optional_tools.
fixed_tools: []
# override of the corresponding setting in serena_config.yml, see the documentation there.
# If null or missing, the value from the global config is used.
symbol_info_budget:

View File

@@ -1,85 +1,24 @@
# SAM React 작업 현황
## 2026-02-19 (수) - 작업일지/작업자화면 슬랫 데이터 파이프라인 연동
## 🔄 진행 중 - 절곡 작업일지 실 데이터 테스트
### 커밋 내역
- `59b9b1b` feat(WEB): 절곡 작업일지 완전 재구현 + 슬랫 입고 LOT NO 개소별 표시 수정
- `827069d` fix(WEB): SlatExtraInfo undefined 방어 처리
- `769019a` fix(WEB): 작업일지 담당자 정보 및 슬랫 데이터 파이프라인 연동
- `0112cd5` fix(WEB): 수주/작업지시 담당자 표시 누락 수정
### 수정된 파일
| 파일명 | 설명 |
|--------|------|
| `src/components/production/WorkOrders/types.ts` | slatInfo에 glassQty 추가, material_inputs/bendingInfo/materialInputLots 추가 |
| `src/components/production/WorkOrders/documents/SlatWorkLogContent.tsx` | 방화유리 수량 연동, 입고 LOT NO 개소별 표시 수정 |
| `src/components/production/WorkOrders/documents/BendingWorkLogContent.tsx` | PHP 기준 4개 카테고리 섹션 완전 재구현 |
| `src/components/production/WorkerScreen/types.ts` | SlatInfo에 glassQty 추가 |
| `src/components/production/WorkerScreen/actions.ts` | slat_info 변환에 glass_qty 추가 |
| `src/components/production/WorkerScreen/index.tsx` | slat_info 매핑 업데이트 |
| `src/components/production/WorkerScreen/WorkItemCard.tsx` | SlatExtraInfo optional props + 조건부 렌더링 |
| `src/components/production/WorkerScreen/mockData.ts` | glassQty 추가 |
### 추가된 파일
| 파일명 | 설명 |
|--------|------|
| `src/components/production/WorkOrders/documents/bending/types.ts` | 절곡 타입 정의 (12개 인터페이스) |
| `src/components/production/WorkOrders/documents/bending/utils.ts` | 무게 계산, 재질 매핑, 행 빌더 등 11개 유틸 |
| `src/components/production/WorkOrders/documents/bending/GuideRailSection.tsx` | 가이드레일 섹션 (벽면형/측면형) |
| `src/components/production/WorkOrders/documents/bending/BottomBarSection.tsx` | 하단마감재 섹션 |
| `src/components/production/WorkOrders/documents/bending/ShutterBoxSection.tsx` | 셔터박스 섹션 (양면/밑면/후면) |
| `src/components/production/WorkOrders/documents/bending/SmokeBarrierSection.tsx` | 연기차단재 섹션 (W50/W80) |
| `src/components/production/WorkOrders/documents/bending/ProductionSummarySection.tsx` | 생산량 합계 (SUS/EGI) |
### 상태: 🔄 진행 중
- ✅ 작업일지 방화유리 수량 연동
- ✅ 작업자화면 슬랫 정보 표시
- ✅ SlatExtraInfo undefined 방어 처리
- ✅ 절곡 작업일지 PHP 기준 완전 재구현 (4개 카테고리 섹션)
- ✅ 슬랫 작업일지 입고 LOT NO 개소별 표시 수정
- ✅ 견적 화면에서 조인트바 BOM 표시 확인 완료
- ⬜ 절곡 실 데이터 테스트 (bending_info 채워진 작업지시로 확인)
### 관련 API 커밋
- `23029b1` (api) fix: 작업지시 단건조회(show)에 materialInputs eager loading 추가
### 관련 문서
- `docs/plans/bending-worklog-reimplementation-plan.md` (✅ 완료)
### 최근 커밋
- `59b9b1b` (2026-02-19) feat(WEB): 절곡 작업일지 완전 재구현 + 슬랫 입고 LOT NO 개소별 표시 수정
---
## 2026-01-09 (목) - Phase L 건설관리 Mock → API 연동 (3개 모듈) ✅
## TODO - 미커밋 변경사항
### 작업 목표
- Backend API가 이미 존재하는 3개 모듈의 Mock → API 연동
- pricing-management, estimates, category-management
- `src/components/quotes/types.ts` - `formula_source?: string` 추가 (TypeScript 빌드 에러 수정)
### 완료된 작업
---
| 모듈 | 변경 내용 | 상태 |
|------|----------|------|
| pricing-management | Mock → apiClient 변환 (378줄), types.ts 타입 추가 | ✅ |
| estimates | Mock → apiClient 변환, 복잡한 중첩 타입 처리 | ✅ |
| category-management | Mock → apiClient 변환, 에러 타입 처리 (IN_USE/DEFAULT/GENERAL) | ✅ |
## TODO - 건설관리 Mock 모듈 (Backend API 개발 후 연동)
### 수정된 파일
| 파일명 | 설명 |
|--------|------|
| `src/components/business/construction/pricing-management/actions.ts` | Mock → apiClient 표준화 |
| `src/components/business/construction/pricing-management/types.ts` | PricingListResponse, PricingFilter, PricingFormData 추가 |
| `src/components/business/construction/estimates/actions.ts` | Mock → apiClient 표준화 (중첩 타입) |
| `src/components/business/construction/category-management/actions.ts` | Mock → apiClient 표준화 |
### 적용된 패턴
- `'use server'` + `apiClient from '@/lib/api'`
- Snake_case API 타입 (ApiXxx) → camelCase Frontend 타입 변환
- 표준 응답: `{ success, data?, error? }`
- 페이지네이션: `{ items, total, page, size, totalPages }`
### 빌드 검증
✅ Next.js 빌드 성공 (349 페이지)
### 남은 Mock 모듈 (Backend API 개발 필요)
| 모듈 | Backend API | 비고 |
|------|-------------|------|
| bidding | ❌ 없음 | Backend 필요 |
@@ -87,807 +26,4 @@
| structure-review | ❌ 없음 | Backend 필요 |
| labor-management | ❌ 없음 | Backend 필요 |
---
## 2026-01-09 (목) - Phase 1.3-1.5 건설관리 apiClient 표준화
### 작업 목표
- 건설관리 모듈의 커스텀 `apiRequest` 함수를 표준 `apiClient` 패턴으로 변환
- Phase 1.3: 계약관리(contract), Phase 1.4: 거래처관리(partners), Phase 1.5: 현장관리(site-management)
### 수정된 파일
| 파일명 | 설명 |
|--------|------|
| `src/components/business/construction/contract/actions.ts` | 커스텀 apiRequest → apiClient 표준화 |
| `src/components/business/construction/partners/actions.ts` | 커스텀 apiRequest → apiClient 표준화 |
| `src/components/business/construction/site-management/actions.ts` | 커스텀 apiRequest → apiClient 표준화 |
### 주요 변경 내용
#### 1. 제거된 코드 (각 파일에서)
- 커스텀 `apiRequest()` 함수 전체
- `import { cookies } from 'next/headers'`
- `const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL`
- `const API_KEY = process.env.API_KEY`
#### 2. 추가된 코드
- `import { apiClient } from '@/lib/api'`
- 명시적 API 타입 정의:
- **contract**: `ApiContract`, `ApiContractFile`, `ApiAttachment`, `ApiContractStats`, `ApiContractStageCount`
- **partners**: `ApiPartner`, `ApiPartnerStats`
- **site-management**: `ApiSite`, `ApiSiteStats`
#### 3. API 엔드포인트 (변경 없음)
**계약관리 (contract)**
- `GET /construction/contracts` - 목록
- `GET /construction/contracts/stats` - 통계
- `GET /construction/contracts/stage-counts` - 단계별 건수
- `GET /construction/contracts/{id}` - 상세
- `POST /construction/contracts` - 등록
- `PUT /construction/contracts/{id}` - 수정
- `DELETE /construction/contracts/{id}` - 삭제
- `DELETE /construction/contracts/bulk` - 일괄 삭제
**거래처관리 (partners)**
- `GET /clients` - 목록
- `GET /clients/stats` - 통계
- `GET /clients/{id}` - 상세
- `POST /clients` - 등록
- `PUT /clients/{id}` - 수정
- `DELETE /clients/{id}` - 삭제
- `DELETE /clients/bulk` - 일괄 삭제
**현장관리 (site-management)**
- `GET /sites` - 목록
- `GET /sites/stats` - 통계
- `DELETE /sites/{id}` - 삭제
- `DELETE /sites/bulk` - 일괄 삭제
### 빌드 검증
✅ Next.js 빌드 성공 (349 페이지)
### Git 커밋
- React: `5db6e59` refactor(construction): 건설관리 3개 모듈 apiClient 표준화
---
## 2026-01-09 (목) - Phase 1.2 인수인계보고서 API 표준화
### 작업 목표
- `handover-report/actions.ts` 커스텀 fetch → 표준 apiClient 변환
- 기존 API 연동 코드를 프로젝트 표준 패턴으로 통일
### 수정된 파일
| 파일명 | 설명 |
|--------|------|
| `src/components/business/construction/handover-report/actions.ts` | 커스텀 apiRequest → apiClient 표준화 |
### 주요 변경 내용
#### 1. 제거된 코드
- 커스텀 `apiRequest()` 함수 (52줄)
- `cookies()` 직접 import
- `API_BASE_URL`, `API_KEY` 직접 정의
#### 2. 추가된 코드
- `import { apiClient } from '@/lib/api'`
- 명시적 API 타입 정의: `ApiHandoverReport`, `ApiManager`, `ApiContractItem`, `ApiExternalEquipmentCost`
#### 3. API 엔드포인트 (변경 없음)
- `GET /construction/handover-reports` - 목록
- `GET /construction/handover-reports/stats` - 통계
- `GET /construction/handover-reports/{id}` - 상세
- `POST /construction/handover-reports` - 등록
- `PUT /construction/handover-reports/{id}` - 수정
- `DELETE /construction/handover-reports/{id}` - 삭제
- `DELETE /construction/handover-reports/bulk` - 일괄 삭제
### 빌드 검증
✅ Next.js 빌드 성공 (349 페이지)
### Git 커밋
- React: `b7b8b90` refactor(handover-report): 커스텀 fetch → apiClient 표준화
---
## 2026-01-09 (목) - Phase 2.4 수주관리 API 연동
### 작업 목표
- 시공사 페이지 API 연동 계획 Phase 2.4: 수주관리
- `order-management/actions.ts` Mock 데이터 → 실제 API 연동
- common_codes 테이블 기반 공용 코드 시스템 도입
### 수정된 파일
| 저장소 | 파일명 | 설명 |
|--------|--------|------|
| api | `database/migrations/2026_01_09_171700_add_order_codes_to_common_codes.php` | order_status/order_type 코드 추가 |
| api | `app/Http/Controllers/Api/V1/CommonController.php` | index 메서드 구현 |
| react | `src/lib/api/common-codes.ts` | 공용 코드 조회 유틸리티 (신규) |
| react | `src/lib/api/index.ts` | common-codes 모듈 export 추가 |
| react | `src/components/business/construction/order-management/actions.ts` | Mock → API 완전 재작성 |
### 주요 변경 내용
#### 1. common_codes 공용 코드 시스템
- `order_status` 코드 그룹: DRAFT, CONFIRMED, IN_PROGRESS, COMPLETED, CANCELLED
- `order_type` 코드 그룹: ORDER, PURCHASE
- API 엔드포인트: `GET /api/v1/settings/common/{group}`
#### 2. 상태 매핑 함수
| Frontend | Backend |
|----------|---------|
| waiting | DRAFT |
| order_complete | CONFIRMED |
| delivery_scheduled | IN_PROGRESS |
| delivery_complete | COMPLETED |
#### 3. API 함수 구현 (10개)
- `getOrderList()` - GET /api/v1/orders
- `getOrderStats()` - GET /api/v1/orders/stats
- `getOrderDetail()` - GET /api/v1/orders/{id}
- `getOrderDetailFull()` - GET /api/v1/orders/{id} (전체 정보)
- `createOrder()` - POST /api/v1/orders
- `updateOrder()` - PUT /api/v1/orders/{id}
- `deleteOrder()` - DELETE /api/v1/orders/{id}
- `deleteOrders()` - 개별 삭제 반복 (batch API 미존재)
- `duplicateOrder()` - 조회 후 새로 생성
- `updateOrderStatus()` - PATCH /api/v1/orders/{id}/status
### Git 커밋
- API: `9f8bff2` feat(common-codes): order_status/order_type 공용 코드 추가
- React: `6615f39` feat(order-management): Mock → API 연동 및 common-codes 유틸리티 추가
### 빌드 검증
✅ Next.js 빌드 성공 (349 페이지)
---
## 2026-01-09 (목) - TODO-1 결재선/참조 Select 버그 수정
### 작업 목표
- 결재선/참조 Select 컴포넌트에서 선택한 직원 정보가 표시되지 않는 버그 수정
- @/lib/api barrel export 추가 (빌드 오류 해결)
### 수정된 파일
| 파일명 | 설명 |
|--------|------|
| `src/components/approval/DocumentCreate/ApprovalLineSection.tsx` | SelectValue 버그 수정 |
| `src/components/approval/DocumentCreate/ReferenceSection.tsx` | SelectValue 버그 수정 |
| `src/lib/api/index.ts` | 신규 생성 - barrel export |
### 주요 변경 내용
#### 1. SelectValue 버그 수정
**문제**: Radix UI SelectValue의 children prop에 조건부 렌더링 사용 시 Select 상태 관리가 깨짐
**해결**: children 제거, placeholder prop으로 이동
```tsx
// Before (버그)
<SelectValue placeholder="부서명 / 직책명 / 이름 ▼">
{person.name ? `${person.department} / ${person.position} / ${person.name}` : null}
</SelectValue>
// After (수정)
<SelectValue
placeholder={
person.name && !person.id.startsWith('temp-')
? `${person.department || ''} / ${person.position || ''} / ${person.name}`
: "부서명 / 직책명 / 이름 ▼"
}
/>
```
#### 2. @/lib/api barrel export
Phase 2.3 자재관리 작업에서 사용하는 import 경로 지원:
```typescript
// src/lib/api/index.ts
export { ApiClient, withTokenRefresh } from './client';
export { serverFetch } from './fetch-wrapper';
export { AUTH_CONFIG } from './auth/auth-config';
export const apiClient = new ApiClient({
mode: 'api-key',
apiKey: process.env.API_KEY,
});
```
### 빌드 검증
✅ Next.js 빌드 성공 (349 페이지)
---
## 2026-01-09 (목) - Phase 2.3 자재관리(품목관리) API 연동
### 작업 목표
- 시공사 페이지 API 연동 계획 Phase 2.3: 자재관리
- `item-management/actions.ts` Mock 데이터 → 실제 API 연동
### 수정된 파일
| 파일명 | 설명 |
|--------|------|
| `src/components/business/construction/item-management/actions.ts` | Mock → API 완전 재작성 |
| `claudedocs/[IMPL-2026-01-09] item-management-api-integration.md` | 구현 문서 |
### 주요 변경 내용
#### 1. 타입 변환 함수 추가
- `transformItemType()` - Backend item_type → Frontend itemType
- `transformToBackendItemType()` - Frontend itemType → Backend item_type
- `transformSpecification()` - Backend options → Frontend specification
- `transformOrderType()` - Backend options → Frontend orderType
- `transformStatus()` - Backend is_active + options → Frontend status
- `transformOrderItems()` - Backend options → Frontend orderItems
- `transformItem()` - API 응답 → Item 타입
- `transformItemDetail()` - API 응답 → ItemDetail 타입
- `transformItemToApi()` - ItemFormData → API 요청 데이터
#### 2. 품목유형 매핑
| Frontend | Backend |
|----------|---------|
| 제품 | FG |
| 부품 | PT |
| 소모품 | CS |
| 공과 | RM |
#### 3. API 함수 구현 (8개)
- `getItemList()` - GET /api/v1/items
- `getItemStats()` - GET /api/v1/items/stats
- `getItem()` - GET /api/v1/items/{id}
- `createItem()` - POST /api/v1/items
- `updateItem()` - PUT /api/v1/items/{id}
- `deleteItem()` - DELETE /api/v1/items/{id}
- `deleteItems()` - DELETE /api/v1/items/batch
- `getCategoryOptions()` - GET /api/v1/categories
#### 4. Frontend 전용 필터링
Backend에서 미지원 필터는 Frontend에서 처리:
- 규격 (specification)
- 구분 (orderType)
- 날짜 범위 (startDate, endDate)
- 정렬 (sortBy)
### 관련 API 변경 (api 저장소)
- `routes/api.php` - `/items/stats` 라우트 추가
### 관련 문서
- 구현 문서: `claudedocs/[IMPL-2026-01-09] item-management-api-integration.md`
---
## 2025-01-09 (목) - 작업지시 process_type → process_id FK 변환
### 작업 목표
- 작업지시의 `process_type` (varchar enum: 'screen'/'slat'/'bending')를 `process_id` (FK → processes.id)로 변환
- API와 Frontend 전체 스택 마이그레이션
### 수정된 파일
| 파일명 | 설명 |
|--------|------|
| `src/components/production/WorkOrders/types.ts` | processId, processName, processCode 필드 추가, transformApiToFrontend에서 processType 하위 호환 유지 |
| `src/components/production/WorkOrders/actions.ts` | getProcessOptions() 추가, createWorkOrder에서 processId 사용 |
| `src/components/production/WorkOrders/WorkOrderCreate.tsx` | processType enum → processId FK 변경, 동적 공정 옵션 로딩 |
| `src/components/production/WorkOrders/WorkOrderList.tsx` | PROCESS_TYPE_LABELS 제거, order.processName 사용 |
| `src/components/production/WorkOrders/WorkOrderDetail.tsx` | PROCESS_TYPE_LABELS 제거, order.processName 사용 (비즈니스 로직은 processType 유지) |
### 주요 변경 내용
#### 1. types.ts - 타입 및 변환 함수
- `WorkOrder` 인터페이스에 `processId`, `processName`, `processCode` 추가
- `processType``@deprecated` 마킹, 하위 호환용 유지
- `transformApiToFrontend`에서 `processName``processType` 자동 매핑
#### 2. actions.ts - 서버 액션
- `getProcessOptions()`: 공정 목록 API 조회 (GET /api/v1/processes)
- `createWorkOrder()`: `processId` 필드 사용 (기존 processType 제거)
#### 3. WorkOrderCreate.tsx - 등록 폼
- `processType: ProcessType``processId: number | null`
- `useEffect`로 공정 옵션 동적 로딩
- 첫 번째 공정 자동 선택 (기본값)
- Select 컴포넌트 동적 옵션 렌더링
#### 4. WorkOrderList.tsx / WorkOrderDetail.tsx - 목록/상세
- `PROCESS_TYPE_LABELS[order.processType]``order.processName`
- 비즈니스 로직(ProcessSteps, 절곡 확인)은 `processType` 유지
### 빌드 검증
✅ Next.js 빌드 성공 (TypeScript 오류 없음)
### 관련 API 변경 (api 저장소)
- `WorkOrder` 모델: `process_id` FK 추가, `process()` 관계 정의
- `WorkOrderService`: `process_id` 사용
- `WorkOrderStoreRequest/UpdateRequest`: `process_id` 검증 규칙
---
## 2025-01-09 (목) - 작업지시 코드 리뷰 기반 프론트엔드 개선
### 작업 목표
- 작업지시 기능 코드 리뷰 결과 기반 프론트엔드 개선
- Critical, High, Medium 우선순위 항목 전체 수정
### 수정된 파일
| 파일명 | 설명 |
|--------|------|
| `src/components/production/WorkOrders/WorkOrderList.tsx` | useCallback 의존성 순환 수정 |
| `src/components/production/WorkOrders/WorkOrderDetail.tsx` | 작업 버튼 핸들러 구현 |
| `src/components/production/WorkOrders/types.ts` | scheduledDate 매핑, 다중 담당자 타입 추가 |
| `src/components/production/WorkOrders/actions.ts` | API 경로 수정 (/sales-orders → /orders) |
| `src/components/production/WorkOrders/SalesOrderSelectModal.tsx` | debounce 적용 |
| `src/components/production/WorkOrders/hooks/useDebounce.ts` | 신규 생성 - 커스텀 debounce 훅 |
### 주요 변경 내용
1. **useCallback 의존성 수정**: 무한 루프 방지를 위한 의존성 배열 수정
2. **scheduledDate 매핑**: transformFrontendToApi에 scheduled_date 필드 추가
3. **작업 버튼 구현**: "시작"/"완료" 버튼 핸들러 추가
4. **API 경로 수정**: `/api/v1/sales-orders``/api/v1/orders` 변경
5. **debounce 적용**: 커스텀 useDebounce 훅 (300ms) 적용
6. **다중 담당자 타입**: WorkOrderAssigneeApi 인터페이스 및 assignees 필드 추가
### Git 커밋
- `12b4259 refactor(work-orders): 코드 리뷰 기반 프론트엔드 개선`
### 관련 문서
- 계획: `~/.claude/plans/purring-sparking-pinwheel.md`
---
## 2025-01-02 (목) - 견적 등록 자동산출 기능 구현
### 작업 목표
- 견적 등록 화면에서 BOM 기반 자동산출 기능 구현
- MNG 시뮬레이터와 동일하게 동작하도록 API 연동
### 수정된 파일
| 파일명 | 설명 |
|--------|------|
| `src/components/quotes/QuoteRegistration.tsx` | FormField type="custom" 추가, API 요청 구조 변경, 응답 파싱 수정 |
| `src/components/quotes/actions.ts` | Item 모델 필드 매핑 수정, BomCalculateItem 인터페이스 변경 |
### 주요 변경 내용
1. **FormField 렌더링 수정**:
- Input 자식 컴포넌트도 `type="custom"` 필요
- openWidth, openHeight 필드에 적용
2. **API 필드 매핑 수정** (actions.ts):
- `item.item_code``item.code` (Laravel Item 모델 필드명)
- `item.item_name``item.name`
3. **API 요청 구조 변경** (QuoteRegistration.tsx):
- 중첩 구조 제거: `{ input_variables: { W0, H0 } }``{ openWidth, openHeight }`
- flat 구조로 API FormRequest와 일치
4. **API Enum 값 변경**:
- 가이드레일: "벽면형" → "wall", "측면형" → "floor"
- 모터전원: "220V" → "single", "380V" → "three"
- 제어기: "단독" → "basic", "연동" → "smart"
5. **API 응답 파싱 수정**:
- `result.data.items` 배열 접근
- `result.data.summary.grand_total` 총합계 접근
### Git 커밋
- `5a3e534` feat(WEB): 견적 등록 자동산출 기능 구현
- `5f062d5` chore(WEB): 견적 등록 디버깅 로그 제거
### 관련 API
- `POST /api/v1/quotes/calculate/bom/bulk` - 다건 BOM 자동산출 API
---
## 2025-01-02 (목) - 채권현황 동적월 지원 및 버그 수정
### 작업 목표
- "최근 1년" 필터 선택 시 동적 월 기간(최근 12개월) 지원
- year=0 파라미터 처리 버그 수정
- 거래처별 연체 상태 및 메모 관리 기능 추가
### 수정된 파일
| 파일명 | 설명 |
|--------|------|
| `src/components/accounting/ReceivablesStatus/types.ts` | MonthlyAmount 동적 배열로 변경, 새 필드 추가 |
| `src/components/accounting/ReceivablesStatus/actions.ts` | year=0 처리 버그 수정, updateMemos 액션 추가 |
| `src/components/accounting/ReceivablesStatus/index.tsx` | 동적 월 헤더 및 메모 입력 행 추가 |
### 주요 변경 내용
1. **types.ts 변경**:
- `MonthlyAmount`: 고정 월 키 → `values: number[]` 동적 배열
- `VendorReceivables`: `monthLabels`, `carryForwardBalance`, `memo` 필드 추가
- 정적 `MONTH_LABELS`, `MONTH_KEYS` 상수 제거
2. **actions.ts 버그 수정**:
- `typeof yearValue === 'number'` 명시적 타입 체크 추가
- `year=0`일 때 `recent_year=true` 파라미터 올바르게 전송
- `updateMemos` 액션 추가
3. **index.tsx UI 개선**:
- API에서 받은 `monthLabels` 사용하여 동적 헤더 렌더링
- 메모 입력 행 추가 (거래처 단위)
- 연체/메모 변경사항 추적 및 저장
### Git 커밋
- `672b1b4` feat(WEB): 채권현황 동적월 지원 및 year=0 파라미터 버그 수정
### 남은 작업
- [ ] 디버깅 console.log 제거 (테스트 완료 후)
- [ ] 추가 UI 개선사항 확인
---
## 2025-12-28 (토) - 고객센터 시스템 게시판 API 연동 수정
### 작업 목표
- 고객센터 컴포넌트에서 시스템 게시판 API 엔드포인트 사용
- 날짜 범위 필터 초기값 수정 (전체 조회)
### 수정된 파일 (4개)
| 파일명 | 변경 내용 |
|--------|----------|
| `src/components/customer-center/shared/actions.ts` | `/boards/``/system-boards/` API 엔드포인트 변경 |
| `src/components/customer-center/EventManagement/EventList.tsx` | 날짜 범위 초기값 빈 문자열로 변경 (전체 조회) |
| `src/components/customer-center/InquiryManagement/InquiryList.tsx` | 날짜 범위 초기값 빈 문자열로 변경 (전체 조회) |
| `src/components/customer-center/NoticeManagement/NoticeList.tsx` | 날짜 범위 초기값 빈 문자열로 변경 (전체 조회) |
### 상세 변경사항
#### 1. shared/actions.ts API 엔드포인트 변경
```typescript
// 변경 전
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/boards/${boardCode}/posts`;
// 변경 후
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/system-boards/${boardCode}/posts`;
```
영향받는 함수:
- `getPosts()` - 게시글 목록 조회
- `getPost()` - 게시글 상세 조회
- `createPost()` - 게시글 생성
- `updatePost()` - 게시글 수정
- `deletePost()` - 게시글 삭제
#### 2. 날짜 범위 필터 초기값 변경
```typescript
// 변경 전
const [startDate, setStartDate] = useState(format(new Date(), 'yyyy-MM-dd'));
const [endDate, setEndDate] = useState(format(new Date(), 'yyyy-MM-dd'));
// 변경 후
const [startDate, setStartDate] = useState('');
const [endDate, setEndDate] = useState('');
```
- 초기 로드 시 모든 데이터 조회 가능
- 날짜 필터 미선택 시 전체 기간 조회
### 연관 API 수정 (api 저장소)
- `PostService.php` - 시스템 게시판 tenant_id 처리 개선
- custom_fields field_key → field_id 매핑 지원
- 댓글 생성 시 tenant_id 추가
---
## 2025-12-27 (금) - 결재 문서 작성 버그 수정
### 수정된 파일 (2개)
| 파일명 | 변경 내용 |
|--------|----------|
| `src/components/approval/DocumentCreate/actions.ts` | transformApiToFormData에서 `form.code` 처리 추가 |
| `src/components/approval/DocumentCreate/index.tsx` | useRef로 toast 중복 호출 방지 |
### 완료된 수정
#### 1. 복제 모드 documentType 매핑 오류 수정
- **문제**: 복제로 들어왔을 때 문서유형이 선택되지 않아 추가 폼이 안 보임
- **원인**: API는 `form.code`로 반환하는데 프론트엔드는 `form_code`를 기대
- **수정파일**: `src/components/approval/DocumentCreate/actions.ts`
- **수정내용**: `transformApiToFormData`에서 `apiData.form?.code || apiData.form_code` 처리
#### 2. 복제 모드 toast 중복 호출 수정
- **문제**: "문서가 복제되었습니다" 메시지가 두 번 표시됨
- **원인**: React.StrictMode에서 useEffect 두 번 실행
- **수정파일**: `src/components/approval/DocumentCreate/index.tsx`
- **수정내용**: `useRef`로 toast 호출 중복 방지
### 미해결 React Todo 🚧
#### TODO-1: 결재선/참조 Select 변경 불가 문제
- **증상**: 한번 결재자/참조자를 선택하면 다른 사람으로 변경 불가
- **원인 후보**:
1. `SelectTrigger` 내부 조건부 렌더링(`span` vs `SelectValue`)이 Radix Select 상태 관리에 영향
2. `employees` 배열에 선택된 person이 없어서 Select value가 유효하지 않음
- **해결 방향**:
- A. `employees` 배열에 현재 선택된 사람들 포함 (useMemo)
- B. `SelectTrigger` 내부를 항상 `SelectValue`만 렌더링하고 표시 내용만 변경
- C. Shadcn/ui Select 컴포넌트 디버깅 필요
- **파일**: `ApprovalLineSection.tsx`, `ReferenceSection.tsx`
---
## 2025-12-26 (목) - 급여관리 직책/직급 매핑 수정
### 문제
- 급여관리 페이지에서 직책과 직급이 사원관리와 다르게 표시됨
- `position_label` → 직책으로 잘못 매핑 (실제로는 직위)
- `job_title_label` → 직급으로 잘못 매핑 (실제로는 직책)
### 수정된 파일 (1개)
| 파일명 | 변경 내용 |
|--------|----------|
| `src/components/hr/SalaryManagement/actions.ts` | 직책/직급 매핑 수정 |
### 상세 변경사항
- `transformApiToFrontend` (목록용):
- `position: profile?.position_label``profile?.job_title_label` (직책)
- `rank: profile?.job_title_label``profile?.rank` (직급)
- `transformApiToDetail` (상세용):
- 동일하게 수정
### 매핑 기준 (사원관리 기준 통일)
| 필드 | API 필드 | 설명 | 예시 |
|------|----------|------|------|
| 직책 (position) | `job_title_label` | 직무상 책임 | 팀장, 팀원 |
| 직급 (rank) | `rank` | 호봉 등급 | 부장, 과장, 대리 |
---
## 2025-12-26 (목) - 휴가관리 사용현황 동기화 수정
### 작업 목표
- 휴가 승인 후 사용현황 즉시 반영
- 부여일수 계산 수정 (기본 15일 + 부여분)
### 수정된 파일 (1개)
| 파일명 | 변경 내용 |
|--------|----------|
| `src/components/hr/VacationManagement/index.tsx` | 승인 후 `fetchUsageData()` 호출 추가, baseVacation 고정 '15일', grantedVacation 계산식 수정 |
### 상세 변경사항
- `handleApproveConfirm`: 승인 후 `fetchUsageData()` 호출 추가
- `baseVacation`: 동적 `${totalDays}일` → 고정 `'15일'`
- `grantedVacation`: 하드코딩 `'0일'``Math.max(0, totalDays - 15)일`
- `useCallback` dependencies에 `fetchUsageData` 추가
### Git 커밋
```
909005c fix(vacation): 휴가 사용현황 동기화 및 부여일수 계산 수정
```
---
## 2025-12-23 (월) - React Mock Data to API 마이그레이션 Phase B
### 프로젝트 개요
React 컴포넌트에서 Mock 데이터를 실제 API 호출로 교체하는 작업
**참고 문서:** `docs/plans/react-mock-to-api-migration-plan.md`
### 진행 상황
#### Phase A (완료 - 이전 세션)
- [x] A-1 악성채권 관리 API 연동
- [x] A-2 거래처 관리 API 연동
- [x] A-3 어음 관리 API 연동
- [x] A-4 대출 관리 API 연동
- [x] A-5 알림 설정 API 연동
- [x] A-6 거래처 원장 (API 미존재로 스킵)
#### Phase B (✅ 완료)
- [x] B-1 매출관리 (SalesManagement) API 연동 ✅
- [x] B-2 매입관리 (PurchaseManagement) API 연동 ✅
- [x] B-2.1 매입 세금계산서 토글 기능 수정 ✅
- [x] B-3 입금관리 (DepositManagement) API 연동 ✅
- [x] B-4 출금관리 (WithdrawalManagement) API 연동 ✅
- [x] B-5 거래처관리 (VendorManagement) API 연동 ✅
- [x] B-6 어음관리 (BillManagement) API 연동 ✅
> **참고**: 원본 계획 문서(`docs/plans/react-mock-to-api-migration-plan.md`)의 Phase B 정의와 일치하도록 수정함
---
### B-1 매출관리 API 연동 (완료)
#### 수정된 파일
- `src/components/accounting/SalesManagement/types.ts`
- API 응답 타입 추가 (ApiSaleData, ApiSalesListResponse 등)
- transformApiSaleToRecord() 변환 함수 추가
- formatDate() 날짜 포맷 함수 추가
- `src/components/accounting/SalesManagement/index.tsx`
- generateMockData() 제거
- fetchSales(), deleteSale() API 함수 추가
- useEffect로 API 데이터 로딩
- 삭제 핸들러 API 연동
#### 테스트 결과
- API 연동 성공 (80개 레코드)
- 페이지네이션 정상 동작 (4페이지)
- 통계 카드 정상 표시 (총 매출: 679,876,062원)
- 날짜 포맷 정상 (YYYY-MM-DD)
---
### B-2 매입관리 API 연동 (완료)
#### 수정된 파일
- `src/components/accounting/PurchaseManagement/types.ts`
- API 응답 타입 추가 (ApiPurchaseData, ApiPurchasesListResponse 등)
- transformApiPurchaseToRecord() 변환 함수 추가
- formatDate() 날짜 포맷 함수 추가
- `src/components/accounting/PurchaseManagement/index.tsx`
- generateMockData() 제거
- fetchPurchases(), deletePurchase() API 함수 추가
- useEffect로 API 데이터 로딩
- 삭제 핸들러 API 연동
- toast 알림 추가
#### 테스트 결과
- API 연동 성공 (70개 레코드)
- 페이지네이션 정상 동작 (4페이지)
- 통계 카드 정상 표시:
- 총 매입: 577,881,642원
- 당월 매입: 164,988,080원
- 매입유형 미설정: 20건
- 세금계산서 수취 미확인: 8건
- 날짜 포맷 정상 (YYYY-MM-DD)
---
### B-2.1 매입 세금계산서 토글 기능 수정 (2025-12-24)
#### 문제
- 매입 관리 페이지에서 세금계산서 수취 토글이 작동하지 않음
- 원인 1: API 마이그레이션 미실행 (tax_invoice_received 컬럼 미존재)
- 원인 2: index.tsx에서 Mock 데이터 사용 중 (API 미연동)
#### 수정된 파일
- `src/components/accounting/PurchaseManagement/index.tsx`
- Mock 데이터(generateMockData) → API 데이터로 전환
- useEffect 추가로 API 데이터 로딩
- isLoading 상태 추가
- vendorOptions에서 빈 문자열 필터링 (Select.Item 에러 수정)
- format import 제거 (미사용)
- PurchaseType import 제거 (미사용)
- `src/components/accounting/PurchaseManagement/actions.ts` (신규)
- getPurchases(): 매입 목록 조회 서버 액션
- togglePurchaseTaxInvoice(): 세금계산서 수취 토글 서버 액션
- API 응답 변환 함수 포함
#### API 변경사항 (api 저장소)
- 마이그레이션 실행: `2025_12_24_160000_add_tax_invoice_received_to_purchases_table`
- Purchase 모델: tax_invoice_received 필드 추가
- PurchaseService: toggleTaxInvoice() 메서드 추가
#### 버그 수정
- **Console Error**: `A <Select.Item /> must have a value prop that is not an empty string`
- 원인: API 응답에 vendorName이 빈 문자열인 매입 레코드 존재
- 해결: vendorOptions 생성 시 빈 문자열 필터링 추가
```typescript
const uniqueVendors = [...new Set(data.map(d => d.vendorName).filter(v => v && v.trim() !== ''))];
```
#### 테스트 결과
- 세금계산서 수취 토글 정상 동작 ✅
- API 호출 및 UI 업데이트 정상 ✅
- Console 에러 해결 ✅
---
### API 연동 패턴 (공통)
```typescript
// 1. types.ts에 API 타입 추가
export interface ApiXxxData {
id: number;
// snake_case 필드들
}
export interface ApiXxxListResponse {
success: boolean;
message: string;
data: {
data: ApiXxxData[];
current_page: number;
last_page: number;
per_page: number;
total: number;
};
}
// 2. 변환 함수 추가
export function transformApiXxxToRecord(apiData: ApiXxxData): XxxRecord {
// snake_case → camelCase 변환
// 날짜 포맷 변환
// 상태 매핑
}
// 3. index.tsx에서 API 함수 추가
async function fetchXxx(params): Promise<ApiXxxListResponse> {
const url = `/api/proxy/xxx?${searchParams.toString()}`;
const response = await fetch(url);
return response.json();
}
// 4. useEffect로 데이터 로딩
useEffect(() => {
loadData();
}, [loadData]);
```
---
#### Phase C (✅ 완료)
- [x] C-1 직원관리 (EmployeeManagement) API 연동 ✅
- [x] C-2 근태관리 (AttendanceManagement) API 연동 ✅
- [x] C-3 휴가관리 (VacationManagement) API 연동 ✅
#### Phase D (✅ 완료) - 설정/시스템
- [x] D-1 부서관리 (DepartmentManagement) API 연동 ✅
- [x] D-2 직급관리 (RankManagement) API 연동 ✅
- [x] D-3 직책관리 (TitleManagement) API 연동 ✅
- [x] D-4 근무시간설정 (WorkScheduleManagement) API 연동 ✅
#### Phase E (✅ 완료) - 인사/급여
- [x] E-1 급여관리 (SalaryManagement) API 연동 ✅
- [x] E-2 카드관리 (CardManagement) API 연동 ✅
#### Phase F (✅ 완료) - 결재시스템
- [x] F-1 기안함 (DraftBox) API 연동 ✅
- [x] F-2 결재함 (ApprovalBox) API 연동 ✅
- [x] F-3 참조함 (ReferenceBox) API 연동 ✅
- [x] F-4 문서작성 (DocumentCreate) API 연동 ✅
#### Phase G (✅ 완료) - 생산관리
- [x] G-1 작업지시 (WorkOrders) API 연동 ✅
- [x] G-2 작업실적 (WorkResults) API 연동 ✅
- [x] G-3 작업자화면 (WorkerScreen) API 연동 ✅
- [x] G-4 생산현황 (ProductionDashboard) API 연동 ✅
#### Phase H (✅ 완료) - 자재/출하
- [x] H-1 재고현황 (StockStatus) API 연동 ✅
- [x] H-2 입고관리 (ReceivingManagement) API 연동 ✅
- [x] H-3 출하관리 (ShipmentManagement) API 연동 ✅
#### Phase I (✅ 완료) - 판매/견적
- [x] I-1 수주관리 (Orders) API 연동 ✅
- [x] I-2 단가관리 (Pricing) API 연동 ✅
- [x] I-3 견적관리 (Quotes) API 연동 ✅
#### Phase J (✅ 완료) - 회계관리
- [x] 악성채권, 계좌조회, 어음관리, 카드거래 등 13개 모듈 API 연동 ✅
#### Phase K (✅ 완료) - 보고서
- [x] K-1 종합분석 (Reports) API 연동 ✅
#### Phase L (🔄 진행중 ~80%) - 건설관리
**✅ apiClient 표준화 완료:**
- [x] handover-report (b7b8b90)
- [x] contract (5db6e59)
- [x] partners (5db6e59)
- [x] site-management (5db6e59)
- [x] order-management (6615f39)
- [x] item-management (Phase 2.3)
- [x] pricing-management (Phase L) ✅ 2026-01-09
- [x] estimates (Phase L) ✅ 2026-01-09
- [x] category-management (Phase L) ✅ 2026-01-09
**⏳ Mock → API 변환 필요 (Backend API 개발 필요):**
- [ ] bidding - 입찰관리
- [ ] site-briefings - 현장설명회
- [ ] structure-review - 구조검토
- [ ] labor-management - 노무관리
> **마이그레이션 진행률**: 97% 완료 (41/43 모듈) - 건설관리 4개 모듈 Backend API 개발 필요
> **점검일**: 2026-01-09
### 다음 작업
- Phase L 건설관리 모듈 마이그레이션 완료 (Backend API 개발 필요: bidding, site-briefings, structure-review, labor-management)
- ~~TODO-1: 결재선/참조 Select 변경 불가 문제~~ ✅ 2026-01-09 수정 완료
---
> Mock → API 마이그레이션 진행률: 97% 완료 (41/43 모듈)

View File

@@ -24,7 +24,7 @@ import {
saveInspectionDocument,
} from '../actions';
import type { WorkOrder, ProcessType } from '../types';
import type { InspectionReportData } from '../actions';
import type { InspectionReportData, InspectionReportNodeGroup } from '../actions';
import { ScreenInspectionContent } from './ScreenInspectionContent';
import { SlatInspectionContent } from './SlatInspectionContent';
import { BendingInspectionContent } from './BendingInspectionContent';
@@ -73,16 +73,52 @@ function toInspectionData(raw: Record<string, unknown>): InspectionData {
}
/**
* API 응답의 items를 WorkItemData[] + InspectionDataMap으로 변환
* API 응답 WorkItemData[] + InspectionDataMap으로 변환
* node_groups가 있으면 개소(node) 단위, 없으면 개별 아이템 단위 (폴백)
*/
function buildFromReportItems(
items: InspectionReportData['items'],
function buildFromReportData(
reportData: InspectionReportData,
processType: ProcessType
): { workItems: WorkItemData[]; inspectionDataMap: InspectionDataMap } {
const workItems: WorkItemData[] = [];
const inspectionDataMap: InspectionDataMap = new Map();
for (const item of items) {
// node_groups가 있으면 개소(node) 단위로 생성 — WorkerScreen과 동일
if (reportData.node_groups && reportData.node_groups.length > 0) {
reportData.node_groups.forEach((group: InspectionReportNodeGroup, index: number) => {
const nodeKey = group.node_id != null ? String(group.node_id) : `unassigned-${index}`;
const syntheticId = `report-node-${nodeKey}`;
const itemNames = group.items.map((it) => it.item_name).filter(Boolean);
workItems.push({
id: syntheticId,
apiItemId: group.items[0]?.id,
itemNo: index + 1,
itemCode: '',
itemName: itemNames.join(', ') || '-',
floor: group.floor || '-',
code: group.code || '-',
width: group.width || 0,
height: group.height || 0,
quantity: group.total_quantity,
processType: processType === 'bending_wip' ? 'bending' : processType,
steps: [],
});
// 개소 내 아이템 중 inspection_data가 있으면 병합
for (const item of group.items) {
if (item.inspection_data) {
inspectionDataMap.set(syntheticId, toInspectionData(item.inspection_data));
break; // 개소 단위 검사 데이터는 첫 번째 것 사용
}
}
});
return { workItems, inspectionDataMap };
}
// 폴백: 개별 아이템 단위 (node_groups 없는 구버전 응답)
for (const item of reportData.items) {
const syntheticId = `report-item-${item.id}`;
workItems.push({
@@ -226,7 +262,7 @@ export function InspectionReportModal({
// 2) 검사 성적서 데이터 → workItems + inspectionDataMap 구성
if (reportResult.success && reportResult.data) {
const { workItems: apiItems, inspectionDataMap: apiMap } =
buildFromReportItems(reportResult.data.items, processType);
buildFromReportData(reportResult.data, processType);
setApiWorkItems(apiItems);
setApiInspectionDataMap(apiMap);
setReportSummary(reportResult.data.summary);

View File

@@ -17,7 +17,7 @@
* - select (판정): 자동 계산 적/부
*/
import { useState, forwardRef, useImperativeHandle, useEffect, useMemo } from 'react';
import React, { useState, forwardRef, useImperativeHandle, useEffect, useMemo } from 'react';
import type { WorkOrder } from '../types';
import type { WorkItemData } from '@/components/production/WorkerScreen/types';
import type { InspectionDataMap } from './InspectionReportModal';
@@ -35,6 +35,7 @@ import {
INPUT_CLASS,
} from './inspection-shared';
import { formatNumber } from '@/lib/utils/amount';
import type { BendingInfoExtended } from './bending/types';
export type { InspectionContentRef };
@@ -145,6 +146,158 @@ function isJudgmentColumn(label: string): boolean {
return label.includes('판정');
}
// ===== Bending 검사 DATA 지원 (레거시 PHP 동기화) =====
interface BendingGapPoint {
point: string;
designValue: string;
}
interface BendingProduct {
id: string;
category: string;
productName: string;
productType: string;
lengthDesign: string;
widthDesign: string;
gapPoints: BendingGapPoint[];
}
interface BendingExpandedRow {
productIdx: number;
product: BendingProduct;
pointIdx: number;
gapPoint: BendingGapPoint;
isFirstRow: boolean;
totalPoints: number;
}
// 절곡 제품별 기본 간격 POINT (단면 치수 - 제품 사양에 따른 고정값)
const DEFAULT_GAP_PROFILES: Record<string, BendingGapPoint[]> = {
guideRailWall: [
{ point: '(1)', designValue: '30' },
{ point: '(2)', designValue: '78' },
{ point: '(3)', designValue: '25' },
{ point: '(4)', designValue: '45' },
],
guideRailSide: [
{ point: '(1)', designValue: '28' },
{ point: '(2)', designValue: '75' },
{ point: '(3)', designValue: '42' },
{ point: '(4)', designValue: '38' },
{ point: '(5)', designValue: '32' },
],
bottomBar: [{ point: '(1)', designValue: '60' }],
caseBox: [
{ point: '(1)', designValue: '550' },
{ point: '(2)', designValue: '50' },
{ point: '(3)', designValue: '385' },
{ point: '(4)', designValue: '50' },
{ point: '(5)', designValue: '410' },
],
smokeW50: [
{ point: '(1)', designValue: '50' },
{ point: '(2)', designValue: '12' },
],
smokeW80: [
{ point: '(1)', designValue: '80' },
{ point: '(2)', designValue: '12' },
],
};
/** bending_info에서 제품 목록 생성, 없으면 기본값 */
function buildBendingProducts(order: WorkOrder): BendingProduct[] {
const bi = order.bendingInfo as BendingInfoExtended | undefined;
const productCode = bi?.productCode || 'KQTS01';
const products: BendingProduct[] = [];
// 가이드레일 벽면형
if (!bi || bi.guideRail?.wall) {
const len = bi?.guideRail?.wall?.lengthData?.[0]?.length || 3500;
products.push({
id: 'guide-wall', category: productCode, productName: '가이드레일',
productType: '벽면형', lengthDesign: String(len), widthDesign: 'N/A',
gapPoints: DEFAULT_GAP_PROFILES.guideRailWall,
});
}
// 가이드레일 측면형
if (bi?.guideRail?.side) {
const len = bi.guideRail.side.lengthData?.[0]?.length || 3000;
products.push({
id: 'guide-side', category: productCode, productName: '가이드레일',
productType: '측면형', lengthDesign: String(len), widthDesign: 'N/A',
gapPoints: DEFAULT_GAP_PROFILES.guideRailSide,
});
}
// 하단마감재
products.push({
id: 'bottom-bar', category: productCode, productName: '하단마감재',
productType: '60×40', lengthDesign: '3000', widthDesign: 'N/A',
gapPoints: DEFAULT_GAP_PROFILES.bottomBar,
});
// 케이스 (shutterBox)
if (bi?.shutterBox?.length) {
bi.shutterBox.forEach((box, boxIdx) => {
(box.lengthData || []).forEach((ld, li) => {
products.push({
id: `case-${boxIdx}-${li}`, category: productCode, productName: '케이스',
productType: `${box.size || '양면'}\n${box.direction || ''}`.trim(),
lengthDesign: String(ld.length), widthDesign: 'N/A',
gapPoints: DEFAULT_GAP_PROFILES.caseBox,
});
});
});
} else {
products.push({
id: 'case-0', category: productCode, productName: '케이스',
productType: '양면', lengthDesign: '3000', widthDesign: 'N/A',
gapPoints: DEFAULT_GAP_PROFILES.caseBox,
});
}
// 연기차단재
products.push({
id: 'smoke-w50', category: productCode, productName: '연기차단재',
productType: '화이바 W50\n가이드레일용', lengthDesign: '-', widthDesign: '50',
gapPoints: DEFAULT_GAP_PROFILES.smokeW50,
});
products.push({
id: 'smoke-w80', category: productCode, productName: '연기차단재',
productType: '화이바 W80\n케이스용', lengthDesign: '-', widthDesign: '80',
gapPoints: DEFAULT_GAP_PROFILES.smokeW80,
});
return products;
}
// ===== 이미지 섹션 컴포넌트 (onError 핸들링) =====
function SectionImage({ section }: { section: { id: number; title?: string; name?: string; image_path?: string | null } }) {
const [imgError, setImgError] = useState(false);
const title = section.title || section.name || '';
const url = section.image_path ? getImageUrl(section.image_path) : '';
return (
<div className="mb-3">
<p className="text-sm font-bold mb-1"> {title}</p>
{url && !imgError ? (
<img
src={url}
alt={title}
className="w-full border rounded"
onError={() => setImgError(true)}
/>
) : (
<div className="border border-dashed border-gray-300 rounded p-6 text-center text-gray-400 text-xs">
</div>
)}
</div>
);
}
// ===== 컴포넌트 =====
export const TemplateInspectionContent = forwardRef<InspectionContentRef, TemplateInspectionContentProps>(
@@ -193,18 +346,47 @@ export const TemplateInspectionContent = forwardRef<InspectionContentRef, Templa
return map;
}, [template.columns, allItems]);
// complex 컬럼 존재 여부 (2행 헤더 필요 판단)
const hasComplexColumn = useMemo(
() => template.columns.some(c => c.column_type === 'complex' && c.sub_labels && c.sub_labels.length > 0),
[template.columns]
);
// 셀 값 상태: key = `${rowIdx}-${colId}`
const [cellValues, setCellValues] = useState<Record<string, CellValue>>({});
const [inadequateContent, setInadequateContent] = useState('');
const effectiveWorkItems = workItems || [];
// ===== Bending template detection & expanded rows =====
const isBending = useMemo(() => {
if (order.processType === 'bending') return true;
return template.columns.some(col =>
col.sub_labels?.some(sl => sl.toLowerCase().includes('point'))
);
}, [order.processType, template.columns]);
const gapColumnId = useMemo(() => {
if (!isBending) return null;
return template.columns.find(col =>
col.sub_labels?.some(sl => sl.toLowerCase().includes('point'))
)?.id ?? null;
}, [isBending, template.columns]);
const bendingProducts = useMemo(() => {
if (!isBending) return [];
return buildBendingProducts(order);
}, [isBending, order]);
const bendingExpandedRows = useMemo(() => {
if (!isBending) return [];
const rows: BendingExpandedRow[] = [];
bendingProducts.forEach((product, productIdx) => {
const total = product.gapPoints.length;
product.gapPoints.forEach((gp, pointIdx) => {
rows.push({
productIdx, product, pointIdx, gapPoint: gp,
isFirstRow: pointIdx === 0, totalPoints: total,
});
});
});
return rows;
}, [isBending, bendingProducts]);
// inspectionDataMap에서 초기값 복원
// InspectionInputModal 저장 키: section_{sectionId}_item_{itemId} / 값: "ok"|"ng"|number
// TemplateInspectionContent 내부 키: {rowIdx}-{colId} / 값: CellValue
@@ -499,31 +681,75 @@ export const TemplateInspectionContent = forwardRef<InspectionContentRef, Templa
},
}));
// Bending 제품별 판정
const getBendingProductJudgment = (productIdx: number): '적' | '부' | null => {
const checkCol = template.columns.find(c => c.column_type === 'check');
if (!checkCol) return null;
const cell = cellValues[`b-${productIdx}-${checkCol.id}`];
if (cell?.status === 'bad') return '부';
if (cell?.status === 'good') return '적';
return null;
};
// 종합판정
const judgments = effectiveWorkItems.map((_, idx) => getRowJudgment(idx));
const judgments = isBending && bendingProducts.length > 0
? bendingProducts.map((_, idx) => getBendingProductJudgment(idx))
: effectiveWorkItems.map((_, idx) => getRowJudgment(idx));
const overallResult = calculateOverallResult(judgments);
// 컬럼별 colspan 계산 (complex 컬럼은 sub_labels 수)
// 컬럼별 colspan 계산 (mng _colSpan 동기화)
const getColSpan = (col: (typeof template.columns)[0]) => {
if (col.column_type === 'complex' && col.sub_labels && col.sub_labels.length > 0) {
return col.sub_labels.length;
}
const label = (col.label || '').trim();
if (label.includes('검사항목') || label.includes('항목') ||
label.includes('검사기준') || label.includes('기준')) return 2;
return 1;
};
// 기본필드 값 해석 (field_key → WorkOrder 데이터 매핑)
// check 컬럼의 체크박스 라벨 추출 (sub_labels 기반, 없으면 양호/불량)
const getCheckLabels = (col: (typeof template.columns)[0]): [string, string] => {
if (col.sub_labels && col.sub_labels.length >= 2) {
const a = (col.sub_labels[0] || '').trim();
const b = (col.sub_labels[1] || '').trim();
if (a && b && !/^n?\d+$/i.test(a)) return [a, b];
}
return ['양호', '불량'];
};
// 기본필드 값 해석 (field_key 또는 label 기반 매핑)
const resolveFieldValue = (field: (typeof template.basic_fields)[0]) => {
if (!field) return '';
switch (field.field_key) {
// field_key가 있으면 field_key 기준, 없으면 label 기준 매칭
const key = field.field_key || '';
const label = (field.label || '').trim();
const LABEL_TO_KEY: Record<string, string> = {
'품명': 'product_name',
'제품명': 'product_name',
'규격': 'specification',
'수주 LOT NO': 'lot_no',
'LOT NO': 'lot_no',
'로트크기': 'lot_size',
'발주처': 'client',
'현장명': 'site_name',
'검사일자': 'inspection_date',
'검사자': 'inspector',
};
const resolvedKey = key || LABEL_TO_KEY[label] || '';
switch (resolvedKey) {
case 'product_name': return order.items?.[0]?.productName || '-';
case 'specification': return field.default_value || '-';
case 'lot_no': return order.lotNo || '-';
case 'lot_size': return `${order.items?.length || 0} 개소`;
case 'lot_size': return `${effectiveWorkItems.length || order.items?.length || 0} 개소`;
case 'client': return order.client || '-';
case 'site_name': return order.projectName || '-';
case 'inspection_date': return fullDate;
case 'inspector': return primaryAssignee;
default: return field.default_value || '(입력)';
default: return field.default_value || '-';
}
};
@@ -576,6 +802,15 @@ export const TemplateInspectionContent = forwardRef<InspectionContentRef, Templa
);
}
// POINT → 포인트 번호 표시 (mng mCell 동기화)
if (sl.includes('point') || sl.includes('포인트')) {
return (
<td key={`${col.id}-s${subIdx}`} className="border border-gray-400 px-1 py-1.5 text-center">
<span className="text-gray-400 text-[10px] italic">({subIdx + 1})</span>
</td>
);
}
// 측정값 → 입력 필드
const mIdx = inputIdx++;
return (
@@ -599,6 +834,302 @@ export const TemplateInspectionContent = forwardRef<InspectionContentRef, Templa
});
};
// 다단계 헤더 행 빌드 (group_name "/" 구분자 지원, mng renderHeaders 동기화)
const buildHeaderRows = () => {
const cols = template.columns;
if (cols.length === 0) return [];
const thCls = 'border border-gray-400 px-2 py-1.5 bg-gray-100 text-center';
const thSubCls = 'border border-gray-400 px-1 py-1 bg-gray-100 text-center text-[10px]';
// 1) group_name "/" split → depth 배열
const colGroups = cols.map(col => {
const gn = (col.group_name || '').trim();
return gn ? gn.split('/').map(s => s.trim()) : [];
});
// 단일 레벨 group_name은 그룹 행 생성 안 함 (하위 호환)
const maxDepth = Math.max(0, ...colGroups.map(g => g.length > 1 ? g.length : 0));
const needSubRow = cols.some(c =>
c.column_type === 'complex' && c.sub_labels && c.sub_labels.length > 0
);
const totalHeaderRows = maxDepth + 1 + (needSubRow ? 1 : 0);
const rows: React.ReactElement[] = [];
// 2) 그룹 행들 (maxDepth > 0일 때만)
if (maxDepth > 0) {
for (let depth = 0; depth < maxDepth; depth++) {
const cells: React.ReactElement[] = [];
let ci = 0;
while (ci < cols.length) {
const levels = colGroups[ci];
const col = cols[ci];
// 그룹 없는/단일 레벨: depth=0에서 전체 rowspan
if (levels.length <= 1) {
if (depth === 0) {
const cs = getColSpan(col);
cells.push(
<th key={`g0-${ci}`} className={thCls}
colSpan={cs > 1 ? cs : undefined}
rowSpan={totalHeaderRows}
style={col.width ? { width: col.width } : undefined}>
{col.label}
</th>
);
}
ci++; continue;
}
if (levels.length <= depth) { ci++; continue; }
// 같은 prefix 중복 방지
const prefix = levels.slice(0, depth + 1).join('/');
let isFirst = true;
for (let k = 0; k < ci; k++) {
if (colGroups[k].length > depth &&
colGroups[k].slice(0, depth + 1).join('/') === prefix) {
isFirst = false; break;
}
}
if (!isFirst) { ci++; continue; }
// colspan 합산
let span = getColSpan(col);
let cj = ci + 1;
while (cj < cols.length) {
if (colGroups[cj].length > depth &&
colGroups[cj].slice(0, depth + 1).join('/') === prefix) {
span += getColSpan(cols[cj]); cj++;
} else break;
}
// 하위 그룹 존재 여부
let hasDeeper = false;
for (let k = ci; k < cj; k++) {
if (colGroups[k].length > depth + 1) { hasDeeper = true; break; }
}
const groupLabel = levels[depth];
const rs = (!hasDeeper && depth < maxDepth - 1) ? maxDepth - depth : undefined;
cells.push(
<th key={`g-${ci}-${depth}`} className={thCls} colSpan={span} rowSpan={rs}>
{groupLabel}
</th>
);
ci = cj;
}
rows.push(<tr key={`grp-${depth}`}>{cells}</tr>);
}
}
// 3) 컬럼 라벨 행
const labelCells: React.ReactElement[] = [];
cols.forEach((col, idx) => {
const levels = colGroups[idx];
if (maxDepth > 0 && levels.length <= 1) return;
const cs = getColSpan(col);
const isComplex = col.column_type === 'complex' && col.sub_labels && col.sub_labels.length > 0;
if (needSubRow && isComplex) {
labelCells.push(
<th key={col.id} className={thCls} colSpan={cs}>{col.label}</th>
);
} else if (needSubRow) {
labelCells.push(
<th key={col.id} className={thCls}
colSpan={cs > 1 ? cs : undefined} rowSpan={2}
style={col.width ? { width: col.width } : undefined}>
{col.label}
</th>
);
} else {
labelCells.push(
<th key={col.id} className={thCls}
colSpan={cs > 1 ? cs : undefined}
style={col.width ? { width: col.width } : undefined}>
{col.label}
</th>
);
}
});
rows.push(<tr key="labels">{labelCells}</tr>);
// 4) sub_labels 행
if (needSubRow) {
const subCells: React.ReactElement[] = [];
cols.forEach(col => {
if (col.column_type === 'complex' && col.sub_labels && col.sub_labels.length > 0) {
col.sub_labels.forEach((sl, si) => {
const slLower = (sl || '').toLowerCase();
const isBasis = slLower.includes('도면') || slLower.includes('기준');
subCells.push(
<th key={`${col.id}-sh-${si}`} className={thSubCls}
style={isBasis ? { background: '#f3f4f6' } : undefined}>
{sl}
</th>
);
});
}
});
rows.push(<tr key="sublabels">{subCells}</tr>);
}
return rows;
};
// --- Bending DATA 테이블 body 렌더링 (제품별 다중 POINT 행 + rowSpan 병합) ---
const renderBendingBody = () => {
return bendingExpandedRows.map((row) => {
const { productIdx, product, pointIdx, gapPoint, isFirstRow, totalPoints } = row;
return (
<tr key={`b-${productIdx}-${pointIdx}`}>
{template.columns.map(col => {
const isGapCol = col.id === gapColumnId;
// 간격 외 컬럼: 첫 행만 렌더 (rowSpan으로 병합)
if (!isGapCol && !isFirstRow) return null;
const rs = isFirstRow && !isGapCol ? totalPoints : undefined;
const cellKey = isGapCol
? `b-${productIdx}-p${pointIdx}-${col.id}`
: `b-${productIdx}-${col.id}`;
const cell = cellValues[cellKey];
const label = col.label.trim();
// 1. 분류/제품명 (text)
if (col.column_type === 'text' && (label.includes('분류') || label.includes('제품명'))) {
return (
<td key={col.id} rowSpan={rs}
className="border border-gray-400 px-2 py-1.5 text-center align-middle text-xs"
style={col.width ? { width: col.width } : undefined}>
<div>{product.category}</div>
<div className="font-medium">{product.productName}</div>
</td>
);
}
// 2. 타입 (text)
if (col.column_type === 'text' && label === '타입') {
return (
<td key={col.id} rowSpan={rs}
className="border border-gray-400 px-2 py-1.5 text-center align-middle text-xs whitespace-pre-line"
style={col.width ? { width: col.width } : undefined}>
{product.productType}
</td>
);
}
// 3. check (절곡상태 - 양호/불량)
if (col.column_type === 'check') {
const [goodLabel, badLabel] = getCheckLabels(col);
return (
<td key={col.id} rowSpan={rs} className="border border-gray-400 p-1"
colSpan={getColSpan(col) > 1 ? getColSpan(col) : undefined}>
<div className="flex flex-col items-center gap-0.5">
<label className="flex items-center gap-0.5 cursor-pointer text-xs whitespace-nowrap">
<InspectionCheckbox
checked={cell?.status === 'good'}
onClick={() => updateCell(cellKey, { status: cell?.status === 'good' ? null : 'good' })}
readOnly={readOnly}
/>
{goodLabel}
</label>
<label className="flex items-center gap-0.5 cursor-pointer text-xs whitespace-nowrap">
<InspectionCheckbox
checked={cell?.status === 'bad'}
onClick={() => updateCell(cellKey, { status: cell?.status === 'bad' ? null : 'bad' })}
readOnly={readOnly}
/>
{badLabel}
</label>
</div>
</td>
);
}
// 4. complex 간격 (per-POINT) → POINT + 도면치수 + 측정값
if (isGapCol && col.column_type === 'complex' && col.sub_labels) {
return col.sub_labels.map((sl, si) => {
const slLower = sl.toLowerCase();
if (slLower.includes('point') || slLower.includes('포인트')) {
return (
<td key={`${col.id}-s${si}`}
className="border border-gray-400 px-1 py-1.5 text-center text-xs">
{gapPoint.point}
</td>
);
}
if (slLower.includes('도면') || slLower.includes('기준')) {
return (
<td key={`${col.id}-s${si}`}
className="border border-gray-400 px-2 py-1.5 text-center text-blue-600 font-bold text-xs">
{gapPoint.designValue}
</td>
);
}
return (
<td key={`${col.id}-s${si}`} className="border border-gray-400 p-0.5">
<input type="text" className={INPUT_CLASS}
value={cell?.measurements?.[0] || ''}
onChange={e => updateCell(cellKey, { measurements: [e.target.value, '', ''] })}
readOnly={readOnly} placeholder="측정값"
/>
</td>
);
});
}
// 5. complex 길이/너비 (merged) → 도면치수 + 측정값
if (!isGapCol && col.column_type === 'complex' && col.sub_labels) {
const isLen = label.includes('길이');
const designVal = isLen ? product.lengthDesign : product.widthDesign;
return col.sub_labels.map((sl, si) => {
const slLower = sl.toLowerCase();
if (slLower.includes('도면') || slLower.includes('기준')) {
return (
<td key={`${col.id}-s${si}`} rowSpan={rs}
className="border border-gray-400 px-2 py-1.5 text-center text-blue-600 font-bold text-xs">
{designVal}
</td>
);
}
return (
<td key={`${col.id}-s${si}`} rowSpan={rs} className="border border-gray-400 p-0.5">
<input type="text" className={INPUT_CLASS}
value={cell?.measurements?.[si] || ''}
onChange={e => {
const m: [string, string, string] = [...(cell?.measurements || ['', '', ''])] as [string, string, string];
m[si] = e.target.value;
updateCell(cellKey, { measurements: m });
}}
readOnly={readOnly} placeholder="측정값"
/>
</td>
);
});
}
// 6. 판정 (적/부)
if (isJudgmentColumn(label)) {
return <JudgmentCell key={col.id} judgment={getBendingProductJudgment(productIdx)} rowSpan={rs} />;
}
// fallback
return (
<td key={col.id} rowSpan={rs}
className="border border-gray-400 px-2 py-1.5 text-center text-xs">-</td>
);
})}
</tr>
);
});
};
return (
<div className="p-6 bg-white">
{/* ===== 헤더: KD + 회사명(좌) | 제목(중앙) | 결재라인(우) ===== */}
@@ -677,24 +1208,11 @@ export const TemplateInspectionContent = forwardRef<InspectionContentRef, Templa
{/* ===== 이미지 섹션: items 없는 섹션 ===== */}
{imageSections.map(section => (
<div key={section.id} className="mb-3">
<p className="text-sm font-bold mb-1"> {section.title || section.name}</p>
{section.image_path ? (
<img
src={getImageUrl(section.image_path)}
alt={section.title || section.name}
className="w-full border rounded"
/>
) : (
<div className="border border-dashed border-gray-300 rounded p-6 text-center text-gray-400 text-xs">
</div>
)}
</div>
<SectionImage key={section.id} section={section} />
))}
{/* ===== DATA 테이블: columns 기반 헤더 + work items 행 ===== */}
{template.columns.length > 0 && effectiveWorkItems.length > 0 && (
{template.columns.length > 0 && (isBending ? bendingProducts.length > 0 : effectiveWorkItems.length > 0) && (
<>
{dataSections.length > 0 && (
<p className="text-sm font-bold mb-1 mt-3"> {dataSections[0].title || dataSections[0].name}</p>
@@ -702,44 +1220,10 @@ export const TemplateInspectionContent = forwardRef<InspectionContentRef, Templa
<div className="overflow-x-auto">
<table className="w-full border-collapse text-xs">
<thead>
{/* 상위 헤더 */}
<tr className="bg-gray-100">
{template.columns.map(col => {
const isComplex = col.column_type === 'complex' && col.sub_labels && col.sub_labels.length > 0;
return (
<th
key={col.id}
className="border border-gray-400 px-2 py-1.5"
colSpan={getColSpan(col)}
rowSpan={isComplex ? 1 : (hasComplexColumn ? 2 : 1)}
style={col.width ? { width: col.width } : undefined}
>
{col.label}
</th>
);
})}
</tr>
{/* 하위 헤더: complex 컬럼의 sub_labels */}
{hasComplexColumn && (
<tr className="bg-gray-100">
{template.columns.map(col => {
if (col.column_type !== 'complex' || !col.sub_labels || col.sub_labels.length === 0) {
return null; // rowSpan=2로 이미 커버
}
return col.sub_labels.map((subLabel, subIdx) => (
<th
key={`${col.id}-sh-${subIdx}`}
className="border border-gray-400 px-1 py-1 text-[10px]"
>
{subLabel}
</th>
));
})}
</tr>
)}
{buildHeaderRows()}
</thead>
<tbody>
{effectiveWorkItems.map((wi, rowIdx) => (
{isBending ? renderBendingBody() : effectiveWorkItems.map((wi, rowIdx) => (
<tr key={wi.id}>
{template.columns.map(col => {
const cellKey = `${rowIdx}-${col.id}`;
@@ -759,10 +1243,12 @@ export const TemplateInspectionContent = forwardRef<InspectionContentRef, Templa
return <JudgmentCell key={col.id} judgment={getRowJudgment(rowIdx)} />;
}
// check → 양호/불량
// check → 커스텀 라벨 (mng _getCheckLabels 동기화)
if (col.column_type === 'check') {
const [goodLabel, badLabel] = getCheckLabels(col);
return (
<td key={col.id} className="border border-gray-400 p-1">
<td key={col.id} className="border border-gray-400 p-1"
colSpan={getColSpan(col) > 1 ? getColSpan(col) : undefined}>
<div className="flex flex-col items-center gap-0.5">
<label className="flex items-center gap-0.5 cursor-pointer text-xs whitespace-nowrap">
<InspectionCheckbox
@@ -770,7 +1256,7 @@ export const TemplateInspectionContent = forwardRef<InspectionContentRef, Templa
onClick={() => updateCell(cellKey, { status: cell?.status === 'good' ? null : 'good' })}
readOnly={readOnly}
/>
{goodLabel}
</label>
<label className="flex items-center gap-0.5 cursor-pointer text-xs whitespace-nowrap">
<InspectionCheckbox
@@ -778,7 +1264,7 @@ export const TemplateInspectionContent = forwardRef<InspectionContentRef, Templa
onClick={() => updateCell(cellKey, { status: cell?.status === 'bad' ? null : 'bad' })}
readOnly={readOnly}
/>
{badLabel}
</label>
</div>
</td>
@@ -793,7 +1279,8 @@ export const TemplateInspectionContent = forwardRef<InspectionContentRef, Templa
// select (판정 외) → 텍스트 입력
if (col.column_type === 'select') {
return (
<td key={col.id} className="border border-gray-400 p-0.5">
<td key={col.id} className="border border-gray-400 p-0.5"
colSpan={getColSpan(col) > 1 ? getColSpan(col) : undefined}>
<input
type="text"
className={INPUT_CLASS}
@@ -808,7 +1295,8 @@ export const TemplateInspectionContent = forwardRef<InspectionContentRef, Templa
// text/기타 → 텍스트 입력
return (
<td key={col.id} className="border border-gray-400 p-0.5">
<td key={col.id} className="border border-gray-400 p-0.5"
colSpan={getColSpan(col) > 1 ? getColSpan(col) : undefined}>
<input
type="text"
className={INPUT_CLASS}