# POST `/api/1.0/oscal-project/start` — 啟動專案 API 規格

> **Route**：`OscalProjectStartRoute.post`
> **File**：`api/project/routes/project_route.py`
> **Auth**：JWT Required（Header：`Authorization: Bearer <token>`）

---

## Request

### Headers

| Header | 必填 | 說明 |
|--------|------|------|
| `Authorization` | 是 | `Bearer <jwt_token>` |
| `Content-Type` | 是 | `application/json` |
| `X-Tenant-ID` | 否 | 多租戶識別（預設從 JWT 取得） |

---

### Request Body

#### 完整範例

```json
{
  "profile_uid":  "a3f9e201-1b2c-4d5e-8f6a-0b1c2d3e4f50",
  "ssp_uid":      null,
  "name":         "2026 CMMC 2.0 Level 2 稽核",
  "description":  "DoD 供應鏈合規年度評估",
  "start_date":   "2026-01-01",
  "end_date":     "2026-12-31",

  "audit_systems": [
    { "information_system_uid": "a1b2c3d4-0001-0000-0000-000000000001" },
    { "information_system_uid": "b2c3d4e5-0002-0000-0000-000000000002" }
  ],

  "participants": [
    { "user_uid": "u-uid-0002", "is_admin": true  },
    { "user_uid": "u-uid-0003", "is_admin": false }
  ],

  "devices": [
    { "device_uid": "dev-uid-0001" },
    { "device_uid": "dev-uid-0002" }
  ]
}
```

#### 最簡請求（僅必填）

```json
{
  "profile_uid": "a3f9e201-1b2c-4d5e-8f6a-0b1c2d3e4f50",
  "name":        "2026 CMMC 2.0 Level 2 稽核",
  "start_date":  "2026-01-01",
  "end_date":    "2026-12-31"
}
```

---

### 欄位說明

#### 基本資訊

| 欄位 | 必填 | 型別 | 說明 |
|------|------|------|------|
| `profile_uid` | **是** | string | OSCAL Profile UID，決定評估哪些 controls（對應 `module_frame.oscal_profile_uid`） |
| `name` | **是** | string (max 250) | 專案名稱，同 tenant 下不可重複 |
| `start_date` | **是** | string `YYYY-MM-DD` | 專案起始日期 |
| `end_date` | **是** | string `YYYY-MM-DD` | 專案結束日期，需 > `start_date` |
| `ssp_uid` | 否 | string \| null | 既有 SSP UID；通常傳 `null`，系統自動建立空白 SSP |
| `description` | 否 | string (max 250) | 專案描述 |

#### 稽核系統 `audit_systems[]`（選填，可為空陣列）

```json
"audit_systems": [
  { "information_system_uid": "<uid>" }
]
```

| 欄位 | 必填 | 說明 |
|------|------|------|
| `information_system_uid` | **是** | 資訊系統 UID（需先於 `GET /information-systems/menu` 取得） |

> 系統會：
> 1. 查詢 `compliance.information_systems` 主檔
> 2. 在 `oscal.system_security_plans_system_characteristics` 建立評估快照
> 3. 在 `compliance.project_information_systems` 記錄關聯

#### 參與者 `participants[]`（選填，可為空陣列）

```json
"participants": [
  { "user_uid": "<uid>", "is_admin": false }
]
```

| 欄位 | 必填 | 說明 |
|------|------|------|
| `user_uid` | **是** | 使用者 UID |
| `is_admin` | 否 | 是否為管理員，預設 `false` |

> **注意**：建立者（發送請求的使用者）會**自動加入為管理員**，不需在此列出。若建立者的 `user_uid` 出現在此陣列，系統會自動略過。

#### 設備 `devices[]`（選填，可為空陣列）

```json
"devices": [
  { "device_uid": "<uid>" }
]
```

| 欄位 | 必填 | 說明 |
|------|------|------|
| `device_uid` | **是** | 設備 UID |

