docs: [종합정비] Phase 1 시스템 현황 문서 14개 작성

- system/overview.md: 전체 아키텍처 개요
- system/api-structure.md: API 구조 (220 모델, 1027 엔드포인트, 18 라우트 도메인)
- system/react-structure.md: React 구조 (249 페이지, 612 컴포넌트)
- system/mng-structure.md: MNG 구조 (171 컨트롤러, 436 Blade 뷰)
- system/docker-setup.md: Docker 7 컨테이너 구성
- system/database/README.md + 9개 도메인 스키마 (270+ 테이블)
  - core, hr, sales, production, finance, boards, files, system, erp-analysis

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-27 18:03:13 +09:00
parent 0ace50b006
commit d4e5f62413
30 changed files with 7589 additions and 0 deletions

193
system/database/README.md Normal file
View File

@@ -0,0 +1,193 @@
# 데이터베이스 스키마 현황
> **최종 갱신**: 2026-02-27
> **DB**: MySQL 8.0 (samdb + sam_stat)
> **마이그레이션**: 459개 (api/에서만 관리)
---
## 1. 규모 요약
| 항목 | 수량 |
|------|------|
| Eloquent 모델 | 220 |
| 도메인 그룹 | 32 |
| 마이그레이션 | 459 (메인 437 + 통계 22) |
| DB 연결 | 2 (samdb, sam_stat) |
---
## 2. 도메인별 모델 분포
| 도메인 | 모델 수 | 주요 엔티티 | 상세 |
|--------|---------|------------|------|
| Tenants | 56 | Tenant, Department, Approval, Payment, Stock 등 | [tenants.md](tenants.md) |
| Stats | 21 | StatFinanceDaily, DimClient, DimDate 등 | [stats.md](stats.md) |
| Documents | 15 | Document, DocumentTemplate, DocumentApproval 등 | [documents.md](documents.md) |
| Commons | 10 | Category, File, Menu, Tag, Classification | [commons.md](commons.md) |
| Quote | 8 | Quote, QuoteItem, QuoteFormula, QuoteRevision | [sales.md](sales.md) |
| Production | 8 | WorkOrder, WorkOrderItem, WorkResult 등 | [production.md](production.md) |
| Orders | 8 | Order, OrderItem, OrderNode, Client 등 | [sales.md](sales.md) |
| ItemMaster | 8 | ItemField, ItemPage, ItemBomItem, CustomTab 등 | [products.md](products.md) |
| Products | 6 | Product, ProductComponent, Part, Price | [products.md](products.md) |
| Interview | 5 | InterviewTemplate, InterviewSession 등 | [hr.md](hr.md) |
| Construction | 5 | Contract, HandoverReport, StructureReview | [production.md](production.md) |
| Boards | 5 | Board, Post, BoardSetting, PostCustomFieldValue | [commons.md](commons.md) |
| Members | 4 | User, UserTenant, UserRole, UserMenuPermission | [tenants.md](tenants.md) |
| Materials | 4 | Material, MaterialReceipt, MaterialInspection | [production.md](production.md) |
| ESign | 4 | EsignContract, EsignSigner, EsignSignField | [documents.md](documents.md) |
| Design | 4 | DesignModel, ModelVersion, BomTemplate | [products.md](products.md) |
| Qualitys | 3 | Inspection, Lot, LotSale | [production.md](production.md) |
| Permissions | 3 | Permission, Role, PermissionOverride | [tenants.md](tenants.md) |
| Items | 3 | Item, ItemDetail, ItemReceipt | [products.md](products.md) |
| BadDebts | 3 | BadDebt, BadDebtDocument, BadDebtMemo | [finance.md](finance.md) |
| Estimate | 2 | Estimate, EstimateItem | [sales.md](sales.md) |
| Audit | 2 | AuditLog, TriggerAuditLog | [commons.md](commons.md) |
| Root Level | 27 | ApiKey, Process, NumberingSequence 등 | 각 도메인 문서 참조 |
---
## 3. 핵심 엔티티 관계도
### 인증 + 멀티테넌시
```
User
├─ hasMany UserTenant (pivot: is_active, is_default)
│ └─ belongsTo Tenant
├─ hasMany UserRole
└─ hasMany UserMenuPermission
Tenant
├─ hasMany Department (계층 구조, parent_id)
│ └─ belongsToMany User (department_user pivot)
├─ hasMany TenantUserProfile (테넌트별 직원 프로필)
└─ hasMany [모든 tenant-scoped 모델]
```
### 제품 + 설계
```
Product
├─ belongsTo Category (계층 분류)
├─ hasMany ProductComponent (BOM)
├─ hasMany Part, Price
└─ morphMany File
DesignModel
└─ hasMany ModelVersion
└─ hasMany BomTemplate
└─ hasMany BomTemplateItem
```
### 견적 → 수주 → 생산 흐름
```
Quote (견적)
├─ belongsTo Client
├─ hasMany QuoteItem
└─ → Order 변환
Order (수주)
├─ belongsTo Quote, Client
├─ hasMany OrderItem (options JSON)
├─ hasMany OrderNode (설계 분해)
└─ hasMany WorkOrder
WorkOrder (작업지시)
├─ belongsTo Order, Process
├─ hasMany WorkOrderItem (options JSON)
├─ hasMany WorkOrderStepProgress
└─ hasMany WorkResult (작업실적)
```
### 문서 + 전자결재
```
Document
├─ belongsTo DocumentTemplate
├─ morphTo linkable (다형 - Order, Quote 등)
├─ hasMany DocumentApproval (결재 단계)
└─ hasMany DocumentData (동적 폼)
DocumentTemplate
├─ hasMany Section → Field → Item
└─ hasMany ApprovalLine (결재선)
```
---
## 4. 공통 패턴
### 트레이트 사용 현황
| 트레이트 | 적용 모델 수 | 역할 |
|---------|-------------|------|
| BelongsToTenant | ~160 (73%) | tenant_id 자동 스코핑 |
| Auditable | ~150 (68%) | created_by, updated_by, deleted_by |
| SoftDeletes | ~150 (68%) | 논리 삭제 (deleted_at) |
| ModelTrait | ~80 (36%) | 날짜 처리, is_active 스코프 |
| HasRoles (Spatie) | 3 | RBAC 권한 관리 |
| HasApiTokens (Sanctum) | 1 (User) | API 토큰 관리 |
### 표준 컬럼 구조
모든 비즈니스 테이블의 공통 컬럼:
```
id PK
tenant_id FK (멀티테넌시)
created_by FK → users (감사)
updated_by FK → users (감사)
deleted_by FK → users (감사)
created_at timestamp
updated_at timestamp
deleted_at timestamp (논리삭제)
is_active boolean
sort_order integer
options JSON (유연한 속성 저장)
```
### DB 설계 패턴
| 패턴 | 사용 예시 |
|------|----------|
| 계층 구조 (Self-Reference) | Category, Department (parent_id) |
| 다형 관계 (Polymorphic) | File, PermissionOverride (morphable_type/id) |
| EAV (Entity-Attribute-Value) | PostCustomFieldValue, CategoryField |
| JSON 컬럼 | Product.bom, OrderItem.options, WorkOrderItem.options |
| Pivot 테이블 | user_tenants, department_user |
| BOM/Tree | ProductComponent, BomTemplateItem |
| 버전 관리 | ModelVersion, QuoteRevision, OrderVersion |
| 상태 코드 | Order.status (DRAFT/CONFIRMED/IN_PRODUCTION) |
### JSON options 컬럼 정책
> **FK/조인키만** 테이블 컬럼으로 추가.
> **나머지 속성은** `options` 또는 `attributes` JSON에 저장.
> 이유: 멀티테넌시 환경에서 테넌트별 스키마 변경 없이 유연한 관리.
---
## 5. DB 연결
| 연결명 | DB | 용도 |
|--------|-----|------|
| mysql (기본) | samdb | 모든 비즈니스 데이터 |
| sam_stat | sam_stat | 통계/집계 전용 (21 모델) |
| chandj | chandj | 레거시 5130 (마이그레이션 대상) |
---
## 6. 도메인별 상세 문서
| 문서 | 포함 도메인 |
|------|-----------|
| [tenants.md](tenants.md) | Tenants, Members, Permissions |
| [products.md](products.md) | Products, ItemMaster, Items, Design |
| [sales.md](sales.md) | Orders, Quote, Estimate |
| [production.md](production.md) | Production, Construction, Materials, Qualitys |
| [finance.md](finance.md) | Finance (Tenants 하위), BadDebts |
| [hr.md](hr.md) | HR (Tenants 하위), Interview |
| [documents.md](documents.md) | Documents, ESign |
| [commons.md](commons.md) | Commons, Boards, Audit |
| [stats.md](stats.md) | Stats (sam_stat DB) |

