# SKILL: DD — Sinh Detail Design

## Dự án: car-security-web (SMART BLOCKER)

| Thuộc tính | Giá trị |
|------------|---------|
| Codebase | `~/GMSTB/car-security-web` (app/ + api/ + notification/) |
| Manifest | `manifest/flows.yaml` (74 luồng) |
| Branch git | `manifest/car-security-web` |
| Tech stack | Vue 3 + Pinia + Vite, NestJS + Prisma, Firebase Auth, MSPF integration |

**Ví dụ luồng tham chiếu trong skill này:**
- **F016** — Bật/tắt Security thủ công (core feature)
- **F006** — Bootstrap session Home (fetchProfile → fetchListDevice → fetchDevice)
- **F039** — Đồng bộ dữ liệu MSPF (notification service cron)

---

Sinh tài liệu **DD (Detail Design)** mô tả chi tiết kỹ thuật để implement một feature:  
component design, sequence diagrams, API specs, database schema, security, performance, testing.

DD là tài liệu **cuối cùng** trong chuỗi SRS → BD → DD.

---

## Điều kiện tiên quyết

**BD phải ở trạng thái `approved` trước khi chạy skill này.**

```yaml
docs:
  srs:
    status: approved
  bd:
    status: approved
```

---

## Đầu vào cần cung cấp

```
flow_id:        <ví dụ: F016>
srs_files:      <đường dẫn tới SRS đã approved>
bd_files:       <đường dẫn tới BD đã approved>
meta_yaml:      <nội dung meta.yaml>
codebase_path:  <để tham khảo tech stack hiện tại>
```

---

## Tổng quan output DD

Một DD hoàn chỉnh gồm **2 loại tài liệu**:

| Tài liệu | Template gốc | Mục đích |
|----------|-------------|---------|
| **Feature List** | `feature-list-template.md` | Index tất cả features có detail design |
| **Feature Detail Design** | `feature-detail-design-template.md` | Chi tiết kỹ thuật cho từng feature (15 sections) |

Ngoài ra, các **Common Design Documents** cần có (dùng chung cho toàn project):

| Tài liệu | Template gốc |
|----------|-------------|
| Architecture Overview | `common/architecture-overview-template.md` |
| Security Patterns | `common/security-patterns-template.md` |
| Error Handling Patterns | `common/error-handling-patterns-template.md` |
| Integration Patterns | `common/integration-patterns-template.md` |
| Performance Standards | `common/performance-standards-template.md` |
| Deployment & Infrastructure | `common/deployment-infrastructure-template.md` |

---

## Tài liệu 1: Feature List (`feature-list-template.md`)

### Section 1 — List of Features

**Ý nghĩa:** Index tất cả features có detail design document.

**Ví dụ (SMART BLOCKER — Module Security):**

| Feature ID | Feature Name | SRS Reference | Priority | Status | Link to Detail |
|------------|--------------|----------------|----------|--------|----------------|
| F-16 | Bật/tắt Security thủ công | SRS F-16 | High | Draft | [F-16 Detail](features/f16-security-toggle.md) |
| F-17 | Liên kết geofence auto khi Security | SRS F-17 | High | Draft | [F-17 Detail](features/f17-geofence-security.md) |
| F-20 | Security schedule tự động (backend) | SRS F-20 | High | Draft | [F-20 Detail](features/f20-security-schedule.md) |

### Section 2 — Feature Dependencies (Optional)

**Ví dụ (SMART BLOCKER):**

| Feature | Depends On | Description |
|---------|------------|-------------|
| F-17 | F-16 | Geofence auto chỉ kích hoạt khi Security ON |
| F-21 | F-16, F-20 | Thông báo Security phụ thuộc trạng thái activation |
| F-29 | F-014 | Lắp đặt hoàn tất mới unblock Home (statusId≠3) |

---

## Tài liệu 2: Feature Detail Design (`feature-detail-design-template.md`)

Mỗi feature có **một file riêng**, gồm **15 sections** bắt buộc:

---

### Section 1 — Feature Implementation Overview

#### 1.1 Feature Summary

**Ý nghĩa:** Tóm tắt feature, SRS reference, priority, approach kỹ thuật tổng thể.

**Fields bắt buộc:**
- **Feature Name:** Tên đầy đủ
- **SRS Reference:** SRS section tương ứng
- **Priority:** High/Medium/Low
- **Brief Description:** 2-3 câu mô tả kỹ thuật approach
- **Implementation Approach:** Microservice / Module / Component / ...
- **Architecture Reference:** Link sang Architecture Overview doc

**Ví dụ (F-16 — Bật/tắt Security thủ công):**

