# AWOOOI 週報自動化機制

> **版本**: v1.0
> **建立日期**: 2026-03-20
> **負責人**: CTO
> **CEO 指示 #6**: 增加每週工作週報機制

---

## 概述

系統自動將該週各單位所有處理的工作，依照報告格式發出到 Email。

---

## 週報生成流程

```
┌─────────────────────────────────────────────────────────┐
│ 每週五 17:00 觸發                                        │
└─────────────────────────────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────────────┐
│ 1. 收集各單位工作記錄                                    │
│    - Git commits (by author)                            │
│    - 部署記錄                                            │
│    - 告警處理記錄                                        │
│    - 工單完成記錄                                        │
│    - 審批記錄                                            │
└─────────────────────────────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────────────┐
│ 2. AI 生成摘要                                          │
│    - 按單位分組                                         │
│    - 提取關鍵成果                                        │
│    - 識別風險項目                                        │
└─────────────────────────────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────────────┐
│ 3. 生成報告                                             │
│    - HTML 格式 (Email)                                  │
│    - Markdown 格式 (歸檔)                               │
└─────────────────────────────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────────────┐
│ 4. 發送 Email                                           │
│    - 收件人: C-Level + 團隊成員                          │
│    - 抄送: CEO                                          │
└─────────────────────────────────────────────────────────┘
```

---

## 週報格式

### Email 範本

```html
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: 'Inter', sans-serif; }
    .header { background: #0A0A0A; color: white; padding: 20px; }
    .section { margin: 20px 0; padding: 15px; background: #F5F5F5; }
    .metric { display: inline-block; margin: 10px; text-align: center; }
    .metric-value { font-size: 24px; font-weight: bold; }
    .status-success { color: #10B981; }
    .status-warning { color: #F59E0B; }
    .status-critical { color: #EF4444; }
  </style>
</head>
<body>
  <div class="header">
    <h1>AWOOOI 週報</h1>
    <p>{{week_start}} - {{week_end}}</p>
  </div>

  <div class="section">
    <h2>📊 本週摘要</h2>
    <div class="metric">
      <div class="metric-value">{{total_commits}}</div>
      <div>Commits</div>
    </div>
    <div class="metric">
      <div class="metric-value">{{total_deployments}}</div>
      <div>部署次數</div>
    </div>
    <div class="metric">
      <div class="metric-value">{{alerts_resolved}}</div>
      <div>告警處理</div>
    </div>
    <div class="metric">
      <div class="metric-value">{{tickets_closed}}</div>
      <div>工單完成</div>
    </div>
  </div>

  <div class="section">
    <h2>👥 各單位工作</h2>

    <h3>CTO 技術團隊</h3>
    <ul>
      {{#each cto_items}}
      <li>{{this}}</li>
      {{/each}}
    </ul>

    <h3>CIO 基建團隊</h3>
    <ul>
      {{#each cio_items}}
      <li>{{this}}</li>
      {{/each}}
    </ul>

    <h3>CPO 產品團隊</h3>
    <ul>
      {{#each cpo_items}}
      <li>{{this}}</li>
      {{/each}}
    </ul>

    <h3>CISO 安全團隊</h3>
    <ul>
      {{#each ciso_items}}
      <li>{{this}}</li>
      {{/each}}
    </ul>
  </div>

  <div class="section">
    <h2>⚠️ 風險與待辦</h2>
    <ul>
      {{#each risks}}
      <li class="status-{{this.severity}}">{{this.description}}</li>
      {{/each}}
    </ul>
  </div>

  <div class="section">
    <h2>📅 下週計畫</h2>
    <ul>
      {{#each next_week_plans}}
      <li>{{this}}</li>
      {{/each}}
    </ul>
  </div>

  <footer style="margin-top: 20px; color: #6B7280; font-size: 12px;">
    <p>此報告由 AWOOOI 系統自動生成</p>
    <p>生成時間: {{generated_at}}</p>
  </footer>
</body>
</html>
```

---

## 資料來源

### Git Commits

```python
# 取得本週 commits
async def get_weekly_commits(start_date: date, end_date: date) -> list[CommitSummary]:
    result = subprocess.run(
        [
            "git", "log",
            f"--since={start_date}",
            f"--until={end_date}",
            "--pretty=format:%H|%an|%ae|%s|%ai",
            "--no-merges"
        ],
        capture_output=True,
        text=True
    )

    commits = []
    for line in result.stdout.strip().split("\n"):
        hash, author, email, subject, date = line.split("|")
        commits.append(CommitSummary(
            hash=hash,
            author=author,
            email=email,
            subject=subject,
            date=date
        ))

    return commits
```