View File

@@ -0,0 +1,85 @@
# 공통 / 게시판 / 감사 도메인
> **모델 수**: Commons 10 + Boards 5 + Audit 2 = 17
> **핵심**: 범용 분류, 파일 관리, 게시판 시스템, 감사 로그
---
## 주요 테이블
### 공통 (Commons)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| categories | Category | 범용 계층 분류 (parent_id, self-reference) |
| category_fields | CategoryField | 카테고리 동적 필드 (EAV) |
| category_templates | CategoryTemplate | 카테고리 필드 스냅샷 (버전) |
| category_logs | CategoryLog | 카테고리 변경 로그 |
| classifications | Classification | 분류 체계 |
| files | File | 파일 첨부 (다형: morphMany) |
| menus | Menu | 메뉴 체계 |
| tags | Tag | 태그 시스템 |
| holidays | Holiday | 공휴일 |
| common_codes | CommonCode | 공통 코드 |
### 게시판 (Boards)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| boards | Board | 게시판 정의 |
| posts | Post | 게시글 |
| board_settings | BoardSetting | 게시판 동적 필드 정의 |
| post_custom_field_values | PostCustomFieldValue | 게시글 커스텀 필드 값 (EAV) |
| board_comments | BoardComment | 댓글 |
### 감사 (Audit)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| audit_logs | AuditLog | 변경 감사 로그 (불변) |
| trigger_audit_logs | TriggerAuditLog | DB 트리거 감사 로그 |
---
## 관계 구조
```
Category (계층 분류)
├─ belongsTo Category (parent_id → self)
├─ hasMany Category (children)
├─ hasMany CategoryField (EAV 동적 필드)
├─ hasMany CategoryTemplate (필드 버전 스냅샷)
├─ hasMany Product
└─ belongsToMany File via tags
Board (게시판)
├─ hasMany Post
│ ├─ hasMany PostCustomFieldValue (EAV)
│ └─ hasMany BoardComment
└─ hasMany BoardSetting (동적 필드 정의)
File (범용 첨부)
└─ morphTo fileable (어떤 모델에든 첨부 가능)
```
---
## EAV 패턴
게시판과 카테고리 모두 **EAV(Entity-Attribute-Value)** 패턴 사용:
```
Board → BoardSetting (필드 정의: field_name, field_type)
Post → PostCustomFieldValue (필드 값: board_setting_id, value)
Category → CategoryField (필드 정의: field_name, field_type)
```
---
## 특이사항
- `File`은 다형(morphMany) 관계 — 모든 모델에서 파일 첨부 가능
- `AuditLog`는 불변 (timestamps 없음, SoftDeletes 없음)
- 감사 로그 보존 정책: 13개월
- 게시판 시스템: EAV 패턴으로 동적 필드 지원 (노션 스타일 전환 계획 중)