```markdown
### 1.1 Feature Summary

**Feature Name:** Bật/tắt Security thủ công (セキュリティ ON/OFF)

**SRS Reference:** SRS F-16 (F-16.1 đến F-16.4)

**Priority:** High

**Brief Description:**
Feature này implement nút Security ON/OFF trên footer HomeView.
Frontend gọi `PUT /devices/activation` với status ACTIVE_ONESHOT/INACTIVE_ONESHOT;
backend forward lệnh tới MSPF và cập nhật trạng thái ACTIVATING/DEACTIVATING/ACTIVE/INACTIVE.

**Implementation Approach:** Pinia store (`device.ts`) + NestJS API + MSPF integration

**Architecture Reference:** [Architecture Overview](common/architecture-overview.md)
```

#### 1.2 Design Decisions

**Ý nghĩa:** Ghi lại các quyết định thiết kế quan trọng và lý do chọn.

**Ví dụ (F-16):**

| Decision | Rationale | Alternatives Considered |
|----------|-----------|------------------------|
| Polling activation status mỗi 15s trên HomeView | MSPF cập nhật async, user cần thấy ACTIVATING→ACTIVE | WebSocket (bị loại — chưa có infra) |
| Chỉ Owner được bật/tắt Security | Member chỉ xem, không điều khiển thiết bị | Cho phép Member (bị loại — business rule) |
| PUT /devices/activation đồng bộ request | Đơn giản, backend queue MSPF command | Direct MSPF call từ frontend (bị loại — security) |

**Technology Choices:**
- Vue 3 + Pinia: device state management
- Axios interceptor: tự động attach Firebase token
- NestJS + Prisma: API layer + DB persistence

#### 1.3 Dependencies

**Ý nghĩa:** Liệt kê các dependencies — internal (features/modules khác) và external (services ngoài).

**Ví dụ (F-21):**

```markdown
**Internal Dependencies:**
- F-09 (Product master): GET /master/products — cần cho bước 2 chọn product
- F-11 (Company Group): shop list được derive từ company/shop master
- Auth module (Vuex): Firebase token cho mọi API call

**External Dependencies:**
- Firebase Authentication: verify token trong mọi request
- SIPS Backend API: POST /accept endpoint

**Infrastructure Dependencies:**
- PostgreSQL: primary database cho accepts, accept_products, accept_shippings tables
```

---

### Section 2 — Component Design

#### 2.1 Component Overview

**Ý nghĩa:** Mô tả các components/modules cần implement. Kèm **Component Diagram** Mermaid.

**Diagram loại:** `C4Component` (nếu project dùng C4) hoặc `classDiagram`/`flowchart` tùy context.

**Ví dụ (F-21 — Component Diagram):**

```mermaid
flowchart TD
    subgraph Frontend[SMART BLOCKER App - Vue]
        WizardRouter[Vue Router\nAcceptCreate routes]
        VuexModule[Vuex: acceptCreate module\nstate, mutations, actions]
        Step1[AcceptCreateBasic.vue\nStep 1 component]
        Step2[AcceptCreateProduct.vue\nStep 2 component]
        Step3[AcceptCreateShipment.vue\nStep 3 component]
        Step4[AcceptCreateConfirm.vue\nStep 4 + submit]
    end

    subgraph Backend[SIPS Backend]
        Controller[AcceptController\nPOST /accept]
        Service[AcceptService\nbusiness logic]
        Repository[AcceptRepository\nDB operations]
    end

    DB[(PostgreSQL)]

    WizardRouter --> Step1
    WizardRouter --> Step2
    WizardRouter --> Step3
    WizardRouter --> Step4
    Step1 --> VuexModule
    Step2 --> VuexModule
    Step3 --> VuexModule
    Step4 --> VuexModule
    Step4 -->|POST /accept| Controller
    Controller --> Service
    Service --> Repository
    Repository --> DB
```

#### 2.2 Component Responsibilities

Mô tả từng component: purpose, responsibilities, interfaces, dependencies.

**Ví dụ:**

```markdown
**AcceptCreateBasic.vue:**
- **Purpose:** Step 1 của wizard — nhập basic info
- **Responsibilities:**
  - Render form: shop dropdown, order_date, delivery_date, remarks
  - Client-side validation (Vuelidate)
  - Commit valid data vào Vuex `acceptCreate.basicInfo`
  - Enable/disable nút "Next" dựa vào validation state
- **Interfaces:**
  - Input: Vuex `acceptCreate.basicInfo` (load saved data nếu user back)
  - Output: Commit `SET_BASIC_INFO` mutation khi validate pass
- **Dependencies:** Vuex store `shopMaster` (shop dropdown options)

**AcceptService (Backend):**
- **Purpose:** Business logic layer cho accept creation
- **Responsibilities:**
  - Validate business rules (delivery_date > order_date, products exist và active)
  - Generate accept_no (format: ACC-YYYYMMDD-{id:04d})
  - Orchestrate DB writes trong transaction
- **Interfaces:**
  - Input: CreateAcceptDTO (validated payload từ controller)
  - Output: AcceptResponseDTO
- **Dependencies:** AcceptRepository, ProductRepository, ShopRepository
```