> 系統會同步在 SSP `system_implementations` 記錄設備資訊（OSCAL 合規文件用）。

---

## Response

### 成功 `200`

回傳新建立的 **Project 基本資料**（不含 AP 巢狀結構）。

```json
{
  "status": true,
  "data": {
    "id":          "550e8400-e29b-41d4-a716-446655440000",
    "uid":         "550e8400-e29b-41d4-a716-446655440000",
    "name":        "2026 CMMC 2.0 Level 2 稽核",
    "description": "DoD 供應鏈合規年度評估",
    "start_date":  "2026-01-01",
    "end_date":    "2026-12-31",
    "status":      "pending",
    "created_user": "john.doe",
    "updated_user": "john.doe",
    "created_at":   "2026-03-01 09:00:00",
    "updated_at":   "2026-03-01 09:00:00"
  }
}
```

> Response 欄位說明：
> - `id` 回傳的是 `uid`（非整數），與 `uid` 相同
> - `status` 初始值固定為 `"pending"`
> - 如需取得完整 AP / Control Groups / Tasks 資料，請接著呼叫 `GET /api/1.0/grc/project/<uid>`

---

### 錯誤情境

#### `409 Conflict` — 專案名稱重複

```json
{
  "status": false,
  "code":   0,
  "msg":    "PROJECT_PROJECT_NAME_DUPLICATE"
}
```

#### `404 Not Found` — Profile UID 不存在

```json
{
  "status": false,
  "code":   0,
  "msg":    "OSCAL_PROFILE_NOT_FOUND"
}
```

#### `404 Not Found` — audit_systems 的 information_system_uid 不存在

```json
{
  "status": false,
  "code":   0,
  "msg":    "Information system not found: <uid>"
}
```

#### `404 Not Found` — participants 的 user_uid 不存在

```json
{
  "status": false,
  "code":   0,
  "msg":    "USER_NOT_FOUND"
}
```

#### `404 Not Found` — devices 的 device_uid 不存在

```json
{
  "status": false,
  "code":   0,
  "msg":    "DEVICE_NOT_FOUND"
}
```

---

## 後端執行流程

整個方法以 **`@transaction`** 包裹，任一步驟失敗均全部 rollback。

```
POST /api/1.0/oscal-project/start
│
├─ Step 1  驗證專案名稱不重複（409 on duplicate）
├─ Step 2  取得 Profile（404 on missing）
├─ Step 3  取得或建立 SSP
│           └─ 有 ssp_uid → 取既有 SSP
│           └─ 無 ssp_uid → INSERT oscal_metadatas + system_security_plans
├─ Step 4  建立 Assessment Plan（AP）
│           └─ INSERT oscal_metadatas + assessment_plans（status=active）
├─ Step 4.5 建立空白 Assessment Result（AR）
│           └─ INSERT oscal_metadatas + assessment_results + assessment_result_datas
├─ Step 5  建立 Project 主檔
│           └─ INSERT compliance.projects（status=pending）
├─ Step 6  建立 Project ↔ AP 關聯
│           └─ INSERT compliance.project_assessment_plan_mapping
├─ Step 7  初始化 AP Controls / Groups / Tasks（try/except，失敗不 rollback）
│           └─ INSERT assessment_plan_groups / controls / tasks / task_controls
├─ Step 8  for each AP task：clone workflow template + 建立 execution
│           └─ INSERT workflow_templates（定版）
│           └─ INSERT workflow_executions / job_executions / element_variables
│           └─ INSERT assessment_plan_task_workflow_mapping
│           └─ INSERT assessment_plan_task_workflow_execution_mapping
│
├─ Step A 🆕  for each audit_system：
│             └─ 查 compliance.information_systems（404 on missing）
│             └─ INSERT oscal.system_security_plans_system_characteristics（快照）
│             └─ INSERT compliance.project_system_characteristic_mapping
│             └─ INSERT compliance.project_information_systems
│
├─ Step B 🆕  for each participant（排除建立者）：
│             └─ INSERT compliance.project_participants
│             └─ UPDATE oscal.oscal_metadatas（SSP parties）
│
├─ Step C 🆕  for each device：
│             └─ INSERT compliance.project_device_mapping
│             └─ INSERT oscal.system_security_plan_system_implementations
│
└─ Step 9  建立者自動加入為管理員（is_admin=true）
            └─ INSERT compliance.project_participants
            └─ UPDATE oscal.oscal_metadatas（SSP parties）
```