View File

@@ -0,0 +1,68 @@
# 문서 / 전자서명 도메인
> **모델 수**: Documents 15 + ESign 4 = 19
> **핵심**: 문서 템플릿 기반 생성, 전자결재, 전자서명
---
## 주요 테이블
### 문서 (Documents)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| documents | Document | 문서 마스터 (다형 linkable) |
| document_templates | DocumentTemplate | 문서 템플릿 정의 |
| document_template_sections | DocumentTemplateSection | 템플릿 섹션 |
| document_template_section_fields | DocumentTemplateSectionField | 섹션 필드 |
| document_template_section_items | DocumentTemplateSectionItem | 체크리스트 항목 |
| document_template_field_presets | DocumentTemplateFieldPreset | 필드 프리셋 |
| document_template_approval_lines | DocumentTemplateApprovalLine | 결재선 정의 |
| document_approvals | DocumentApproval | 문서 결재 기록 |
| document_attachments | DocumentAttachment | 문서 첨부 |
| document_data | DocumentData | 문서 동적 데이터 |
| document_links | DocumentLink | 문서 링크 |
### 전자서명 (ESign)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| esign_contracts | EsignContract | 전자서명 계약 |
| esign_signers | EsignSigner | 서명자 |
| esign_sign_fields | EsignSignField | 서명 필드 |
| esign_audit_logs | EsignAuditLog | 전자서명 감사 로그 |
---
## 관계 구조
```
DocumentTemplate
├─ hasMany DocumentTemplateSection
│ └─ hasMany DocumentTemplateSectionField
│ ├─ hasMany DocumentTemplateSectionItem (체크리스트)
│ └─ hasMany DocumentTemplateFieldPreset (프리셋)
└─ hasMany DocumentTemplateApprovalLine (결재선)
Document
├─ belongsTo DocumentTemplate
├─ morphTo linkable (Order, Quote 등에 연결)
├─ hasMany DocumentApproval
├─ hasMany DocumentAttachment
├─ hasMany DocumentData
└─ hasMany DocumentLink
EsignContract
├─ hasMany EsignSigner
├─ hasMany EsignSignField
└─ hasMany EsignAuditLog
```
---
## 특이사항
- 문서 시스템은 템플릿 기반 (Section → Field → Item 3단계)
- `Document.linkable`은 다형 관계 (Order, Quote 등에 첨부 가능)
- 전자서명은 별도 감사 로그 보유 (EsignAuditLog)
- 문서 15개 모델 중 7개가 템플릿 구조 관련