#### 2.3 Class Design

**Ý nghĩa:** Class diagram cho backend service layer (nếu phức tạp). Dùng `classDiagram`.

```mermaid
classDiagram
    class AcceptController {
        +createAccept(req, res)
        +handleValidationError()
    }
    class AcceptService {
        +createAccept(dto: CreateAcceptDTO) AcceptResponseDTO
        +validateBusinessRules(dto)
        +generateAcceptNo(date, id) string
    }
    class AcceptRepository {
        +create(data) Accept
        +createProducts(acceptId, products[]) AcceptProduct[]
        +createShipping(acceptId, shipping) AcceptShipping
    }
    class CreateAcceptDTO {
        +shop_id: number
        +order_date: string
        +delivery_date: string
        +products: ProductItemDTO[]
        +shipping: ShippingDTO
    }

    AcceptController --> AcceptService : uses
    AcceptService --> AcceptRepository : uses
    AcceptController ..> CreateAcceptDTO : receives
```

---

### Section 3 — Sequence Diagrams

**Ý nghĩa:** Sequence diagrams chi tiết cho happy path, alternative flows, và error flows.

#### 3.1 Primary Flow: Wizard submit thành công

**Ví dụ đầy đủ với xử lý lỗi (F-21):**

```mermaid
sequenceDiagram
    actor Vehicle Owner as Vehicle Owner
    participant Vue as Vue Frontend
    participant Vuex as Vuex Store (acceptCreate)
    participant API as SIPS Backend API
    participant DB as PostgreSQL

    Vehicle Owner->>Vue: Mở /accept/create/basic
    Vue->>Vuex: dispatch('loadShops') → GET /master/shops
    Vuex-->>Vue: shops list

    Vehicle Owner->>Vue: Điền Basic Info → bấm Next
    Vue->>Vuex: commit SET_BASIC_INFO({ shop_id, order_date, delivery_date })
    Vue->>Vue: navigate → /accept/create/product

    Vehicle Owner->>Vue: Chọn products + qty → bấm Next
    Vue->>Vuex: commit SET_PRODUCTS([{ product_id, quantity }])
    Vue->>Vue: navigate → /accept/create/shipment

    Vehicle Owner->>Vue: Nhập shipping info → bấm Next
    Vue->>Vuex: commit SET_SHIPPING({ address, method, recipient_name })
    Vue->>Vue: navigate → /accept/create/confirm

    Vehicle Owner->>Vue: Review Confirm → bấm Submit
    Vue->>Vuex: getters.buildPayload
    Vuex-->>Vue: { shop_id, order_date, products, shipping, ... }

    Vue->>API: POST /accept { payload }
    API->>API: Verify Firebase token
    API->>API: Validate DTO (joi/class-validator)

    alt Validation OK
        API->>DB: BEGIN TRANSACTION
        API->>DB: INSERT accepts → id=1024
        API->>DB: INSERT accept_products × N
        API->>DB: INSERT accept_shippings
        API->>DB: COMMIT
        DB-->>API: OK
        API-->>Vue: 201 { id: 1024, accept_no: "ACC-20240115-1024", status: "受注" }
        Vue->>Vuex: dispatch('resetWizard')
        Vue-->>Vehicle Owner: navigate /accept/1024 + toast "受注を作成しました"
    else Validation Error (422)
        API-->>Vue: 422 { errors: [{ field, message }] }
        Vue->>Vue: Map errors → xác định step bị lỗi
        Vue-->>Vehicle Owner: Navigate về step lỗi + hiển thị inline errors
    else Server Error (500)
        API-->>Vue: 500 Internal Server Error
        Vue-->>Vehicle Owner: Toast "システムエラーが発生しました"
        Note over Vue,Vehicle Owner: Wizard state KHÔNG reset — user có thể retry
    end
```

#### 3.2 Alternative Flow: User navigate Back

