# CLAUDE.md This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## Project Architecture This is a multi-application Laravel-based SAM (Smart Application Management) system consisting of: ### Core Applications - **admin/** - Laravel 12 application with Filament admin panel for tenant management - **api/** - Laravel 12 REST API backend with comprehensive API endpoints and Swagger documentation - **front/** - CodeIgniter 3 frontend application - `front/www/` - Main CodeIgniter application directory - `front/_Codeigniter/` - CodeIgniter 3 system files (extracted from www) - **5130/** - Legacy PHP application for construction/manufacturing management - **docker/** - Docker configuration files - **mng/** - MNG admin panel (Plain Laravel, DaisyUI) ### Key Features & Components - Multi-tenant architecture with tenant switching capabilities - Role-based access control (RBAC) with permissions and departments - Product management with BOM (Bill of Materials) support - Material management and inventory tracking - File upload and management system - Category management with templates and versioning - Design workflow with version control and audit logging ### Models Structure (독립 운영) **중요**: 각 프로젝트는 독립적인 모델을 사용합니다. - **admin/app/Models/** - Admin 프로젝트 전용 모델 (Filament 통합) - **api/app/Models/** - API 프로젝트 전용 모델 (REST API) - **mng/app/Models/** - MNG 프로젝트 전용 모델 (관리자 패널) **이전 shared/ 구조는 각 프로젝트로 이관 완료되었습니다.** ## Development Commands ### Admin Application (admin/) ```bash # Development server with all services composer dev # Individual services php artisan serve # Laravel server php artisan queue:listen --tries=1 # Queue worker php artisan pail --timeout=0 # Log viewer npm run dev # Vite dev server # Testing composer test php artisan test # Code quality ./vendor/bin/pint # PHP CS Fixer ``` ### API Application (api/) ```bash # Development server with all services composer dev # API documentation # Access Swagger UI at: /api-docs/index.html (root redirects here) # JSON spec at: /docs/api-docs.json # Database php artisan migrate php artisan migrate:generate # Generate migrations from existing DB # Development tools php artisan ide-helper:generate php artisan ide-helper:models ``` ### Frontend Application (front/www/) ```bash # CodeIgniter 3 application composer install # Install PHP dependencies php -S localhost:8080 # Built-in development server # Note: front/_Codeigniter/ contains the extracted CI3 system files # Main application is in front/www/ directory ``` ### Build and Assets ```bash # Frontend assets (both admin and api) npm run build # Production build npm run dev # Development with hot reload # In individual directories cd admin && npm run build cd api && npm run build ``` ## API Structure & Authentication ### Authentication Flow 1. **API Key Authentication** - All endpoints require valid API key via `auth.apikey` middleware 2. **User Authentication** - POST `/v1/login` returns Sanctum token 3. **Protected Routes** - Use `auth:sanctum` middleware for user-specific operations ### Core API Endpoints (v1/) - **Auth**: `/v1/login`, `/v1/logout`, `/v1/signup` - **Users**: `/v1/users/*` - User management and profile operations - **Tenants**: `/v1/tenants/*` - Multi-tenant operations and switching - **Admin**: `/v1/admin/*` - Tenant user administration - **Products**: `/v1/products/*` - Product catalog with BOM support - **Materials**: `/v1/materials/*` - Material management - **Categories**: `/v1/categories/*` - Hierarchical category management - **Files**: `/v1/file/*` - File upload and management - **Design**: `/v1/design/*` - Design workflow and versioning ### Permission System - Menu-based permissions with role inheritance - Department-based access control - Multi-level permission matrix (user → role → department → menu) ## Database & Models ### Multi-tenant Data Architecture - Tenant isolation via `tenant_id` columns with BelongsToTenant global scope - 각 프로젝트는 독립적인 모델 사용 (admin, api, mng) - Global admin tables for system management - Soft deletes (`deleted_at`) applied across most entities - Common audit columns: `created_by`, `updated_by`, `deleted_by` ### Core Tables & Relationships #### Authentication & Authorization - **`api_keys`** - API key management with active status - **`users`** - User accounts with soft deletes - **`user_tenants`** - Many-to-many user-tenant relationships with active/default flags - **`personal_access_tokens`** - Sanctum token storage - **`permissions`** - Role-based permissions with tenant scoping - **`roles`** - Tenant-scoped roles - **`model_has_permissions/roles`** - Spatie permission assignments - **`permission_overrides`** - Manual permission allow/deny with temporal validity #### Multi-tenant Organization - **`tenants`** - Company/organization master with subscription info - **`tenant_user_profiles`** - Extended user profiles per tenant - **`departments`** - Hierarchical organizational structure - **`department_user`** - User-department assignments with primary department flag #### Product Management - **`categories`** - Hierarchical product categorization with soft deletes - **`category_fields`** - Dynamic field definitions per category - **`category_templates`** - Versioned category field snapshots - **`products`** - Product catalog with type classification (PRODUCT/PART/SUBASSEMBLY) - **`product_components`** - BOM relationships (MATERIAL|PRODUCT references) - **`materials`** - Material master with dynamic attributes - **`classifications`** - Flat code tables by group (product_type, payment_method, etc.) #### Design & Manufacturing - **`models`** - Design model master with lifecycle status - **`model_versions`** - Versioned model releases with DRAFT/RELEASED status - **`bom_templates`** - BOM templates linked to model versions - **`bom_template_items`** - Template BOM line items with quantities and waste rates #### Orders & Operations - **`orders`** - Order/quotation master with workflow status - **`order_items`** - Order line items with design codes - **`order_item_components`** - Required materials/products per order item - **`order_histories`** - Order change tracking and notes - **`clients`** - Customer/vendor master #### Inventory & Materials - **`material_receipts`** - Incoming material receipts with lot tracking - **`material_inspections`** - Quality inspection records - **`material_inspection_items`** - Inspection checklist items - **`lots`** - Material lot management - **`lot_sales`** - Lot consumption tracking - **`price_histories`** - Historical pricing with temporal validity #### System & Configuration - **`common_codes`** - Hierarchical master codes with tenant support - **`files`** - Polymorphic file attachments - **`audit_logs`** - Comprehensive audit trail with 13-month retention - **`setting_field_defs`** - Global field definitions - **`tenant_field_settings`** - Tenant-specific field configurations - **`tenant_option_groups/values`** - Tenant-managed dropdown options #### Content Management - **`boards`** - Configurable board system - **`posts`** - Board posts with custom fields - **`board_settings`** - Dynamic field definitions per board - **`board_comments`** - Hierarchical commenting system ### Key Model Relationships - **Tenant → Users** (many-to-many via user_tenants) - **Products ↔ Materials** (via product_components with ref_type) - **Models → Versions → BOM Templates** (design workflow) - **Orders → Items → Components** (order breakdown) - **Categories ↔ Fields ↔ Templates** (dynamic forms with versioning) - **Audit Logs** (polymorphic tracking across all major entities) ## Legacy Integration (5130/) The `5130/` directory contains a large legacy PHP application for: - Construction/manufacturing workflow management - Equipment and material tracking - Work order processing - Financial calculations and reporting Key legacy components: - **dbeditor/** - Database administration tools - **estimate/** - Cost estimation system - **output/** - Report generation - Various specialized modules for construction processes ## File Organization ### Configuration - Environment files: `.env` in each application directory - Docker configs: `docker/` directory - Asset building: `vite.config.js` and `tailwind.config.js` in each app ### Testing - PHPUnit configuration: `phpunit.xml` in each Laravel app - Test directories: `tests/` in Laravel applications ## SAM 프로젝트 권장 워크플로우 ### 1. 기능 개발 워크플로우 (Feature Development) 새로운 기능 개발 시 API-First 접근 방식을 따릅니다: ``` 1. 기획 및 분석 - CURRENT_WORKS.md에 작업 계획 작성 - 영향받는 저장소 식별 (api/admin/front) - 데이터베이스 스키마 변경 필요성 검토 2. 개발 환경 준비 - git status로 모든 저장소 상태 확인 - Docker 서비스 실행 확인 (composer dev) - 마이그레이션 상태 확인 (php artisan migrate:status) 3. API 우선 개발 (API-First) - Service 클래스 구현 (비즈니스 로직) - Controller 구현 (FormRequest + ApiResponse) - Swagger 문서 작성 - API 테스트 (Postman/Swagger UI) 4. Frontend 연동 - Admin 패널 (Filament) 구현 - 각 프로젝트는 독립적인 모델 사용 5. 품질 검증 - API 테스트 실행 - Pint 코드 포맷팅 (./vendor/bin/pint) - Swagger 문서 검토 6. 커밋 및 정리 - CURRENT_WORKS.md 업데이트 - 저장소별 순차 커밋 - 임시 파일 정리 ``` **확인 포인트**: API 개발 완료 후 → Frontend 연동 진행 여부 확인 ### 2. 버그 수정 워크플로우 (Bugfix) ``` 1. 문제 식별 - 에러 로그 확인 (Laravel 로그, 브라우저 콘솔) - 영향 범위 파악 (어떤 저장소/컴포넌트) - 재현 방법 문서화 2. 핫픽스 브랜치 생성 (긴급시) - git checkout -b hotfix/issue-description - 수정 범위를 최소화 3. 수정 구현 - 근본 원인 해결 (임시방편 금지) - 관련 테스트 케이스 추가 - 감사 로그 영향 고려 4. 검증 및 배포 - 로컬 테스트 완료 - Swagger 문서 업데이트 (API 변경시) - 프로덕션 배포 후 모니터링 ``` **확인 포인트**: 긴급도에 따른 핫픽스 브랜치 생성 여부 확인 ### 3. 데이터베이스 변경 워크플로우 ``` 1. 마이그레이션 설계 - 기존 데이터 호환성 검토 - 롤백 시나리오 준비 - 멀티테넌트 영향도 분석 2. 개발 환경 테스트 - php artisan migrate:status 확인 - 테스트 데이터로 마이그레이션 검증 - 롤백 테스트 수행 3. 모델 업데이트 - Eloquent 모델 수정 - BelongsToTenant 스코프 확인 - 감사 로그 설정 점검 4. API 영향도 점검 - 기존 API 호환성 확인 - Swagger 스키마 업데이트 - 버전 호환성 고려 ``` **확인 포인트**: 마이그레이션 실행 전 백업 완료 확인 ### 4. 멀티 저장소 동기화 워크플로우 (상시 적용) ``` 작업 순서: api (백엔드) → admin (관리 UI) → mng (MNG 관리 UI) 의존성 관리: - API 변경사항 완료 후 Frontend 작업 - 각 프로젝트는 독립적인 모델 사용 (동기화 불필요) - Docker 설정 변경 시 전체 재시작 통합 테스트: - API → Admin 패널 → 사용자 화면 순서로 테스트 - 권한 및 멀티테넌트 기능 검증 ``` ### 5. 코드 리뷰 및 품질 관리 (상시 적용) **코드 품질 체크리스트:** ``` □ SAM API Development Rules 준수 □ Service-First 아키텍처 (Controller는 단순) □ FormRequest 검증 사용 □ i18n 메시지 키 사용 (__('message.xxx')) □ Swagger 문서 완성도 □ 멀티테넌트 스코프 적용 (BelongsToTenant) □ 감사 로그 고려 □ Soft Delete 적용 □ 테스트 케이스 작성 □ Pint 포맷팅 적용 ``` ### 6. 배포 준비 워크플로우 ``` 1. 코드 검증 - 모든 테스트 통과 - Swagger 문서 최신화 - 환경변수 설정 확인 2. 데이터베이스 - 마이그레이션 순서 확인 - 백업 계획 수립 - 롤백 시나리오 준비 3. 문서화 - CURRENT_WORKS.md 최종 업데이트 - API 변경사항 문서화 - 배포 노트 작성 ``` **확인 포인트**: 배포 전 마지막 체크리스트 확인 ### 워크플로우 진행 방식 - **1~3번**: 시작부터 완료까지 연속 진행 (중간 확인 포인트에서 사용자 확인) - **4~5번**: 상시 적용 (작업할 때마다 자동 적용) - **6번**: 배포 시에만 적용 ### SuperClaude 활용 전략 각 개발 단계별로 SuperClaude 프레임워크를 전략적으로 활용합니다: #### 🎯 기획 단계 (SuperClaude 필수) ``` /sc:business-panel @requirements.md - 비즈니스 전문가 패널을 통한 요구사항 분석 - Porter, Drucker, Collins 등 전문가 관점으로 기능 검증 - 시장 적합성 및 비즈니스 가치 평가 - 우선순위 및 리소스 배분 결정 ``` #### 🔧 백엔드 개발 (SuperClaude 적극 활용) ``` /sc:architect --system --api-design - 시스템 아키텍처 설계 및 검토 - API 설계 패턴 최적화 - 데이터베이스 스키마 설계 - 성능 및 확장성 고려사항 /sc:security-engineer --api-security - API 보안 취약점 분석 - 멀티테넌트 보안 설계 - 인증/인가 시스템 검증 - 감사 로그 보안 검토 ``` #### 🎨 프론트엔드 개발 (SuperClaude 부분 활용) ``` /sc:frontend-architect --ui-design --accessibility - UI/UX 아키텍처 설계 - 접근성 및 사용성 검증 - 컴포넌트 재사용성 최적화 - 반응형 디자인 전략 Magic MCP 활용: - /ui 명령어로 21st.dev 패턴 기반 컴포넌트 생성 - 현대적이고 접근성 높은 UI 구현 ``` #### ✅ 검증 단계 (SuperClaude 필수) ``` /sc:quality-engineer --comprehensive-testing - 테스트 전략 수립 및 검증 - 코드 품질 메트릭 분석 - 성능 테스트 설계 - 엣지 케이스 식별 /sc:security-engineer --penetration-testing - 보안 취약점 스캔 - 멀티테넌트 격리 검증 - API 보안 테스트 - 데이터 보호 검증 /sc:business-panel --quality-validation - 비즈니스 요구사항 충족도 검증 - 사용자 관점 품질 평가 - ROI 및 비즈니스 가치 측정 ``` #### 🚀 배포 준비 (SuperClaude 선택적 활용) ``` /sc:devops-architect --deployment-strategy - 배포 전략 최적화 - 인프라 자동화 검토 - 모니터링 및 로깅 설정 - 롤백 시나리오 검증 ``` ### SuperClaude 모드별 활용 가이드 #### 🔥 고강도 작업 (--ultrathink) - 복잡한 시스템 설계 - 대규모 리팩토링 - 보안 아키텍처 설계 - 성능 최적화 #### 🎯 중강도 작업 (--think-hard) - API 설계 및 검토 - 데이터베이스 스키마 변경 - 비즈니스 로직 구현 - 테스트 전략 수립 #### 💡 일반 작업 (--think) - 기능 구현 - 버그 수정 - 코드 리뷰 - 문서 작성 ### 자동 SuperClaude 활성화 조건 다음 상황에서 자동으로 SuperClaude를 활성화합니다: **기획 단계:** - 새로운 기능 요구사항 분석 시 - 비즈니스 프로세스 변경 시 - 시장 적합성 검토 시 **백엔드 개발:** - 새로운 API 엔드포인트 설계 시 - 데이터베이스 스키마 변경 시 - 보안 관련 기능 구현 시 - 성능 최적화 작업 시 **프론트엔드 개발:** - 새로운 UI 컴포넌트 설계 시 - 사용자 경험 개선 작업 시 - 접근성 요구사항 구현 시 **검증 단계:** - 품질 보증 체크리스트 실행 시 - 보안 검증 작업 시 - 성능 테스트 수행 시 - 비즈니스 요구사항 검증 시 ## Development Workflow (기본 환경 설정) 1. **Environment Setup**: Configure `.env` files for each application 2. **Database**: Run migrations in both admin and api applications 3. **Dependencies**: `composer install` and `npm install` in relevant directories 4. **Development**: Use `composer dev` to run all services concurrently 5. **API Testing**: Access Swagger documentation for API endpoints 6. **Code Quality**: Run Pint for PHP formatting ## SAM API Development Rules ### 1. Architecture Philosophy - **Service First**: All business logic must be written in Service classes (public functions) - **Controller**: Only responsible for DI injection of Services and calling them. Use ApiResponse::handle() for responses - **Import**: `use App\Helpers\ApiResponse;` (⚠️ 반드시 이 경로 사용) - **Exception Flow**: Errors are thrown → converted to JSON by global handler - **Context Enforcement**: Base Service requires tenantId(), apiUserId(). Throws exception if not set ### 2. Multi-tenancy & Models - BelongsToTenant global scope applied - ModelTrait for is_active, date handling - SoftDeletes by default - Common columns: tenant_id, created_by, updated_by, deleted_by (COMMENT required) - FK constraints: Created during design, minimal in production ### 3. Middleware Stack - ApiKeyMiddleware, CheckSwaggerAuth, CorsMiddleware, CheckPermission, PermMapper - Default route group: auth.apikey (some with auth:sanctum) ### 4. Routing (v1) - Auth, Common codes, Files, Tenants, Users (me/tenants/switch), Menus+Permissions, Roles/Permissions, Departments, Field settings, Options, Categories, Classifications, Products, BOM - REST conventions: index/show/store/update/destroy + extensions (toggle, bulkUpsert, reorder) ### 5. Controller/Service Rules - **Controller**: FormRequest type-hint → only pass $request->validated() to Service - **Service**: extends Service, tenantId()/apiUserId() required - **Lists**: Pagination, explicit search parameters - **Responses**: {success, message, data}, message must be i18n key only ### 6. i18n & Response Messages - Messages: lang/{locale}/message.php - Errors: lang/{locale}/error.php - **Rule**: No direct strings, must use __('message.xxx'), __('error.xxx') - Common keys: message.fetched/created/updated/deleted/bulk_upsert/reordered - Resource-specific keys allowed: message.product.created, message.bom.bulk_upsert ### 7. Swagger Documentation (l5-swagger 9.0) - **Structure**: Swagger annotations are written in separate PHP class files under `app/Swagger/v1/` - **File Naming**: `{Resource}Api.php` (e.g., CategoryApi.php, ClientApi.php, ProductApi.php) - **Controller Clean**: Controllers contain ONLY business logic, NO Swagger annotations - **Tags**: Resource-based (User, Auth, Product, BOM, Client...) - **Security**: ApiKeyAuth + BearerAuth - **Schemas**: Define in Swagger files - Resource model, Pagination, CreateRequest, UpdateRequest - **Methods**: Define empty methods for each endpoint with full @OA annotations - **Specifications**: Clear Path/Query/Body parameters with examples - **No duplicate schemas**, accurate nullable/oneOf distinctions - **Regeneration**: Run `php artisan l5-swagger:generate` after creating/updating Swagger files **Swagger File Structure Example**: ```php ``` #### Commit Types - `feat`: 새로운 기능 추가 - `fix`: 버그 수정 - `docs`: 문서 변경 - `style`: 코드 포맷팅, 세미콜론 누락, 코드 변경이 없는 경우 - `refactor`: 프로덕션 코드 리팩토링 - `test`: 테스트 추가, 테스트 리팩토링 - `chore`: 빌드 테스크 업데이트, 패키지 매니저 설정 등 ### Session Management Best Practices #### Session Start 1. Check Docker services are running 2. Compare CLAUDE.md files and sync if needed 3. Review CURRENT_WORKS.md for context 4. Check Git status in all repositories 5. Verify database migration status #### During Work 1. Update CURRENT_WORKS.md regularly 2. Commit frequently with descriptive messages 3. Run tests before committing 4. Keep CLAUDE.md local copy updated with new insights #### Session End 1. Final CURRENT_WORKS.md update 2. Commit all pending changes 3. Push critical changes to remote (if needed) 4. Sync CLAUDE.md files 5. Clean up temporary files ### Database Migration Management ```bash # Check current status php artisan migrate:status # Run pending migrations php artisan migrate # Rollback specific steps (for debugging) php artisan migrate:rollback --step=N # Reset to specific commit state # 1. First rollback migrations to target state # 2. Then git reset to target commit # 3. Finally run migrations up to target state ``` ## Important Notes - The system uses Laravel 12 with PHP 8.2+ - Filament v3 is used for admin panel interface - TailwindCSS for styling with Vite for asset building - Sanctum for API authentication - Multi-tenant architecture requires proper tenant context in all operations - **Follow SAM API Development Rules strictly when working on API-related tasks** - **Always maintain CURRENT_WORKS.md for project continuity** - **Sync CLAUDE.md files between sessions for consistency** - **🇰🇷 LANGUAGE SETTING: 모든 응답은 한국어로 제공 (별도 요청 시 예외)**