View File

@@ -0,0 +1,57 @@
ㅇ# 재무 / 회계 도메인
> **모델 수**: Finance 관련 (Tenants 하위) + BadDebts 3
> **핵심**: 매입/매출, 결제, 세금계산서, 대출, 경비
> **API 엔드포인트**: 180개 (finance.php — 최대 규모)
---
## 주요 테이블
### 결제 / 청구
| 테이블 | 모델 | 역할 |
|--------|------|------|
| payments | Payment | 결제 마스터 |
| bills | Bill | 청구서 |
| deposits | Deposit | 입금 |
| withdrawals | Withdrawal | 출금 |
| receivables | Receivables | 매출채권 |
| vendor_ledgers | VendorLedger | 거래처 원장 |
### 세금 / 카드
| 테이블 | 모델 | 역할 |
|--------|------|------|
| tax_invoices | TaxInvoice | 세금계산서 |
| vat_* | Vat 관련 | 부가세 관리 |
| cards | Card | 법인카드 |
| card_transactions | CardTransaction | 카드 거래 |
| bank_accounts | BankAccount | 은행 계좌 |
| bank_transactions | BankTransaction | 은행 거래 |
### 대손 (BadDebts)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| bad_debts | BadDebt | 대손 마스터 |
| bad_debt_documents | BadDebtDocument | 대손 관련 문서 |
| bad_debt_memos | BadDebtMemo | 대손 메모 |
### 기타 재무
| 테이블 | 모델 | 역할 |
|--------|------|------|
| expected_expenses | ExpectedExpense | 예상 경비 |
| entertainments | Entertainment | 접대비 |
| purchases | Purchase | 매입 |
| subscriptions | Subscription | 구독/정기결제 |
---
## 특이사항
- 재무 모델은 대부분 `Tenants/` 디렉토리 하위에 위치
- finance.php 라우트가 180개로 전체 API 중 최대 규모
- 바로빌 연동은 mng에서 관리 (api에는 해당 모델 없음)
- 모든 재무 모델은 BelongsToTenant + Auditable + SoftDeletes

68
system/database/hr.md Normal file
View File