```mermaid
sequenceDiagram
    actor Vehicle Owner as Vehicle Owner
    participant Vue as Vue Frontend
    participant Vuex as Vuex Store

    Note over Vehicle Owner,Vuex: User đang ở Step 3 (Shipment), muốn sửa lại Product

    Vehicle Owner->>Vue: Bấm "← Back"
    Vue->>Vue: navigate → /accept/create/product
    Vue->>Vuex: getters.products (load saved state)
    Vuex-->>Vue: [{ product_id: 101, quantity: 2 }, ...]
    Vue-->>Vehicle Owner: Hiển thị Step 2 với data đã lưu

    Vehicle Owner->>Vue: Sửa quantity, bấm Next
    Vue->>Vuex: commit SET_PRODUCTS([{ product_id: 101, quantity: 3 }])
    Vue->>Vue: navigate → /accept/create/shipment
    Note over Vue,Vuex: Shipping data vẫn giữ nguyên từ lần trước
```

#### 3.3 Error Flow: DB transaction failure

```mermaid
sequenceDiagram
    participant API as SIPS Backend
    participant DB as PostgreSQL
    participant Logger as Logger Service
    participant Vue as Vue Frontend

    API->>DB: BEGIN TRANSACTION
    API->>DB: INSERT accepts OK
    API->>DB: INSERT accept_products OK
    API->>DB: INSERT accept_shippings ERROR (FK violation)
    DB-->>API: Error: FK constraint violation

    API->>DB: ROLLBACK
    API->>Logger: log ERROR { request_id, user_id, error: "FK_VIOLATION", table: "accept_shippings" }
    API-->>Vue: 500 { error: "internal_error", message: "システムエラーが発生しました", request_id: "req_abc123" }

    Note over API,Vue: DB transaction đảm bảo không có orphan records
```

---

### Section 4 — API Design

#### 4.1 API Overview

Base path, authentication method, reference sang BD API List/Detail.

#### 4.2 Endpoints

Chi tiết từng endpoint (giống BD API Detail nhưng focus vào implementation notes):

**Ví dụ (F-21 — POST /accept):**

```markdown
#### 4.2.1 `POST /api/v1/accept`

**Summary:** Tạo đơn nhận mới

**SRS Reference:** SRS F-21.3 FR-21-01

**Operation ID:** `createAccept`

**Authentication:** Required (Firebase ID Token)

**Request Body Schema:**
```json
{
  "shop_id": 42,
  "order_date": "2024-01-15",
  "delivery_date": "2024-01-22",
  "remarks": "急ぎでお願いします",
  "products": [
    { "product_id": 101, "quantity": 2 }
  ],
  "shipping": {
    "address": "東京都渋谷区道玄坂1-2-3",
    "method": "EXPRESS",
    "recipient_name": "田中 太郎"
  }
}
```

**201 Created Response:**
```json
{
  "id": 1024,
  "accept_no": "ACC-20240115-1024",
  "status": "受注",
  "created_at": "2024-01-15T09:30:00+09:00"
}
```
```

#### 4.3 API Security

Feature-specific security requirements + reference sang Security Patterns doc.

---

### Section 5 — Database Design

#### 5.1 Database Schema

ER Diagram Mermaid + table definitions.

**Ví dụ (F-21 — ER diagram):**

```mermaid
erDiagram
    accepts ||--|{ accept_products : "contains"
    accepts ||--o| accept_shippings : "has shipping"
    accepts }|--|| shops : "belongs to"
    accept_products }|--|| products : "references"

    accepts {
        bigint id PK
        string accept_no UNIQUE
        bigint shop_id FK
        date order_date
        date delivery_date
        string status
        text remarks
        bigint created_by
        timestamp created_at
        timestamp deleted_at
    }
    accept_products {
        bigint id PK
        bigint accept_id FK
        bigint product_id FK
        integer quantity
        decimal unit_price
    }
    accept_shippings {
        bigint id PK
        bigint accept_id FK
        string address
        string method
        string recipient_name
    }
```

#### 5.2 Tables

Chi tiết từng table: purpose, PK, fields, indexes, FK, business rules.

#### 5.3 Data Access Patterns

Read patterns (query conditions thường dùng) + Write patterns (insert/update logic).

---

### Section 6 — UI Design

#### 6.1 Screen Overview

Liệt kê màn hình liên quan + reference sang BD Screen Detail.

#### 6.2 Screen: [Tên màn hình]

Layout + key components + interactions. Reference sang BD hoặc mô tả lại nếu có thay đổi kỹ thuật.

#### 6.3 User Flows

Primary flow + Alternative flows từ góc kỹ thuật implementation.

#### 6.4 Responsive Design

Breakpoints + adaptations.

---

### Section 7 — Security Considerations

#### 7.1 Authentication & Authorization

**Ý nghĩa:** Feature-specific security requirements. Reference sang Security Patterns doc.

**Ví dụ (F-21):**

