Files
vmis/backend/app/api/v1/accounts.py
VMIS Developer 62baadb06f feat(vmis): 租戶自動開通完整流程 + Admin Portal SSO + NC 行事曆訂閱
Backend:
- schedule_tenant: NC 新容器自動 pgsql 安裝 (_nc_db_check 全新容器處理)
- schedule_tenant: NC 初始化加入 Redis + APCu memcache 設定 (修正 OIDC invalid_state)
- schedule_tenant: 新租戶 KC realm 自動設定 accessCodeLifespan=600s (修正 authentication_expired)
- schedule_account: NC Mail 帳號自動設定 (nc_mail_result/nc_mail_done_at)
- schedule_account: NC 台灣國定假日行事曆自動訂閱 (CalDAV MKCALENDAR)
- nextcloud_client: 新增 subscribe_calendar() CalDAV 訂閱方法
- settings: 新增系統設定 API (site_title/version/timezone/SSO/Keycloak)
- models/result: 新增 nc_mail_result, nc_mail_done_at 欄位
- alembic: 遷移 002(system_settings) 003(keycloak_admin) 004(nc_mail_result)

Frontend (Admin Portal):
- 新增完整管理後台 (index/tenants/accounts/servers/schedules/logs/settings/system-status)
- api.js: Keycloak JS Adapter SSO 整合 (PKCE/S256, fallback KC JS 來源, 自動 token 更新)
- index.html: Promise.allSettled 取代 Promise.all,防止單一 API 失敗影響整頁
- 所有頁面加入 try/catch + toast 錯誤處理
- 新增品牌 LOGO 與 favicon

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-15 15:31:37 +08:00

125 lines
4.3 KiB
Python

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,
nc_mail_result=result.nc_mail_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)):
import secrets
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}"
data = payload.model_dump()
if not data.get("default_password"):
data["default_password"] = account_code # 預設密碼 = 帳號編碼,使用者首次登入後必須變更
account = Account(
**data,
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()