@@ -0,0 +1,68 @@
# 인사 / HR 도메인
> **모델 수**: HR 관련 (Tenants 하위) + Interview 5
> **핵심**: 급여, 근태, 휴가, 대출, 면접
> **API 엔드포인트**: 141개 (hr.php)
---
## 주요 테이블
### 급여 / 근무
| 테이블 | 모델 | 역할 |
|--------|------|------|
| payrolls | Payroll | 급여 마스터 |
| salaries | Salary | 급여 항목 |
| attendances | Attendance | 근태 기록 |
| attendance_requests | AttendanceRequest | 근태 요청 |
| leaves | Leave | 휴가 사용 기록 |
| leave_policies | LeavePolicy | 휴가 정책 |
| labors | Labor | 노무비 |
### 대출
| 테이블 | 모델 | 역할 |
|--------|------|------|
| loans | Loan | 직원 대출 |
### 면접 (Interview)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| interview_templates | InterviewTemplate | 면접 양식 |
| interview_sessions | InterviewSession | 면접 세션 |
| interview_questions | InterviewQuestion | 면접 질문 |
| interview_categories | InterviewCategory | 면접 카테고리 |
| interview_responses | InterviewResponse | 면접 답변 |
---
## 관계 구조
```
TenantUserProfile (직원)
├─ hasMany Payroll
├─ hasMany Attendance
├─ hasMany Leave
├─ hasMany Loan
└─ hasMany AttendanceRequest
LeavePolicy
└─ belongsTo Tenant (테넌트별 휴가 정책)
InterviewTemplate
├─ hasMany InterviewCategory
│ └─ hasMany InterviewQuestion
└─ hasMany InterviewSession
└─ hasMany InterviewResponse
```
---
## 특이사항
- HR 모델은 대부분 `Tenants/` 디렉토리 하위
- 직원 정보는 `TenantUserProfile` (테넌트별 프로필)
- 면접 모델은 별도 `Interview/` 도메인으로 분리
- 급여 관련 최근 추가: long_term_care 컬럼 (2026-02-27)

View File

@@ -0,0 +1,112 @@
# 생산 / 시공 / 자재 / 품질 도메인
> **모델 수**: Production 8 + Construction 5 + Materials 4 + Qualitys 3 = 20
> **핵심**: 작업지시, 공정 관리, 자재/LOT 추적, 품질 검사
---
## 주요 테이블
### 생산 (Production)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| work_orders | WorkOrder | 작업지시 마스터 |
| work_order_items | WorkOrderItem | 작업지시 항목 (options JSON) |
| work_order_step_progress | WorkOrderStepProgress | 단계별 진행 추적 |
| work_order_bending_details | WorkOrderBendingDetail | 절곡 상세 사양 |
| work_order_assignees | WorkOrderAssignee | 작업자 배정 |
| work_order_issues | WorkOrderIssue | 작업 이슈 기록 |
| work_results | WorkResult | 작업실적 |
| work_order_material_inputs | WorkOrderMaterialInput | 자재 투입 기록 |
### 시공 (Construction)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| contracts | Contract | 시공 계약 |
| handover_reports | HandoverReport | 인수인계 보고서 |
| handover_report_managers | HandoverReportManager | 인수인계 담당자 |
| structure_reviews | StructureReview | 구조 검토 |
### 자재 (Materials)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| materials | Material | 자재 마스터 |
| material_receipts | MaterialReceipt | 자재 입고 |
| material_inspections | MaterialInspection | 수입검사 마스터 |
| material_inspection_items | MaterialInspectionItem | 수입검사 항목 |
### 품질 (Qualitys)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| inspections | Inspection | 검사 마스터 |
| lots | Lot | LOT 관리 |
| lot_sales | LotSale | LOT 출고 |
---
## 관계 구조
```
WorkOrder (작업지시)
├─ belongsTo Order
├─ belongsTo Process (공정)
├─ belongsTo Department (담당 팀)
├─ hasMany WorkOrderItem
│ ├─ options: JSON { floor, code, width, height, slat_info, bending_info }
│ └─ hasMany WorkOrderMaterialInput
├─ hasMany WorkOrderStepProgress
├─ hasMany WorkOrderBendingDetail
├─ hasMany WorkOrderAssignee
├─ hasMany WorkOrderIssue
└─ hasMany WorkResult
Material
├─ belongsTo Category
├─ hasMany MaterialReceipt
├─ hasMany Lot
└─ morphMany File
Inspection
├─ belongsTo WorkOrder (또는 MaterialReceipt)
└─ hasMany InspectionItem
```
---
## WorkOrderItem options JSON 구조
```json
{
"floor": "1F",
"code": "SL-001",
"width": 1200,
"height": 800,
"cutting_info": { ... },
"slat_info": { "joint_bar": 2, "glass_qty": 10 },
"bending_info": { ... },
"wip_info": { ... }
}
```
- OrderItem.options에서 복사됨 (width 직접 접근 가능)
- 조인트바 자동계산: `createWorkOrders()` 에서 처리
---
## LOT 관리 흐름
```
Material → MaterialReceipt (입고)
MaterialInspection (수입검사)
Lot (LOT 생성)
WorkOrderMaterialInput (투입)
LotSale (출고)
```