```markdown
**Feature-Specific Requirements:**
- Chỉ user có role `Vehicle Owner` mới được gọi POST /accept
- Backend kiểm tra role từ decoded Firebase token (không trust client)
- `shop_id` trong request phải thuộc company group của Vehicle Owner user (không được tạo đơn hộ shop khác)

**Authorization Rules:**
- Vehicle Owner: Có thể tạo đơn nhận cho shops trong company group của mình
- ADMIN: Có thể tạo đơn cho mọi shop
- TECH, SHIPPING: Không có quyền gọi POST /accept → 403
```

#### 7.2 Data Protection

Sensitive data + encryption method.

#### 7.3 Input Validation

Validation rules chi tiết từng field (reference BD Field Validation table).

**Ví dụ (F-21):**

```markdown
**Server-side Validation (bắt buộc, không trust client):**
- `shop_id`: EXISTS trong shops table AND thuộc company group của user
- `order_date`: IS date format, >= TODAY
- `delivery_date`: IS date format, > order_date
- `products`: NOT EMPTY array, mỗi product_id EXISTS và status = 'active' trong products table
- `quantity`: integer, 1 <= qty <= 9999
```

---

### Section 8 — Integration Details

#### 8.1 Internal Integrations

Integration với features/modules khác trong SIPS.

**Ví dụ (F-21):**

```markdown
**Integration với Product Master (F-09):**
- **Purpose:** Validate product_id tồn tại và active khi tạo đơn
- **Method:** Direct DB query (cùng database)
- **Data Flow:** AcceptService → ProductRepository.findById(id) → SELECT FROM products WHERE id = ? AND status = 'active'
- **Error Handling:** Nếu product không tồn tại/inactive → throw BusinessRuleException → 422

**Integration với Shop Master (F-13):**
- **Purpose:** Validate shop_id và kiểm tra authorization (shop thuộc company group của user)
- **Method:** Direct DB query
- **Error Handling:** Shop không tồn tại → 422; Shop không thuộc quyền user → 403
```

#### 8.2 External Integrations

Integration với services ngoài (Firebase, FileMaker, v.v.).

**Ví dụ (F-21):**

```markdown
**Integration với Firebase Authentication:**
- **Purpose:** Verify identity của user khi gọi POST /accept
- **Method:** Firebase Admin SDK: `admin.auth().verifyIdToken(token)`
- **Authentication:** Firebase service account credentials (env var)
- **Error Handling:**
  - Token expired → 401 AUTH_TOKEN_EXPIRED
  - Token invalid → 401 AUTH_TOKEN_INVALID
- **Retry Strategy:** Không retry — nếu token hết hạn, Firebase SDK tự refresh ở frontend
```

#### 8.3 Event Publishing/Subscribing

Nếu feature publish/subscribe events qua message queue.

---

### Section 9 — Error Handling

#### 9.1 Error Scenarios

**Ý nghĩa:** Bảng tất cả error codes đặc thù của feature.

**Ví dụ (F-21):**

| Error Code | HTTP Status | Condition | User Message |
|------------|-------------|-----------|--------------|
| `ACCEPT_VALIDATION_ERROR` | 422 | Required field thiếu hoặc format sai | "入力内容に誤りがあります" |
| `ACCEPT_INVALID_SHOP` | 422 | shop_id không tồn tại trong master | "指定されたショップは存在しません" |
| `ACCEPT_PRODUCT_INACTIVE` | 422 | product_id đã ngừng kinh doanh | "指定された商品は現在利用できません" |
| `ACCEPT_UNAUTHORIZED_SHOP` | 403 | Shop không thuộc company group của user | "このショップへのアクセス権限がありません" |
| `ACCEPT_CREATE_FAILED` | 500 | DB transaction failure | "システムエラーが発生しました" |

#### 9.2 Error Handling Flow

Sequence diagram cho error handling:

```mermaid
sequenceDiagram
    participant Service as AcceptService
    participant ErrorHandler as GlobalErrorHandler
    participant Logger as Logger
    participant Client as Vue Frontend

    Service->>Service: Error occurs (e.g. ProductInactiveException)
    Service->>ErrorHandler: throw ProductInactiveException({ product_id: 101 })
    ErrorHandler->>ErrorHandler: Map to ACCEPT_PRODUCT_INACTIVE (422)
    ErrorHandler->>Logger: log WARN { error_code, product_id, user_id, request_id }
    ErrorHandler->>Client: 422 { error: "ACCEPT_PRODUCT_INACTIVE", message: "指定された商品は現在利用できません", details: [{ field: "products[0].product_id" }] }
```

#### 9.3 Recovery Strategies

- **422 errors:** User sửa input → retry
- **500 errors:** Wizard state không reset → user có thể retry sau
- **Network timeout:** Show toast, giữ nguyên form data

---

### Section 10 — Performance Considerations

