fix: API 응답 파싱 오류 수정 및 에러 처리 개선

주요 변경사항:
- 창고 관리 API 응답 구조와 DTO 불일치 수정
  - WarehouseLocationDto에 code, manager_phone 필드 추가
  - RemoteDataSource에서 API 응답을 DTO 구조에 맞게 변환
- 회사 관리 API 응답 파싱 오류 수정
  - CompanyResponse의 필수 필드를 nullable로 변경
  - PaginatedResponse 구조 매핑 로직 개선
- 에러 처리 및 로깅 개선
  - Service Layer에 상세 에러 로깅 추가
  - Controller에서 에러 타입별 처리
- 새로운 유틸리티 추가
  - ResponseInterceptor: API 응답 정규화
  - DebugLogger: 디버깅 도구
  - HealthCheckService: 서버 상태 확인
- 문서화
  - API 통합 테스트 가이드
  - 에러 분석 보고서
  - 리팩토링 계획서
This commit is contained in:
JiWoong Sul
2025-07-31 19:15:39 +09:00
parent ad2c699ff7
commit f08b7fec79
89 changed files with 10521 additions and 892 deletions

447
CLAUDE.md
View File

@@ -1,174 +1,331 @@
# CLAUDE.md
# Claude Code Global Development Rules
이 파일은 Claude Code (claude.ai/code)가 SuperPort 프로젝트에서 작업할 때 필요한 가이드라인을 제공합니다.
## 🌐 Language Settings
- **All answers and explanations must be provided in Korean**
- **Variable and function names in code should use English**
- **Error messages should be explained in Korean**
## 🎯 프로젝트 개요
## 🤖 Agent Selection Rules
- **Always select and use a specialized agent appropriate for the task**
**SuperPort**는 Flutter 기반 장비 관리 ERP 시스템으로, 웹과 모바일 플랫폼을 지원합니다.
## 🎯 Mandatory Response Format
### 주요 기능
- 장비 입출고 관리 및 이력 추적
- 회사/지점 계층 구조 관리
- 사용자 권한 관리 (관리자/일반)
- 유지보수 라이선스 관리
- 창고 위치 관리
Before starting any task, you MUST respond in the following format:
### 기술 스택
- **Frontend**: Flutter (Web + Mobile)
- **State Management**: Custom Controller Pattern
- **Data Layer**: MockDataService (API 연동 준비됨)
- **UI Theme**: Shadcn Design System
- **Localization**: 한국어 우선, 영어 지원
## 📂 프로젝트 구조
### 아키텍처 개요
```
lib/
├── models/ # 데이터 모델 (JSON serialization 포함)
├── services/ # 비즈니스 로직 서비스
│ └── mock_data_service.dart # Singleton 패턴 Mock 데이터
├── screens/ # 화면별 디렉토리
│ ├── equipment/ # 장비 관리
│ ├── company/ # 회사/지점 관리
│ ├── user/ # 사용자 관리
│ ├── license/ # 라이선스 관리
│ ├── warehouse/ # 창고 관리
│ └── common/ # 공통 컴포넌트
│ ├── layouts/ # AppLayoutRedesign (사이드바 네비게이션)
│ └── custom_widgets/ # 재사용 위젯
└── theme/ # theme_shadcn.dart (커스텀 테마)
[Model Name] - [Agent Name]. I have reviewed all the following rules: [rule file list or categories]. Proceeding with the task. Master!
```
### 상태 관리 패턴
- **Controller Pattern** 사용 (Provider 대신)
- 각 화면마다 전용 Controller 구현
- 위치: `lib/screens/*/controllers/`
- 예시: `EquipmentInController`, `CompanyController`
**Agent Names:**
- **Direct Implementation**: Perform direct implementation tasks
- **Master Manager**: Overall project management and coordination
- **flutter-ui-designer**: Flutter UI/UX design
- **flutter-architecture-designer**: Flutter architecture design
- **flutter-offline-developer**: Flutter offline functionality development
- **flutter-network-engineer**: Flutter network implementation
- **flutter-qa-engineer**: Flutter QA/testing
- **app-launch-validator**: App launch validation
- **aso-optimization-expert**: ASO optimization
- **mobile-growth-hacker**: Mobile growth strategy
- **Idea Analysis**: Idea analysis
- **mobile app mvp planner**: MVP planning
## 💼 비즈니스 엔티티
**Examples:**
- `Claude Opus 4 - Direct Implementation. I have reviewed all the following rules: development guidelines, class structure, testing rules. Proceeding with the task. Master!`
- `Claude Opus 4 - flutter-network-engineer. I have reviewed all the following rules: API integration, error handling, network optimization. Proceeding with the task. Master!`
- For extensive rules: `coding style, class design, exception handling, testing rules` (categorized summary)
### 1. Equipment (장비)
- 제조사, 이름, 카테고리 (대/중/소)
- 시리얼 번호가 있으면 수량 = 1 (수정 불가)
- 시리얼 번호가 없으면 복수 수량 가능
- 입출고 이력: 'I' (입고), 'O' (출고)
### 2. Company (회사)
- 본사/지점 계층 구조
- 지점별 독립된 주소와 연락처
- 회사 → 지점들 관계
### 3. User (사용자)
- 회사 연결
- 권한 레벨: 'S' (관리자), 'M' (일반)
## 🚀 Mandatory 3-Phase Task Process
### 4. License (라이선스)
- 유지보수 라이선스
- 기간 및 방문 주기 관리
### Phase 1: Codebase Exploration & Analysis
**Required Actions:**
- Systematically discover ALL relevant files, directories, modules
- Search for related keywords, functions, classes, patterns
- Thoroughly examine each identified file
- Document coding conventions and style guidelines
- Identify framework/library usage patterns
- Map dependencies and architectural structure
## 🛠 개발 명령어
### Phase 2: Implementation Planning
**Required Actions:**
- Create detailed implementation roadmap based on Phase 1 findings
- Define specific task lists and acceptance criteria per module
- Specify performance/quality requirements
- Plan test strategy and coverage
- Identify potential risks and edge cases
```bash
# 개발 실행
flutter run
### Phase 3: Implementation Execution
**Required Actions:**
- Implement each module following Phase 2 plan
- Verify ALL acceptance criteria before proceeding
- Ensure adherence to conventions identified in Phase 1
- Write tests alongside implementation
- Document complex logic and design decisions
# 빌드
flutter build web # 웹 배포
flutter build apk # Android APK
flutter build ios # iOS (macOS 필요)
## ✅ Core Development Principles
# 코드 품질
flutter analyze # 정적 분석
flutter format . # 코드 포맷팅
### Language & Documentation Rules
- **Code, variables, and identifiers**: Always in English
- **Comments and documentation**: Use project's primary spoken language
- **Commit messages**: Use project's primary spoken language
- **Error messages**: Bilingual when appropriate (technical term + native explanation)
# 의존성
flutter pub get # 설치
flutter pub upgrade # 업그레이드
### Type Safety Rules
- **Always declare types explicitly** for variables, parameters, and return values
- Avoid `any`, `dynamic`, or loosely typed declarations (except when strictly necessary)
- Define **custom types/interfaces** for complex data structures
- Use **enums** for fixed sets of values
- Extract magic numbers and literals into named constants
# 테스트
flutter test # 테스트 실행
### Naming Conventions
|Element|Style|Example|
|---|---|---|
|Classes/Interfaces|`PascalCase`|`UserService`, `DataRepository`|
|Variables/Methods|`camelCase`|`userName`, `calculateTotal`|
|Constants|`UPPERCASE` or `PascalCase`|`MAX_RETRY_COUNT`, `DefaultTimeout`|
|Files (varies by language)|Follow language convention|`user_service.py`, `UserService.java`|
|Boolean variables|Verb-based|`isReady`, `hasError`, `canDelete`|
|Functions/Methods|Start with verbs|`executeLogin`, `saveUser`, `validateInput`|
**Critical Rules:**
- Use meaningful, descriptive names
- Avoid abbreviations unless widely accepted: `i`, `j`, `err`, `ctx`, `API`, `URL`
- Name length should reflect scope (longer names for wider scope)
## 🔧 Function & Method Design
### Function Structure Principles
- **Keep functions short and focused** (≤20 lines recommended)
- **Follow Single Responsibility Principle (SRP)**
- **Minimize parameters** (≤3 ideal, use objects for more)
- **Avoid deeply nested logic** (≤3 levels)
- **Use early returns** to reduce complexity
- **Extract complex conditions** into well-named functions
### Function Optimization Techniques
- Prefer **pure functions** without side effects
- Use **default parameters** to reduce overloading
- Apply **RO-RO pattern** (Receive Object Return Object) for complex APIs
- **Cache expensive computations** when appropriate
- **Avoid premature optimization** - profile first
## 📦 Data & Class Design
### Class Design Principles
- **Single Responsibility Principle (SRP)**: One class, one purpose
- **Favor composition over inheritance**
- **Program to interfaces**, not implementations
- **Keep classes cohesive** - high internal, low external coupling
- **Prefer immutability** when possible
### File Size Management
**Guidelines (not hard limits):**
- Classes: ≤200 lines
- Functions: ≤20 lines
- Files: ≤300 lines
**Split when:**
- Multiple responsibilities exist
- Excessive scrolling required
- Pattern duplication occurs
- Testing becomes complex
### Data Model Design
- **Encapsulate validation** within data models
- **Use Value Objects** for complex primitives
- **Apply Builder pattern** for complex object construction
- **Implement proper equals/hashCode** for data classes
## ❗ Exception Handling
### Exception Usage Principles
- Use exceptions for **exceptional circumstances only**
- **Fail fast** at system boundaries
- **Catch exceptions only when you can handle them**
- **Add context** when re-throwing
- **Use custom exceptions** for domain-specific errors
- **Document thrown exceptions**
### Error Handling Strategies
- Return **Result/Option types** for expected failures
- Use **error codes** for performance-critical paths
- Implement **circuit breakers** for external dependencies
- **Log errors appropriately** (error level, context, stack trace)
## 🧪 Testing Strategy
### Test Structure
- Follow **Arrange-Act-Assert (AAA)** pattern
- Use **descriptive test names** that explain what and why
- **One assertion per test** (when practical)
- **Test behavior, not implementation**
### Test Coverage Guidelines
- **Unit tests**: All public methods and edge cases
- **Integration tests**: Critical paths and external integrations
- **End-to-end tests**: Key user journeys
- Aim for **80%+ code coverage** (quality over quantity)
### Test Best Practices
- **Use test doubles** (mocks, stubs, fakes) appropriately
- **Keep tests independent** and idempotent
- **Test data builders** for complex test setups
- **Parameterized tests** for multiple scenarios
- **Performance tests** for critical paths
## 📝 Version Control Guidelines
### Commit Best Practices
- **Atomic commits**: One logical change per commit
- **Frequent commits**: Small, incremental changes
- **Clean history**: Use interactive rebase when needed
- **Branch strategy**: Follow project's branching model
### Commit Message Format
```
type(scope): brief description
Detailed explanation if needed
- Bullet points for multiple changes
- Reference issue numbers: #123
BREAKING CHANGE: description (if applicable)
```
## 📐 코딩 컨벤션
### Commit Types
- `feat`: New feature
- `fix`: Bug fix
- `refactor`: Code refactoring
- `perf`: Performance improvement
- `test`: Test changes
- `docs`: Documentation
- `style`: Code formatting
- `chore`: Build/tooling changes
### 네이밍 규칙
- **파일**: snake_case (`equipment_list.dart`)
- **클래스**: PascalCase (`EquipmentInController`)
- **변수/메서드**: camelCase (`userName`, `calculateTotal`)
- **Boolean**: 동사 기반 (`isReady`, `hasError`)
## 🏗️ Architecture Guidelines
### 파일 구조
- 300줄 초과 시 기능별 분리 고려
- 모델별 파일 분리 (`equipment.dart` vs `equipment_in.dart`)
- 재사용 컴포넌트는 `custom_widgets/`로 추출
### Clean Architecture Principles
- **Dependency Rule**: Dependencies point inward
- **Layer Independence**: Each layer has single responsibility
- **Testability**: Business logic independent of frameworks
- **Framework Agnostic**: Core logic doesn't depend on external tools
### UI 가이드라인
- **Metronic Admin Template** 디자인 패턴 준수
- **Material Icons** 사용
- **ShadcnCard**: 일관된 카드 스타일
- **FormFieldWrapper**: 폼 필드 간격
- 반응형 디자인 (웹/모바일)
### Common Architectural Patterns
- **Repository Pattern**: Abstract data access
- **Service Layer**: Business logic coordination
- **Dependency Injection**: Loose coupling
- **Event-Driven**: For asynchronous workflows
- **CQRS**: When read/write separation needed
## 🚀 구현 가이드
### 새 기능 추가 순서
1. `lib/models/`에 모델 생성
2. `MockDataService`에 목 데이터 추가
3. 화면 디렉토리에 Controller 생성
4. 목록/폼 화면 구현
5. `AppLayoutRedesign`에 네비게이션 추가
### 폼 구현 팁
- 필수 필드 검증
- 날짜 선택: 과거 날짜만 허용 (이력 기록용)
- 카테고리: 계층적 드롭다운 (대→중→소)
- 생성/수정 모드 모두 처리
## 📋 현재 상태
### ✅ 구현 완료
- 로그인 화면 (Mock 인증)
- 메인 레이아웃 (사이드바 네비게이션)
- 모든 엔티티 CRUD
- 한국어/영어 다국어 지원
- 반응형 디자인
- Mock 데이터 서비스
### 🔜 구현 예정
- API 연동
- 실제 인증
- 바코드 스캔
- 테스트 커버리지
- 장비 보증 추적
- PDF 내보내기 (의존성 준비됨)
## 🔍 디버깅 팁
- 데이터 문제: `MockDataService` 확인
- 비즈니스 로직: Controller 확인
- 정적 분석: `flutter analyze`
- 웹 문제: 브라우저 콘솔 확인
## 💬 응답 규칙
### 언어 설정
- **코드/변수명**: 영어
- **주석/문서/응답**: 한국어
- 기술 용어는 영어 병기 가능
### Git 커밋 메시지
### Module Organization
```
type: 간단한 설명 (한국어)
선택적 상세 설명
src/
├── domain/ # Business entities and rules
├── application/ # Use cases and workflows
├── infrastructure/ # External dependencies
├── presentation/ # UI/API layer
└── shared/ # Cross-cutting concerns
```
**타입**:
- `feat`: 새 기능
- `fix`: 버그 수정
- `refactor`: 리팩토링
- `docs`: 문서 변경
- `test`: 테스트
- `chore`: 빌드/도구
## 🔄 Safe Refactoring Practices
**주의**: AI 도구 속성 표시 금지
### Preventing Side Effects During Refactoring
- **Run all tests before and after** every refactoring step
- **Make incremental changes**: One small refactoring at a time
- **Use automated refactoring tools** when available (IDE support)
- **Preserve existing behavior**: Refactoring should not change functionality
- **Create characterization tests** for legacy code before refactoring
- **Use feature flags** for large-scale refactorings
- **Monitor production metrics** after deployment
### Refactoring Checklist
1. **Before Starting**:
- [ ] All tests passing
- [ ] Understand current behavior completely
- [ ] Create backup branch
- [ ] Document intended changes
2. **During Refactoring**:
- [ ] Keep commits atomic and reversible
- [ ] Run tests after each change
- [ ] Verify no behavior changes
- [ ] Check for performance impacts
3. **After Completion**:
- [ ] All tests still passing
- [ ] Code coverage maintained or improved
- [ ] Performance benchmarks verified
- [ ] Peer review completed
### Common Refactoring Patterns
- **Extract Method**: Break large functions into smaller ones
- **Rename**: Improve clarity with better names
- **Move**: Relocate code to appropriate modules
- **Extract Variable**: Make complex expressions readable
- **Inline**: Remove unnecessary indirection
- **Extract Interface**: Decouple implementations
## 🧠 Continuous Improvement
### Code Review Focus Areas
- **Correctness**: Does it work as intended?
- **Clarity**: Is it easy to understand?
- **Consistency**: Does it follow conventions?
- **Completeness**: Are edge cases handled?
- **Performance**: Are there obvious bottlenecks?
- **Security**: Are there vulnerabilities?
- **Side Effects**: Are there unintended consequences?
### Knowledge Sharing
- **Document decisions** in ADRs (Architecture Decision Records)
- **Create runbooks** for operational procedures
- **Maintain README** files for each module
- **Share learnings** through team discussions
- **Update rules** based on team consensus
## ✅ Quality Validation Checklist
Before completing any task, confirm:
### Phase Completion
- [ ] Phase 1: Comprehensive analysis completed
- [ ] Phase 2: Detailed plan with acceptance criteria
- [ ] Phase 3: Implementation meets all criteria
### Code Quality
- [ ] Follows naming conventions
- [ ] Type safety enforced
- [ ] Single Responsibility maintained
- [ ] Proper error handling
- [ ] Adequate test coverage
- [ ] Documentation complete
### Best Practices
- [ ] No code smells or anti-patterns
- [ ] Performance considerations addressed
- [ ] Security vulnerabilities checked
- [ ] Accessibility requirements met
- [ ] Internationalization ready (if applicable)
## 🎯 Success Metrics
### Code Quality Indicators
- **Low cyclomatic complexity** (≤10 per function)
- **High cohesion**, low coupling
- **Minimal code duplication** (<5%)
- **Clear separation of concerns**
- **Consistent style throughout**
### Professional Standards
- **Readable**: New developers understand quickly
- **Maintainable**: Changes are easy to make
- **Testable**: Components tested in isolation
- **Scalable**: Handles growth gracefully
- **Reliable**: Fails gracefully with clear errors
---
**Remember**: These are guidelines, not rigid rules. Use professional judgment and adapt to project needs while maintaining high quality standards.