View File

@@ -0,0 +1,88 @@
# 제품 / 품목 / 설계 도메인
> **모델 수**: Products 6 + ItemMaster 8 + Items 3 + Design 4 = 21
> **핵심**: 제품 정의, BOM 구조, 품목 마스터, 설계 모델
---
## 주요 테이블
### 제품 (Products)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| products | Product | 제품 마스터 (code, name, product_type) |
| product_components | ProductComponent | BOM 구성 (parent-child 관계) |
| parts | Part | 부품 정의 |
| prices | Price | 가격 정보 |
| common_codes | CommonCode | 공통 코드 |
### 품목 마스터 (ItemMaster)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| item_fields | ItemField | 품목 필드 정의 |
| item_pages | ItemPage | 품목 페이지 구성 |
| item_bom_items | ItemBomItem | 품목 BOM 항목 |
| custom_tabs | CustomTab | 커스텀 탭 |
| unit_options | UnitOption | 단위 옵션 |
### 품목 (Items)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| items | Item | 품목 마스터 |
| item_details | ItemDetail | 품목 상세 |
| item_receipts | ItemReceipt | 품목 입고 |
### 설계 (Design)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| design_models | DesignModel | 설계 모델 마스터 |
| model_versions | ModelVersion | 모델 버전 |
| bom_templates | BomTemplate | BOM 템플릿 |
| bom_template_items | BomTemplateItem | BOM 템플릿 항목 (수량, 로스율) |
---
## 관계 구조
```
Product
├─ belongsTo Category (계층 분류)
├─ hasMany ProductComponent (BOM)
│ └─ child_product_id → Product (자기 참조)
├─ hasMany Part
├─ hasMany Price
└─ morphMany File
Item
├─ hasMany ItemDetail
├─ hasMany ItemReceipt
└─ options JSON: { lot_managed, consumption_method, production_source, input_tracking }
DesignModel → ModelVersion → BomTemplate → BomTemplateItem
```
---
## 품목 options 체계
items.options JSON으로 품목별 관리 방식 정의:
| 속성 | 타입 | 설명 |
|------|------|------|
| lot_managed | bool | LOT 추적 여부 |
| consumption_method | auto/manual/none | 소진 방식 |
| production_source | purchased/self_produced/both | 조달 구분 |
| input_tracking | bool | 원자재 투입 추적 여부 |
### 유형별 조합
| 유형 | 예시 | lot | consumption | source |
|------|------|-----|------------|--------|
| 구매 소모품 (LOT) | 내화실 | true | manual | purchased |
| 구매 소모품 (비LOT) | 장갑, 테이프 | false | manual | purchased |
| 일반 자체생산 | 슬랫, 절곡물 | true | auto | self_produced |
| 잔재 활용 생산 | 조인트바 | true | auto | self_produced |

98
system/database/sales.md Normal file
View File