#### 10.1 Performance Requirements

Reference sang Performance Standards doc + feature-specific targets.

**Ví dụ (F-21):**

```markdown
**Feature-Specific Targets:**
- POST /accept: P95 < 300ms (bao gồm 3 DB inserts trong transaction)
- GET /master/products (cho wizard step 2): P95 < 200ms, có cache
- Wizard navigation giữa steps: < 50ms (pure client-side, no API call)
```

#### 10.2 Optimization Strategies

**Ví dụ (F-21):**

```markdown
**Caching:**
- Product master: cache trong Vuex store, TTL = session (reload khi F5)
- Shop list: cache trong Vuex store, TTL = session

**Database Optimization:**
- Indexes: idx_accepts_shop_id, idx_accepts_status_date (xem Section 5)
- Bulk insert: dùng INSERT ... VALUES (row1), (row2) cho accept_products (không loop từng row)
- Connection pooling: pgBouncer, pool size = 10

**API Optimization:**
- POST /accept không trả về full object (chỉ id, accept_no, status) — tránh N+1 query khi load detail
```

#### 10.3 Scalability

Horizontal scaling approach, auto-scaling config nếu applicable.

---

### Section 11 — Testing Strategy

#### 11.1 Unit Testing

Components và services cần test.

**Ví dụ (F-21):**

```markdown
**Backend Unit Tests:**
- [ ] AcceptService.createAccept() — happy path
- [ ] AcceptService.createAccept() — invalid shop_id → throw exception
- [ ] AcceptService.createAccept() — inactive product → throw exception
- [ ] AcceptService.generateAcceptNo() — format: ACC-YYYYMMDD-XXXX
- [ ] AcceptService.validateBusinessRules() — delivery_date <= order_date → throw

**Frontend Unit Tests:**
- [ ] AcceptCreateBasic.vue — validate required fields
- [ ] AcceptCreateBasic.vue — delivery_date < order_date → Next button disabled
- [ ] Vuex acceptCreate module — SET_BASIC_INFO mutation
- [ ] Vuex acceptCreate module — buildPayload getter → correct structure
```

#### 11.2 Integration Testing

```markdown
- [ ] POST /accept — happy path: 201 + DB records created
- [ ] POST /accept — missing shop_id: 422
- [ ] POST /accept — inactive product: 422
- [ ] POST /accept — shop không thuộc quyền user: 403
- [ ] POST /accept — no auth token: 401
- [ ] POST /accept — expired Firebase token: 401
```

#### 11.3 End-to-End Testing

```markdown
**E2E Scenarios:**
- Scenario 1: Vehicle Owner tạo đơn thành công qua wizard 4 bước → verify redirect + accept_no hiển thị
- Scenario 2: Vehicle Owner bấm Back ở step 3 → verify data step 2 không bị reset
- Scenario 3: Submit với product inactive → verify error message + redirect về step Product
```

#### 11.4 Performance Testing

Load test scenarios với expected throughput.

---

### Section 12 — Deployment Considerations

#### 12.1 Deployment Requirements

Reference sang Deployment & Infrastructure doc + feature-specific requirements.

#### 12.2 Configuration

**Ví dụ (F-21):**

```markdown
**Environment Variables:**
- `FIREBASE_PROJECT_ID`: Firebase project ID để verify tokens
- `FIREBASE_SERVICE_ACCOUNT`: Path tới service account JSON (hoặc base64 encoded)
- `DATABASE_URL`: PostgreSQL connection string
- `ACCEPT_NO_PREFIX`: Prefix cho accept_no (default: "ACC")

**Feature Flags:**
- `FEATURE_ACCEPT_CREATE_EXPRESS_SHIPPING`: Enable/disable EXPRESS shipping option (default: true)
```

#### 12.3 Migration Strategy

SQL migration scripts cần chạy trước deploy.

---

### Section 13 — Monitoring and Observability

#### 13.1 Metrics

Key metrics cần monitor.

**Ví dụ (F-21):**

```markdown
**Key Metrics:**
- `accept.create.success_rate`: tỷ lệ POST /accept thành công (alert nếu < 99%)
- `accept.create.p95_latency`: P95 latency của POST /accept (alert nếu > 500ms)
- `accept.create.validation_error_rate`: tỷ lệ 422 errors (cao → UX issue)
```

#### 13.2 Logging

Log events quan trọng.

**Ví dụ (F-21):**

```markdown
**Log Events:**
- `accept.created`: log khi tạo đơn thành công { accept_id, accept_no, shop_id, user_id }
- `accept.create.failed`: log khi POST /accept thất bại { error_code, user_id, request_id }
- `accept.create.auth_failed`: log khi Firebase verify thất bại { ip, user_agent }
```

