feat(backend): Phase 1-4 全新開發完成,37/37 TDD 通過

[Phase 0 Reset]
- 清除舊版 app/、alembic/versions/、雜亂測試腳本
- 新 requirements.txt (移除 caldav/redis/keycloak-lib,加入 apscheduler/croniter/docker/paramiko/ping3/dnspython)

[Phase 1 資料庫]
- 9 張資料表 SQLAlchemy Models:tenants / accounts / schedules / schedule_logs /
  tenant_schedule_results / account_schedule_results / servers / server_status_logs / system_status_logs
- Alembic migration 001_create_all_tables (已套用到 10.1.0.20:5433/virtual_mis)
- seed.py:schedules 初始 3 筆 / servers 初始 4 筆

[Phase 2 CRUD API]
- GET/POST/PUT/DELETE: /api/v1/tenants / accounts / servers / schedules
- /api/v1/system-status
- 帳號編碼自動產生 (prefix + seq_no 4碼左補0)
- 燈號 (lights) 從最新排程結果取得

[Phase 3 Watchdog]
- APScheduler interval 3分鐘,原子 UPDATE status=Going 防重複執行
- 手動觸發 API: POST /api/v1/schedules/{id}/run

[Phase 4 Service Clients]
- KeycloakClient:vmis-admin realm,REST API (不用 python-keycloak)
- MailClient:Docker Mailserver @ 10.1.0.254:8080,含 MX DNS 驗證
- DockerClient:docker-py 本機 + paramiko SSH 遠端 compose
- NextcloudClient:OCS API user/quota
- SystemChecker:功能驗證 (traefik routers>0 / keycloak token / SMTP EHLO / DB SELECT 1 / ping)

[TDD]
- 37 tests / 37 passed (2.11s)
- SQLite in-memory + StaticPool,無需外部 DB

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
VMIS Developer
2026-03-14 13:10:15 +08:00
parent 22611f7f73
commit 42d1420f9c
52 changed files with 2934 additions and 0 deletions

View File

@@ -0,0 +1,118 @@
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.models.account import Account
from app.models.tenant import Tenant
from app.models.result import AccountScheduleResult
from app.schemas.account import AccountCreate, AccountUpdate, AccountResponse, AccountStatusLight
router = APIRouter(prefix="/accounts", tags=["accounts"])
def _next_seq_no(db: Session, tenant_id: int) -> int:
max_seq = db.query(Account.seq_no).filter(Account.tenant_id == tenant_id).order_by(Account.seq_no.desc()).first()
return (max_seq[0] + 1) if max_seq else 1
def _build_account_code(prefix: str, seq_no: int) -> str:
return f"{prefix}{str(seq_no).zfill(4)}"
def _get_lights(db: Session, account_id: int) -> Optional[AccountStatusLight]:
result = (
db.query(AccountScheduleResult)
.filter(AccountScheduleResult.account_id == account_id)
.order_by(AccountScheduleResult.recorded_at.desc())
.first()
)
if not result:
return None
return AccountStatusLight(
sso_result=result.sso_result,
mailbox_result=result.mailbox_result,
nc_result=result.nc_result,
quota_usage=result.quota_usage,
)
@router.get("", response_model=List[AccountResponse])
def list_accounts(
tenant_id: Optional[int] = Query(None),
is_active: Optional[bool] = Query(None),
db: Session = Depends(get_db),
):
q = db.query(Account)
if tenant_id is not None:
q = q.filter(Account.tenant_id == tenant_id)
if is_active is not None:
q = q.filter(Account.is_active == is_active)
accounts = q.order_by(Account.id).all()
result = []
for a in accounts:
resp = AccountResponse.model_validate(a)
resp.tenant_name = a.tenant.name if a.tenant else None
resp.lights = _get_lights(db, a.id)
result.append(resp)
return result
@router.post("", response_model=AccountResponse, status_code=201)
def create_account(payload: AccountCreate, db: Session = Depends(get_db)):
tenant = db.get(Tenant, payload.tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
seq_no = _next_seq_no(db, payload.tenant_id)
account_code = _build_account_code(tenant.prefix, seq_no)
email = f"{payload.sso_account}@{tenant.domain}"
account = Account(
**payload.model_dump(),
seq_no=seq_no,
account_code=account_code,
email=email,
)
db.add(account)
db.commit()
db.refresh(account)
resp = AccountResponse.model_validate(account)
resp.tenant_name = tenant.name
resp.lights = None
return resp
@router.get("/{account_id}", response_model=AccountResponse)
def get_account(account_id: int, db: Session = Depends(get_db)):
account = db.get(Account, account_id)
if not account:
raise HTTPException(status_code=404, detail="Account not found")
resp = AccountResponse.model_validate(account)
resp.tenant_name = account.tenant.name if account.tenant else None
resp.lights = _get_lights(db, account_id)
return resp
@router.put("/{account_id}", response_model=AccountResponse)
def update_account(account_id: int, payload: AccountUpdate, db: Session = Depends(get_db)):
account = db.get(Account, account_id)
if not account:
raise HTTPException(status_code=404, detail="Account not found")
for field, value in payload.model_dump(exclude_none=True).items():
setattr(account, field, value)
db.commit()
db.refresh(account)
resp = AccountResponse.model_validate(account)
resp.tenant_name = account.tenant.name if account.tenant else None
resp.lights = _get_lights(db, account_id)
return resp
@router.delete("/{account_id}", status_code=204)
def delete_account(account_id: int, db: Session = Depends(get_db)):
account = db.get(Account, account_id)
if not account:
raise HTTPException(status_code=404, detail="Account not found")
db.delete(account)
db.commit()