# 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 - **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/) ```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 - 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 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 ## 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 - **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 schema - `POST /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 1. **Work Tracking**: All ongoing work is documented in `CURRENT_WORKS.md` at the root level 2. **Progress Updates**: As features are developed, update `CURRENT_WORKS.md` with changes per repository 3. **Commit Process**: When a feature is complete: - Organize completed work by repository (api, admin, front/www, front/_Codeigniter, shared) - Update `CURRENT_WORKS.md` with summary of modified/added/deleted files - Create Git commits in each affected repository - If `CURRENT_WORKS.md` doesn't exist, create it and add to Git ### Repository-Specific Operations Each repository operates independently with its own: - Git history and branches - Environment configuration (`.env` files) - Dependencies and build processes - Deployment workflows ## Project Workflow Management ### CLAUDE.md File Synchronization This project uses multiple CLAUDE.md files for better workspace management: 1. **Master File**: `/SAM/CLAUDE.md` - Contains comprehensive project documentation 2. **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 ```markdown # SAM 프로젝트 작업 현황 ## YYYY-MM-DD (요일) - 작업 제목 ### 주요 작업 - 작업 항목들 나열 ### 저장소별 작업 내용 #### API 저장소 (`/api`) **수정된 파일:** - 파일명 - 변경 내용 **삭제된 파일:** - 파일명 - 삭제 이유 **추가된 파일:** - 파일명 - 추가 목적 **작업 내용:** - 상세한 작업 설명 - 마이그레이션 상태 변경사항 - 환경 설정 변경사항 #### [다른 저장소들도 동일한 구조로] ``` #### Git Commit Workflow ```bash # 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 ``` #### 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**