#### 13.3 Alerting

Thresholds và alert actions.

---

### Section 14 — References

**Ý nghĩa:** Links tới tất cả documents liên quan.

```markdown
**Detail Design:**
- [Feature List](../feature-list.md)

**Common Design Documents:**
- [Architecture Overview](../common/architecture-overview.md)
- [Security Patterns](../common/security-patterns.md)
- [Error Handling Patterns](../common/error-handling-patterns.md)
- [Performance Standards](../common/performance-standards.md)
- [Integration Patterns](../common/integration-patterns.md)
- [Deployment & Infrastructure](../common/deployment-infrastructure.md)

**Basic Design Documents:**
- [Screen Map](../../bd/screen-map.md)
- [Screen Detail](../../bd/screen-detail.md)
- [API List](../../bd/api-list.md)
- [API Detail](../../bd/api-detail.md)
- [DB Design](../../bd/db-design.md)

**SRS References:**
- SRS F-21: Feature Detail — Tạo đơn nhận wizard 4 bước
- SRS Section 5: Data Requirements
- SRS Section 7: Quality Attributes
```

---

### Section 15 — Notes

Implementation notes, design decisions log, future enhancements, open questions.

---

## Hướng dẫn các Common Design Documents

### Architecture Overview (`common/architecture-overview-template.md`)

Document này viết **một lần** cho toàn project, cover 13 sections:

| Section | Nội dung |
|---------|---------|
| 1. Overview | Architecture principles, design goals |
| 2. System Context (C4 Level 1) | C4Context diagram — hệ thống + external systems + users |
| 3. Container Architecture (C4 Level 2) | C4Container diagram — các containers (web app, API, DB, queue) |
| 4. Component Architecture (C4 Level 3) | C4Component cho các key containers |
| 5. Technology Stack | Frontend/Backend/DB/Infrastructure stack |
| 6. Architectural Patterns | Layered, microservices, event-driven, API gateway |
| 7. Design Principles | Separation of concerns, loose coupling, security |
| 8. System Boundaries | Internal/external components, integration points |
| 9. Data Flow | High-level data flow flowchart |
| 10. Non-Functional Requirements | Performance, scalability, availability, security targets |
| 11. Deployment Architecture | Environments, deployment strategy |
| 12. References | Related docs |
| 13. Notes | Design decisions, trade-offs, future |

**Ví dụ (SMART BLOCKER — System Context):**

```mermaid
flowchart LR
    Vehicle Owner((Vehicle Owner\nStaff))
    TECH((TECH\nStaff))
    SHIPPING((SHIPPING\nStaff))
    ADMIN((ADMIN))

    subgraph SIPS[SIPS System]
        WebApp[Vue.js\nFrontend]
        API[SIPS\nBackend API]
        DB[(PostgreSQL)]
    end

    Firebase[Firebase\nAuthentication]
    FileMaker[FileMaker\nHarness DB]

    Vehicle Owner --> WebApp
    TECH --> WebApp
    SHIPPING --> WebApp
    ADMIN --> WebApp
    WebApp <--> API
    API <--> DB
    WebApp <--> Firebase
    API <--> Firebase
    TECH -->|マスタ更新| FileMaker
    FileMaker -->|Sync harness| API
```

### Security Patterns (`common/security-patterns-template.md`)

Document này viết **một lần**, cover 12 sections:

| Section | Key Points cho SIPS |
|---------|---------------------|
| 1. Overview | Firebase-based auth, RBAC theo role SIPS |
| 2. Authentication | Firebase ID Token, verify qua Admin SDK |
| 3. Authorization | Role-based: Vehicle Owner/TECH/SHIPPING/SHIPADMIN/ADMIN |
| 4. Data Protection | Encryption at rest (PostgreSQL), TLS in transit |
| 5. Input Validation | 4 layers: Client → API → Service → DB |
| 6. Security Headers | CSP, X-Frame-Options, HSTS |
| 7. Security Logging | Log auth events, permission denied attempts |
| 8. API Security | Rate limiting, versioning |
| 9. Secure Development | Code review checklist |
| 10. Compliance | PII handling, access logging |
| 11. References | Related docs |
| 12. Notes | SIPS-specific considerations |

### Error Handling Patterns (`common/error-handling-patterns-template.md`)

**Standard error response format cho SIPS:**

```json
{
  "error": "ACCEPT_PRODUCT_INACTIVE",
  "message": "指定された商品は現在利用できません",
  "details": [
    { "field": "products[0].product_id", "message": "商品ID 101 は販売停止中です" }
  ],
  "timestamp": "2024-01-15T09:30:00+09:00",
  "request_id": "req_abc123xyz"
}
```