@@ -0,0 +1,98 @@
# 영업 / 수주 / 견적 도메인
> **모델 수**: Orders 8 + Quote 8 + Estimate 2 = 18
> **핵심**: 견적 → 수주 → 생산 변환 흐름
---
## 주요 테이블
### 수주 (Orders)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| orders | Order | 수주 마스터 (status: DRAFT→CONFIRMED→IN_PRODUCTION) |
| order_items | OrderItem | 수주 항목 (options JSON 포함) |
| order_nodes | OrderNode | 설계 분해 구조 |
| order_item_components | OrderItemComponent | 수주 항목 구성요소 |
| order_histories | OrderHistory | 수주 변경 이력 |
| clients | Client | 거래처 마스터 |
| client_groups | ClientGroup | 거래처 그룹 |
| site_briefings | SiteBriefing | 현장 브리핑 |
### 견적 (Quote)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| quotes | Quote | 견적 마스터 |
| quote_items | QuoteItem | 견적 항목 |
| quote_formulas | QuoteFormula | 견적 공식 |
| quote_formula_categories | QuoteFormulaCategory | 공식 카테고리 |
| quote_revisions | QuoteRevision | 견적 버전 이력 |
### 견적서 (Estimate)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| estimates | Estimate | 견적서 마스터 |
| estimate_items | EstimateItem | 견적서 항목 |
---
## 관계 구조
```
Quote (견적)
├─ belongsTo Client
├─ belongsTo SiteBriefing
├─ belongsTo Item
├─ hasMany QuoteItem
├─ hasMany QuoteRevision
└─ → Order 변환 (OrderService)
Order (수주)
├─ belongsTo Quote
├─ belongsTo Client
├─ hasMany OrderItem
│ ├─ belongsTo Item
│ ├─ hasMany OrderItemComponent
│ └─ options: JSON { floor, code, width, height, cutting_info, slat_info, bending_info }
├─ hasMany OrderNode
├─ hasMany OrderHistory
└─ hasMany WorkOrder (생산으로 변환)
```
---
## 비즈니스 흐름
```
견적(Quote) → 수주(Order) → 작업지시(WorkOrder) → 작업실적(WorkResult)
│ │ │
QuoteItem OrderItem WorkOrderItem
```
### 상태 흐름 (Order)
```
DRAFT → CONFIRMED → IN_PRODUCTION → COMPLETED → SHIPPED
```
---
## OrderItem options JSON 구조
```json
{
"floor": "1F",
"code": "SL-001",
"width": 1200,
"height": 800,
"cutting_info": { ... },
"slat_info": { "joint_bar": 2, "glass_qty": 10 },
"bending_info": { ... },
"wip_info": { ... }
}
```
- 견적 → 수주 변환 시 `extractSlatInfoFromBom()`으로 slat_info 자동 계산
- 조인트바 수량 공식: `(2 + floor((제작가로 - 500) / 1000)) × 셔터수량`

68
system/database/stats.md Normal file
View File

@@ -0,0 +1,68 @@
# 통계 도메인
> **모델 수**: 21
> **DB 연결**: sam_stat (별도 데이터베이스)
> **핵심**: 일별/월별 집계, 차원 테이블, 통계 서비스 15개
---
## 주요 테이블
### 일별 집계 (Daily)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| stat_finance_daily | StatFinanceDaily | 일별 재무 통계 |
| stat_production_daily | StatProductionDaily | 일별 생산 통계 |
| stat_sales_daily | StatSalesDaily | 일별 영업 통계 |
| stat_hr_daily | StatHrDaily | 일별 인사 통계 |
| stat_inventory_daily | StatInventoryDaily | 일별 재고 통계 |
### 월별 집계 (Monthly)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| stat_finance_monthly | StatFinanceMonthly | 월별 재무 통계 |
| stat_production_monthly | StatProductionMonthly | 월별 생산 통계 |
| stat_sales_monthly | StatSalesMonthly | 월별 영업 통계 |
### 차원 테이블 (Dimensions)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| dim_clients | DimClient | 거래처 차원 |
| dim_dates | DimDate | 날짜 차원 |
| dim_products | DimProduct | 제품 차원 |
| dim_departments | DimDepartment | 부서 차원 |
### 기타
| 테이블 | 모델 | 역할 |
|--------|------|------|
| base_stat_model | BaseStatModel | 통계 모델 베이스 |
| stat_* | 기타 통계 모델 | 도메인별 집계 |
---
## 아키텍처
```
[samdb] ──Observer 이벤트──→ [통계 서비스 15개] ──집계──→ [sam_stat DB]
StatEventObserver
├─ 주문 이벤트 → StatSalesDaily 업데이트
├─ 생산 이벤트 → StatProductionDaily 업데이트
├─ 재무 이벤트 → StatFinanceDaily 업데이트
└─ ... (도메인별)
```
---
## 특이사항
- **별도 DB 연결**: `sam_stat` (samdb와 분리)
- **마이그레이션**: 22개 (별도 관리)
- **서비스**: 15개 전용 서비스 (Stats/ 디렉토리)
- **차원 테이블**: 스타 스키마 기반 (DimClient, DimDate 등)
- **이벤트 기반**: Observer 패턴으로 실시간 집계
- API 엔드포인트: 5개 (stats.php) — 대부분 조회용