---

## DB 寫入總覽

| # | Table | Schema | 說明 |
|---|-------|--------|------|
| 1 | `oscal_metadatas` | oscal | SSP metadata |
| 2 | `system_security_plans` | oscal | SSP 主檔 |
| 3 | `oscal_metadatas` | oscal | AP metadata |
| 4 | `assessment_plans` | oscal | AP 主檔 |
| 5 | `oscal_metadatas` | oscal | AR metadata |
| 6 | `assessment_results` | oscal | AR 主檔 |
| 7 | `assessment_result_datas` | oscal | AR 初始 run |
| 8 | `assessment_plan_groups` | oscal | AP groups（clone from catalog） |
| 9 | `assessment_plan_controls` | oscal | AP controls snapshot |
| 10 | `assessment_plan_tasks` | oscal | AP tasks |
| 11 | `assessment_task_controls` | oscal | task ↔ control 關聯 |
| 12 | `projects` | compliance | 專案主檔 |
| 13 | `project_assessment_plan_mapping` | compliance | Project ↔ AP |
| 14 | `workflow_templates` | public | 定版 template（per task） |
| 15 | `workflow_executions` | public | 子流程（per task） |
| 16 | `element_variables` | public | Workflow / Job 變數 |
| 17 | `job_executions` | public | BPMN Jobs |
| 18 | `assessment_plan_task_workflow_mapping` | oscal | AP task ↔ template |
| 19 | `assessment_plan_task_workflow_execution_mapping` | oscal | AP task ↔ execution |
| 20 | `system_security_plans_system_characteristics` | oscal | 稽核系統快照（per audit_system）🆕 |
| 21 | `project_system_characteristic_mapping` | compliance | Project ↔ SC（per audit_system）🆕 |
| 22 | `project_information_systems` | compliance | Project ↔ IS（per audit_system）🆕 |
| 23 | `project_participants` | compliance | 額外參與者（per participant）🆕 |
| 24 | `project_device_mapping` | compliance | Project ↔ Device（per device）🆕 |
| 25 | `system_security_plan_system_implementations` | oscal | SSP 設備記錄（per device）🆕 |
| 26 | `project_participants` | compliance | 建立者 admin |
| 27 | `oscal_metadatas` | oscal | UPDATE SSP parties（含所有參與者） |

---

## 前端串接建議流程

```
1. GET  /api/1.0/information-systems/menu
   → 取得稽核系統選單，讓使用者勾選

2. GET  /api/1.0/auth/users/menu（或現有的 user 選單 API）
   → 取得參與者選單

3. GET  /api/1.0/devices/menu（或現有的 device 選單 API）
   → 取得設備選單

4. POST /api/1.0/oscal-project/start
   → 傳入上面選取的結果，建立專案

5. GET  /api/1.0/grc/project/<uid>
   → 取得建立完成的專案詳細資料（含 AP / control groups / tasks）
```

---

## 相關 API

| 說明 | API |
|------|-----|
| 取得稽核系統選單 | `GET /api/1.0/information-systems/menu` |
| 取得專案詳細（含 AP） | `GET /api/1.0/grc/project/<uid>` |
| 取得專案 Control Groups | `POST /api/1.0/grc/project/<uid>/control-groups/list` |
| 取得 AO 下的 Jobs | `POST /api/1.0/grc/ao/<ao_uid>/jobs/list` |
| 取得我的任務列表 | `POST /api/1.0/grc/jobs/my/list` |
