[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,91 +2,151 @@
|
||||
id: wiki-2026-0508-inventory-management-example
|
||||
title: Inventory Management Example
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-9C355C]
|
||||
aliases: [Inventory Domain Model, 재고 관리 예제]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
source_trust_level: B
|
||||
confidence_score: 0.85
|
||||
verification_status: applied
|
||||
tags: [example, domain-modeling, typescript, ddd]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Inventory [[Management]] Example"
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: TypeScript
|
||||
framework: Zod
|
||||
---
|
||||
|
||||
# [[Inventory Management Example]]
|
||||
# Inventory Management Example
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> 이 주제는 프론트엔드 모델과 백엔드 응답 간의 데이터 변환 시 발생할 수 있는 타입 불일치 문제를 보여주는 실제 사례입니다. 인벤토리 관리 시스템에서 백엔드의 데이터 형식과 프론트엔드의 정의된 타입 구조가 다를 때 발생할 수 있는 매핑 오류의 위험성을 다룹니다. TypeScript의 `satisfies` 키워드를 사용하여 엄격한 속성 검사를 강제함으로써 오타나 원치 않는 초과 필드의 포함을 방지하는 방법을 설명합니다.
|
||||
## 매 한 줄
|
||||
> **"매 SKU · stock · reservation 의 type-safe domain model 의 walking example"**. 매 branded types · discriminated unions · runtime validation 매 결합 — 2026 modern TS pattern 의 canonical illustration.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **데이터 구조의 차이**: 인벤토리 관리 시스템에서 프론트엔드는 `id`, `name`, `quantity` 속성을 가진 `InventoryItem` 타입을 정의하여 사용합니다 [1, 2]. 그러나 외부 백엔드에서 전달되는 데이터는 `qty`나 `lastUpdated`와 같이 프론트엔드 타입과 다른 형식으로 도착할 수 있습니다 [2].
|
||||
- **매핑 오류와 조용한 실패**: 백엔드 데이터를 프론트엔드 타입으로 매핑할 때, 속성 이름을 잘못 입력하거나(`quantity` 대신 `qty` 사용 등) 불필요한 필드를 포함하는 등의 오류가 쉽게 발생할 수 있습니다 [2]. 엄격한 검사가 없다면 TypeScript는 이러한 오타를 잡아내지 못할 수 있으며, 조용히 오류를 통과시킬 위험이 있습니다 [2].
|
||||
- **`satisfies` 키워드를 통한 엄격성 강제**: 데이터 매핑 함수 내에서 `satisfies` 키워드를 사용하면 엄격한 타입 계약을 강제할 수 있습니다 [3]. 이를 통해 대상 타입에 정의된 유효한 속성만 포함되도록 보장하며, 그렇지 않을 경우 발생할 수 있는 초과 속성 문제나 오타를 컴파일 단계에서 포착하여 방지할 수 있습니다 [3, 4].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 도메인 entities
|
||||
- `SKU` (branded string)
|
||||
- `Stock` (positive int)
|
||||
- `Reservation` (id, sku, qty, expiresAt)
|
||||
- `InventoryEvent` (Tagged: Received | Reserved | Shipped | Cancelled)
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[satisfies Keyword]], [[Excess Property Checking]], [[Type Casting]]
|
||||
- **Projects/Contexts:** [[Frontend]]-[[Backend]] Data Transformation
|
||||
- **Contradictions/Notes:** 소스는 데이터 변환 시 `as` 키워드를 사용한 타입 캐스팅에 의존하는 것을 경고합니다. 타입 캐스팅은 초과 속성 검사를 우회하여 조용한 오류(silent errors)와 의도치 않은 동작을 유발할 수 있으므로, 엄격한 계약을 강제하기 위해서는 `satisfies`를 사용하는 것이 더 안전합니다 [3, 4].
|
||||
### 매 invariants
|
||||
- 매 stock ≥ 0 항상.
|
||||
- 매 reservation 의 release 후 stock 회복.
|
||||
- 매 ship 의 reservation 의 존재 시.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-18*
|
||||
### 매 응용
|
||||
1. E-commerce checkout flow (재고 차감 · 복구).
|
||||
2. Warehouse management (multi-location).
|
||||
3. Event-sourced inventory ledger.
|
||||
|
||||
---
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### Branded SKU
|
||||
```ts
|
||||
type SKU = string & { readonly __brand: "SKU" }
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
const SkuSchema = z.string().regex(/^[A-Z]{3}-\d{6}$/).brand("SKU")
|
||||
const sku = SkuSchema.parse("ABC-123456") // SKU
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Stock value object
|
||||
```ts
|
||||
class Stock {
|
||||
private constructor(public readonly value: number) {}
|
||||
static of(n: number): Stock {
|
||||
if (!Number.isInteger(n) || n < 0) throw new Error("invalid stock")
|
||||
return new Stock(n)
|
||||
}
|
||||
reserve(qty: number): Stock { return Stock.of(this.value - qty) }
|
||||
release(qty: number): Stock { return Stock.of(this.value + qty) }
|
||||
}
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Discriminated event union
|
||||
```ts
|
||||
type InventoryEvent =
|
||||
| { type: "Received"; sku: SKU; qty: number; at: Date }
|
||||
| { type: "Reserved"; sku: SKU; qty: number; reservationId: string }
|
||||
| { type: "Shipped"; reservationId: string }
|
||||
| { type: "Cancelled"; reservationId: string }
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
function reduce(state: Map<SKU, Stock>, e: InventoryEvent): Map<SKU, Stock> {
|
||||
switch (e.type) {
|
||||
case "Received":
|
||||
return new Map(state).set(e.sku, (state.get(e.sku) ?? Stock.of(0)).release(e.qty))
|
||||
case "Reserved":
|
||||
return new Map(state).set(e.sku, state.get(e.sku)!.reserve(e.qty))
|
||||
case "Shipped":
|
||||
case "Cancelled":
|
||||
return state
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Reservation lifecycle (Result type)
|
||||
```ts
|
||||
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E }
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
function reserve(stock: Stock, qty: number): Result<Stock, "INSUFFICIENT"> {
|
||||
if (stock.value < qty) return { ok: false, error: "INSUFFICIENT" }
|
||||
return { ok: true, value: stock.reserve(qty) }
|
||||
}
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Zod runtime parse (API boundary)
|
||||
```ts
|
||||
const ReserveCmd = z.object({
|
||||
sku: SkuSchema,
|
||||
qty: z.number().int().positive(),
|
||||
customerId: z.string().uuid(),
|
||||
})
|
||||
|
||||
app.post("/reserve", (req, res) => {
|
||||
const cmd = ReserveCmd.safeParse(req.body)
|
||||
if (!cmd.success) return res.status(400).json(cmd.error.flatten())
|
||||
// ... cmd.data is fully typed
|
||||
})
|
||||
```
|
||||
|
||||
### Exhaustive switch guard
|
||||
```ts
|
||||
function never(x: never): never { throw new Error(`unhandled: ${x}`) }
|
||||
// switch default → never(e) 매 새 event 추가 시 compile error
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Single-location inventory | In-memory `Map<SKU, Stock>` |
|
||||
| Multi-location | Add `LocationId` brand · partition state |
|
||||
| Audit-required | Event sourcing (full event log) |
|
||||
| High-concurrency | Optimistic concurrency token + retry |
|
||||
|
||||
**기본값**: event-sourced reduce 매 audit + replay benefit. 매 단순 case도 future-proof.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Domain-Driven Design]] · [[견고한 도메인 모델 및 API 계약 설계]]
|
||||
- 변형: [[Result Type]] · [[Discriminated Unions]]
|
||||
- 응용: [[Zod 파싱과 브랜디드 타입을 결합한 런타임 데이터 검증]]
|
||||
- Adjacent: [[브랜디드 타입 (Branded Types)]] · [[ts-brand]] · [[완전성 검사(Exhaustiveness Checking)]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 type-safe domain modeling 의 teaching example 으로 reuse.
|
||||
**언제 X**: 매 production app 의 직접 copy — 매 oversimplified.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Plain `number` for stock**: 매 invariant 의 enforce 의 X — class · brand 의 사용.
|
||||
- **Stringly-typed events**: 매 discriminated union 의 사용.
|
||||
- **Skipping runtime parse at boundary**: 매 type erasure 후 — Zod / Effect Schema 의 필수.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (DDD blue book · Effect/Zod docs · TypeScript handbook 2026).
|
||||
- 신뢰도 B (illustrative example, not canonical implementation).
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — full domain example with brands · DU · event sourcing |
|
||||
|
||||
Reference in New Issue
Block a user