View File

@@ -0,0 +1,90 @@
# 테넌트 / 사용자 / 권한 도메인
> **모델 수**: Tenants 56 + Members 4 + Permissions 3 = 63
> **핵심**: 멀티테넌시 기반, 모든 비즈니스 데이터의 기준점
---
## 주요 테이블
### 인증 / 사용자
| 테이블 | 모델 | 역할 |
|--------|------|------|
| users | User | 시스템 계정 (Sanctum, HasRoles) |
| user_tenants | UserTenant | 사용자-테넌트 매핑 (is_active, is_default) |
| user_roles | UserRole | 사용자-역할 매핑 |
| user_menu_permissions | UserMenuPermission | 사용자별 메뉴 권한 |
### 테넌트 핵심
| 테이블 | 모델 | 역할 |
|--------|------|------|
| tenants | Tenant | 조직/회사 마스터 |
| departments | Department | 부서 (계층 구조, parent_id) |
| department_user | (pivot) | 부서-사용자 다대다 |
| tenant_user_profiles | TenantUserProfile | 테넌트별 직원 프로필 |
| positions | Position | 직급/직위 |
### 테넌트 설정
| 테이블 | 모델 | 역할 |
|--------|------|------|
| tenant_settings | TenantSetting | 테넌트별 설정값 |
| tenant_field_settings | TenantFieldSetting | 필드별 설정 |
| tenant_option_groups | TenantOptionGroup | 옵션 그룹 정의 |
| tenant_option_values | TenantOptionValue | 옵션 값 |
| tenant_stat_fields | TenantStatField | 통계 필드 설정 |
### 권한 (Spatie Permission)
| 테이블 | 모델 | 역할 |
|--------|------|------|
| permissions | Permission | 권한 정의 |
| roles | Role | 역할 정의 |
| permission_overrides | PermissionOverride | 권한 오버라이드 (다형) |
---
## 관계 구조
```
User (1)
├─ (N) UserTenant ─→ (1) Tenant
├─ (N) UserRole ─→ (1) Role ─→ (N) Permission
└─ (N) UserMenuPermission
Tenant (1)
├─ (N) Department (parent_id → self)
│ └─ (N:M) User via department_user
├─ (N) TenantUserProfile
│ ├─ → User
│ └─ → Department
├─ (N) TenantSetting
└─ (N) [모든 BelongsToTenant 모델]
```
---
## Tenants 하위 비즈니스 모델 (56개)
Tenants 도메인은 조직 내 다양한 비즈니스 기능을 포함:
- **재무**: Payment, Bill, TaxInvoice, JournalEntry, Deposit, Withdrawal 등
- **인사**: Payroll, Attendance, Leave, LeavePolicy, Salary, Loan 등
- **영업**: Sale, Client, ClientGroup, Shipment, Receivables 등
- **재고**: Stock, StockLot, MaterialInput 등
- **결재**: Approval, ApprovalForm, ApprovalLine 등
- **기타**: Calendar, CalendarSchedule, Notification 등
> 이 모델들의 상세 내용은 각 도메인 문서(finance.md, hr.md, sales.md 등)에서 다룸.
---
## 특이사항
- `User`는 BelongsToTenant가 아님 (시스템 전역)
- `UserTenant`으로 다중 테넌트 소속 지원
- `TenantUserProfile`은 테넌트별 직원 정보 (직급, 입사일 등)
- `Department`는 self-reference 계층 구조 (parent_id)
- 권한은 메뉴 기반 RBAC (Spatie Permission + UserMenuPermission)