- CLAUDE.md 파일 동기화 규칙 정의 - CURRENT_WORKS.md 구조 및 작업 추적 시스템 문서화 - Git 커밋 워크플로우 및 컨벤션 정립 - 세션 관리 베스트 프랙티스 추가 - 데이터베이스 마이그레이션 관리 가이드 포함 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
17 KiB
17 KiB
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 directoryfront/_Codeigniter/- CodeIgniter 3 system files (extracted from www)
- 5130/ - Legacy PHP application for construction/manufacturing management
- shared/ - Common models and services package shared between applications
- docker/ - Docker configuration files
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
Shared Models Structure
The shared/ directory contains common Eloquent models organized by domain:
- Members/ - User and tenant management
- Products/ - Product catalog and BOM structures
- Materials/ - Material specifications and inventory
- Orders/ - Order processing workflows
- Tenants/ - Multi-tenant configurations
- Commons/ - Shared utilities and common data
Development Commands
Admin Application (admin/)
# 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/)
# 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/)
# 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
# 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
- API Key Authentication - All endpoints require valid API key via
auth.apikeymiddleware - User Authentication - POST
/v1/loginreturns Sanctum token - Protected Routes - Use
auth:sanctummiddleware 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_idcolumns with BelongsToTenant global scope - Shared models in
shared/Models/with tenant scoping - 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 statususers- User accounts with soft deletesuser_tenants- Many-to-many user-tenant relationships with active/default flagspersonal_access_tokens- Sanctum token storagepermissions- Role-based permissions with tenant scopingroles- Tenant-scoped rolesmodel_has_permissions/roles- Spatie permission assignmentspermission_overrides- Manual permission allow/deny with temporal validity
Multi-tenant Organization
tenants- Company/organization master with subscription infotenant_user_profiles- Extended user profiles per tenantdepartments- Hierarchical organizational structuredepartment_user- User-department assignments with primary department flag
Product Management
categories- Hierarchical product categorization with soft deletescategory_fields- Dynamic field definitions per categorycategory_templates- Versioned category field snapshotsproducts- Product catalog with type classification (PRODUCT/PART/SUBASSEMBLY)product_components- BOM relationships (MATERIAL|PRODUCT references)materials- Material master with dynamic attributesclassifications- Flat code tables by group (product_type, payment_method, etc.)
Design & Manufacturing
models- Design model master with lifecycle statusmodel_versions- Versioned model releases with DRAFT/RELEASED statusbom_templates- BOM templates linked to model versionsbom_template_items- Template BOM line items with quantities and waste rates
Orders & Operations
orders- Order/quotation master with workflow statusorder_items- Order line items with design codesorder_item_components- Required materials/products per order itemorder_histories- Order change tracking and notesclients- Customer/vendor master
Inventory & Materials
material_receipts- Incoming material receipts with lot trackingmaterial_inspections- Quality inspection recordsmaterial_inspection_items- Inspection checklist itemslots- Material lot managementlot_sales- Lot consumption trackingprice_histories- Historical pricing with temporal validity
System & Configuration
common_codes- Hierarchical master codes with tenant supportfiles- Polymorphic file attachmentsaudit_logs- Comprehensive audit trail with 13-month retentionsetting_field_defs- Global field definitionstenant_field_settings- Tenant-specific field configurationstenant_option_groups/values- Tenant-managed dropdown options
Content Management
boards- Configurable board systemposts- Board posts with custom fieldsboard_settings- Dynamic field definitions per boardboard_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:
.envin each application directory - Docker configs:
docker/directory - Asset building:
vite.config.jsandtailwind.config.jsin each app
Testing
- PHPUnit configuration:
phpunit.xmlin each Laravel app - Test directories:
tests/in Laravel applications
Development Workflow
- Environment Setup: Configure
.envfiles for each application - Database: Run migrations in both admin and api applications
- Dependencies:
composer installandnpm installin relevant directories - Development: Use
composer devto run all services concurrently - API Testing: Access Swagger documentation for API endpoints
- 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
- 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)
- Tags: Resource-based (User, Auth, Product, BOM...)
- Security: ApiKeyAuth + BearerAuth
- Schemas: Reuse ApiResponse, ErrorResponse, resource DTOs
- Specifications: Clear Path/Query/Body parameters with examples
- No duplicate schemas, accurate nullable/oneOf distinctions
8. Validation (FormRequest)
- No direct validate() calls. Separate all into FormRequest classes
- Reuse common Requests: PaginateRequest, BomItemsRequest, DateRangeRequest
- Boundary validation (effective_from ≤ effective_to) in Request
9. Audit Logging
- Table: audit_logs (tenant_id, target_type, target_id, action, before/after(json), actor_id, ip, ua, created_at)
- Actions: created, updated, deleted, released, cloned, items_replaced, diff_viewed
- Retention: 13 months default, audit:prune scheduler cleanup
- Failure tolerance: Log failures don't block business operations
10. Domain Rules
- Status: Strings (DRAFT/RELEASED/ARCHIVED)
- Unique/Indexes: models(code), model_versions(version_no), bom_items(parent, order)
- BOM: Supports summary/validate/bulkUpsert/reorder
11. Commit Messages
- Format: [type]: title + detailed bullets
- Types: feat | fix | chore | refactor | style
- Example:
feat: 감사 로그 도입 및 스케줄러 추가
Design/Estimation/Ordering Domain
Parameter-based BOM Resolution
- Input Parameters: W0/H0, installation type, power source, etc.
- Output Preview: W1/H1, area, weight, motor, bracket, guide, case, bottom, shaft, pipe (auto-calculated)
- Rules: Product family-specific formulas (Screen/Steel), boundary values apply higher capacity
- Proposed APIs:
GET /design/models/{id}/parameters→ Returns input schemaPOST /design/models/{id}/bom/resolve→ BOM/item calculation preview based on input values
Git Repository Structure & Workflow
Multiple Repository Setup
This project uses 5 separate Git repositories for different components:
- api/ - API project repository
- admin/ - Laravel admin panel repository
- front/www/ - CodeIgniter frontend repository
- front/_Codeigniter/ - Extracted CI3 system files repository
- shared/ - Shared models and services (planned for future use when API is mature)
Work Tracking & Commit Workflow
- Work Tracking: All ongoing work is documented in
CURRENT_WORKS.mdat the root level - Progress Updates: As features are developed, update
CURRENT_WORKS.mdwith changes per repository - Commit Process: When a feature is complete:
- Organize completed work by repository (api, admin, front/www, front/_Codeigniter, shared)
- Update
CURRENT_WORKS.mdwith summary of modified/added/deleted files - Create Git commits in each affected repository
- If
CURRENT_WORKS.mddoesn't exist, create it and add to Git
Repository-Specific Operations
Each repository operates independently with its own:
- Git history and branches
- Environment configuration (
.envfiles) - Dependencies and build processes
- Deployment workflows
Project Workflow Management
CLAUDE.md File Synchronization
This project uses multiple CLAUDE.md files for better workspace management:
- Master File:
/SAM/CLAUDE.md- Contains comprehensive project documentation - Local Copies: Each repository has its own CLAUDE.md for focused development
Synchronization Rules:
- At session start: Compare timestamps and update master file if local is newer
- When working: Use local CLAUDE.md for repository-specific guidance
- Before commit: Ensure synchronization is complete
Work Tracking System
CURRENT_WORKS.md Structure
# SAM 프로젝트 작업 현황
## YYYY-MM-DD (요일) - 작업 제목
### 주요 작업
- 작업 항목들 나열
### 저장소별 작업 내용
#### API 저장소 (`/api`)
**수정된 파일:**
- 파일명 - 변경 내용
**삭제된 파일:**
- 파일명 - 삭제 이유
**추가된 파일:**
- 파일명 - 추가 목적
**작업 내용:**
- 상세한 작업 설명
- 마이그레이션 상태 변경사항
- 환경 설정 변경사항
#### [다른 저장소들도 동일한 구조로]
Git Commit Workflow
# 1. 작업 완료 후 CURRENT_WORKS.md 업데이트
# 2. 각 저장소별 커밋
cd api && git add . && git commit -m "feat: 작업 내용"
cd ../admin && git add . && git commit -m "feat: 작업 내용"
cd ../front/www && git add . && git commit -m "feat: 작업 내용"
# 3. 커밋 메시지 형식
# [type]: 간결한 제목
#
# - 상세 변경 내용 (필요시)
# - 브레이킹 체인지 (있는 경우)
#
# 🤖 Generated with [Claude Code](https://claude.ai/code)
# Co-Authored-By: Claude <noreply@anthropic.com>
Commit Types
feat: 새로운 기능 추가fix: 버그 수정docs: 문서 변경style: 코드 포맷팅, 세미콜론 누락, 코드 변경이 없는 경우refactor: 프로덕션 코드 리팩토링test: 테스트 추가, 테스트 리팩토링chore: 빌드 테스크 업데이트, 패키지 매니저 설정 등
Session Management Best Practices
Session Start
- Check Docker services are running
- Compare CLAUDE.md files and sync if needed
- Review CURRENT_WORKS.md for context
- Check Git status in all repositories
- Verify database migration status
During Work
- Update CURRENT_WORKS.md regularly
- Commit frequently with descriptive messages
- Run tests before committing
- Keep CLAUDE.md local copy updated with new insights
Session End
- Final CURRENT_WORKS.md update
- Commit all pending changes
- Push critical changes to remote (if needed)
- Sync CLAUDE.md files
- Clean up temporary files
Database Migration Management
# 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