### 部署記錄

```python
async def get_weekly_deployments(start_date: date, end_date: date) -> list[Deployment]:
    async with get_db() as db:
        return await db.execute(
            select(Deployment)
            .where(Deployment.created_at >= start_date)
            .where(Deployment.created_at < end_date)
            .order_by(Deployment.created_at.desc())
        ).scalars().all()
```

### 告警處理

```python
async def get_weekly_alerts(start_date: date, end_date: date) -> AlertSummary:
    async with get_db() as db:
        total = await db.execute(
            select(func.count(Alert.id))
            .where(Alert.created_at >= start_date)
            .where(Alert.created_at < end_date)
        ).scalar()

        resolved = await db.execute(
            select(func.count(Alert.id))
            .where(Alert.resolved_at >= start_date)
            .where(Alert.resolved_at < end_date)
        ).scalar()

        return AlertSummary(total=total, resolved=resolved)
```

---

## 單位分組邏輯

### 根據 Git Author Email 分組

```python
TEAM_MAPPING = {
    "cto": ["cto@wooo.work", "dev@wooo.work", "backend@wooo.work"],
    "cio": ["cio@wooo.work", "infra@wooo.work", "ops@wooo.work"],
    "cpo": ["cpo@wooo.work", "frontend@wooo.work", "design@wooo.work"],
    "ciso": ["ciso@wooo.work", "security@wooo.work"],
}

def get_team_by_email(email: str) -> str:
    for team, emails in TEAM_MAPPING.items():
        if email in emails:
            return team
    return "other"
```

### 根據工作類型分組

```python
WORK_TYPE_MAPPING = {
    "cto": ["api", "backend", "database", "ai"],
    "cio": ["k8s", "nginx", "monitoring", "network"],
    "cpo": ["ui", "frontend", "design", "i18n"],
    "ciso": ["security", "rbac", "audit", "encryption"],
}
```

---

## AI 摘要生成

```python
async def generate_ai_summary(weekly_data: WeeklyData) -> str:
    prompt = f"""
    請根據以下本週工作資料，生成簡潔的週報摘要：

    ## Commits ({len(weekly_data.commits)} 筆)
    {[c.subject for c in weekly_data.commits[:20]]}

    ## 部署 ({len(weekly_data.deployments)} 次)
    {[d.description for d in weekly_data.deployments]}

    ## 告警處理
    - 總數: {weekly_data.alerts.total}
    - 已解決: {weekly_data.alerts.resolved}

    請用繁體中文，按 CTO/CIO/CPO/CISO 分組，每組列出 3-5 項關鍵工作。
    同時指出本週的風險項目和下週建議關注點。
    """

    return await ai_router.generate(prompt, system_user_id="weekly-report")
```

---

## K8s CronJob 配置

```yaml
# k8s/jobs/weekly-report-cronjob.yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: awoooi-weekly-report
  namespace: awoooi-prod
spec:
  schedule: "0 17 * * 5"  # 每週五 17:00
  timeZone: "Asia/Taipei"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
            - name: report-generator
              image: awoooi-api:latest
              command: ["python", "-m", "app.jobs.weekly_report"]
              env:
                - name: SMTP_HOST
                  valueFrom:
                    secretKeyRef:
                      name: awoooi-secrets
                      key: SMTP_HOST
                - name: SMTP_USER
                  valueFrom:
                    secretKeyRef:
                      name: awoooi-secrets
                      key: SMTP_USER
                - name: SMTP_PASSWORD
                  valueFrom:
                    secretKeyRef:
                      name: awoooi-secrets
                      key: SMTP_PASSWORD
          restartPolicy: OnFailure
```

---

## 收件人配置

```yaml
# 環境變數配置
WEEKLY_REPORT_RECIPIENTS:
  - ceo@wooo.work
  - cto@wooo.work
  - cio@wooo.work
  - cpo@wooo.work
  - ciso@wooo.work

WEEKLY_REPORT_CC:
  - all-team@wooo.work
```

---

## 報告歸檔

每週報告自動保存至：

```
docs/reports/weekly/
├── 2026-W12.md
├── 2026-W13.md
└── ...
```

---

## 變更記錄

| 日期 | 版本 | 變更 | 作者 |
|------|------|------|------|
| 2026-03-20 | v1.0 | 初版建立 | CTO |

---

*此文件由 CTO 維護，定義週報自動化機制的規範。*