**Exception handling flow diagram:**

```mermaid
flowchart TD
    Request[API Request] --> Auth{Firebase\nToken Valid?}
    Auth -->|No| AuthError[401 Unauthorized]
    Auth -->|Yes| RoleCheck{Role\nPermission?}
    RoleCheck -->|No| ForbidError[403 Forbidden]
    RoleCheck -->|Yes| Validation{Input\nValidation}
    Validation -->|Fail| ValError[422 Validation Error]
    Validation -->|Pass| Business[Business Logic]
    Business -->|BusinessRuleException| BizError[422 Business Rule Error]
    Business -->|NotFoundException| NotFoundError[404 Not Found]
    Business -->|Success| DBOp[DB Operation]
    DBOp -->|DBException| DBError[500 Internal Error\n+ ROLLBACK]
    DBOp -->|Success| Response[201/200 Success]
```

### Performance Standards (`common/performance-standards-template.md`)

**SIPS performance targets:**

| Endpoint | P50 | P95 | P99 |
|----------|-----|-----|-----|
| GET /accept (list) | < 100ms | < 200ms | < 500ms |
| POST /accept | < 150ms | < 300ms | < 600ms |
| GET /master/products | < 50ms (cached) | < 100ms | < 200ms |

### Integration Patterns (`common/integration-patterns-template.md`)

**SIPS integration points:**
- **Firebase Auth:** REST verify bằng Admin SDK, không dùng REST API trực tiếp
- **FileMaker (Harness sync):** POST /master/harnesses/update, auth riêng (Cognito)
- **Internal modules:** Direct DB queries (cùng PostgreSQL instance)

### Deployment & Infrastructure (`common/deployment-infrastructure-template.md`)

**SIPS environments:**
- Development: local Docker Compose (PostgreSQL + backend + frontend)
- Staging: GCP Cloud Run (backend) + Firebase Hosting (frontend)
- Production: GCP Cloud Run + Cloud SQL PostgreSQL

---

## Hướng dẫn diagram cho DD

### 1. Component Diagram

Dùng `flowchart TD` với subgraph phân layer Frontend/Backend/DB (xem Section 2.1 ở trên).

### 2. Sequence Diagram chi tiết (với xử lý lỗi)

Dùng `sequenceDiagram` với `alt/else` cho error cases (xem Section 3.1 ở trên).  
**Quan trọng:** DD sequence diagram chi tiết hơn BD — phải thể hiện:
- Từng method call giữa Controller → Service → Repository
- DB transaction BEGIN/COMMIT/ROLLBACK
- Log events tại error handler

### 3. State Diagram (trạng thái đơn nhận)

```mermaid
stateDiagram-v2
    [*] --> 受注 : POST /accept\n(Vehicle Owner tạo đơn)
    受注 --> 確定 : POST /accept/:id/approve\n(Vehicle Owner/ADMIN duyệt)
    受注 --> 差戻 : POST /accept/:id/reject\n(Vehicle Owner từ chối)
    差戻 --> 受注 : PUT /accept/:id\n(Vehicle Owner sửa + resubmit)
    確定 --> 出荷依頼 : POST /accept/:id/ship-request\n(yêu cầu xuất kho)
    出荷依頼 --> [*] : Hoàn tất xuất kho

    受注 --> [*] : DELETE /accept/:id\n(soft delete, chỉ status = 受注)
```

### 4. Class Diagram (Service Layer)

Xem ví dụ Section 2.3. Dùng khi service layer phức tạp (nhiều dependencies, inheritance).

### 5. Error Handling Flow

Xem ví dụ Section 9.2 và Error Handling Patterns ở trên.

---

## Quy tắc chất lượng DD

1. **API spec phải đủ để FE call ngay** — request body example điền data thực, không dùng `"value1"`.
2. **DB schema phải có SQL CREATE TABLE** hoặc migration script — không để dev tự suy.
3. **Sequence diagram phải cover error flows** — không chỉ happy path.
4. **Security section phải điền feature-specific rules** — không chỉ "reference security patterns".
5. **Unit test list phải enumerate method cụ thể** — không chỉ "test AcceptService".
6. **Env vars phải liệt kê đầy đủ** — dev mới setup được môi trường mà không cần hỏi.
7. Dùng đúng thuật ngữ domain: `受注`, `確定`, `差戻`, `出荷依頼`, `端末`, `ハーネス`.

---

## Sau khi sinh xong

1. Lưu files vào `docs/flows/{flow_folder}/dd/`
2. Cập nhật `meta.yaml`: `dd.status: review`
3. Tạo branch `docs/{flow_id}/dd` và commit
4. Tạo PR lên Bitbucket với security checklist trong PR description
