unis-oa/backend/app/api/support.py

722 lines
29 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""附件、草稿、通知、统计、公开配置与运行状态、操作日志、存储探活。
运行配置存在数据库里,读写入口在 :mod:`app.api.config`;这里只留公开配置
(``/settings/public``,登录页匿名可读)、运行状态快照(``/system/info``)
和存储状态。存库即生效,改配置不用重启服务。
"""
from __future__ import annotations
import logging
import os
from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, File, Form, Query, Request, UploadFile
from fastapi.responses import Response
from sqlalchemy import func, or_, select
from sqlalchemy.orm import Session
from .. import hubconfig
from .. import config as config_module
from .. import models, permissions, schemas, serializers, storage
from ..config import settings
from ..security import session_idle_minutes
from ..db import get_db, ping
from ..deps import CurrentUser, actor_of, client_ip, current_user, require_permission
from ..envelope import bad_request, not_found, ok
from ..service import dicts, drafts, starters
from ..storage import (
StorageError,
describe_preview,
check_upload,
clean_name,
extension_of,
resolve_uri,
store_for,
)
from ..storage.http import download_response, storage_error
from ..storage import preview as preview_layer
router = APIRouter(tags=["support"])
logger = logging.getLogger("unisoa.support")
def read_size(file: UploadFile) -> int:
"""Size of an upload without buffering it twice."""
if file.size:
return int(file.size)
handle = file.file
handle.seek(0, os.SEEK_END)
size = handle.tell()
handle.seek(0)
return size
def stored_location(row) -> str:
"""Where a record points at, for the settings page / troubleshooting."""
return row.storage or ""
# ------------------------------ attachments ------------------------------
@router.post("/attachment")
def upload_attachment(
file: UploadFile = File(...),
job: str = Form(""),
work: str = Form(""),
process: str = Form(""),
activity: str = Form(""),
activity_name: str = Form(""),
type: str = Form("attachment"),
user: CurrentUser = Depends(current_user),
db: Session = Depends(get_db),
) -> dict:
name = clean_name(file.filename or "attachment")
try:
check_upload(name, read_size(file))
# 附件一律进 MinIO,落点见配置项 minio_*(系统设置页保存即生效);MinIO 不可用时按 fallback_to_local 决定。
stored = store_for("attachment").save(
purpose="attachment", name=name, data=file.file, content_type=file.content_type or ""
)
except StorageError as exc:
raise storage_error(exc) from exc
row = models.Attachment(
name=name,
extension=extension_of(name),
storage=stored.uri,
length=stored.size,
type=type,
process=process,
job=job,
work=work,
activity=activity,
activity_name=activity_name,
person=user.person_id,
person_name=user.display_name,
)
db.add(row)
db.commit()
return ok(serializers.attachment(row))
@router.get("/attachment/{attachment_id}/download")
def download_attachment(
attachment_id: str,
request: Request,
inline: bool = Query(False),
db: Session = Depends(get_db),
_: CurrentUser = Depends(current_user),
) -> Response:
"""取附件字节。``inline=1`` 给批注里的图片预览用:按原类型回、不当下载弹。"""
row = db.get(models.Attachment, attachment_id)
if row is None:
raise not_found("附件不存在")
store = resolve_uri(row.storage)
try:
return download_response(
store,
row.storage,
row.name,
"" if inline else "application/octet-stream",
inline=inline,
range_header=request.headers.get("range"),
)
except StorageError as exc:
raise storage_error(exc) from exc
@router.get("/attachment/{attachment_id}/preview")
def preview_attachment(
attachment_id: str,
db: Session = Depends(get_db),
_: CurrentUser = Depends(current_user),
) -> dict:
"""这条附件怎么在流程里显示:浏览器直出,还是由后端读出正文。
``mode = "inline"`` 表示字节直接给 ``/download?inline=1``,前端拿 blob 就能显示
(图片、PDF、音视频);其余格式回 ``mode = "payload"`` 加一份结构化正文,
Word 是段落与表格、Excel 是工作表数组、PPT 是逐页文本,前端用模板渲染,
不走 ``v-html``——附件是不可信输入,不能在里面藏脚本。
"""
row = db.get(models.Attachment, attachment_id)
if row is None:
raise not_found("附件不存在")
info = describe_preview(row.name, int(row.length or 0))
if not info.previewable:
raise bad_request(info.reason or "该文件不支持在线预览", reason="PREVIEW_UNSUPPORTED")
if info.renderer not in preview_layer.BACKEND_RENDERERS:
return ok(
{
"kind": info.kind,
"renderer": info.renderer,
"mode": "inline",
"name": row.name,
"length": row.length,
"url": preview_layer.inline_url(row.id),
}
)
store = resolve_uri(row.storage)
try:
payload = preview_layer.render(store, row.storage, row.name)
except StorageError as exc:
raise storage_error(exc) from exc
except Exception as exc: # pragma: no cover - 解析库抛什么都有可能
# 损坏、加密、或者干脆是改了后缀的非该格式文件:说清是文件读不了,别让人去查存储
logger.warning("附件解析失败 %s (%s):%r", row.id, row.name, exc)
raise bad_request("文件无法解析,可能已损坏或加了密,请下载后查看", reason="PREVIEW_PARSE_FAILED") from exc
return ok({**payload, "mode": "payload", "length": row.length})
@router.get("/attachment")
def list_attachments(
db: Session = Depends(get_db),
_: CurrentUser = Depends(current_user),
job: str = Query(""),
work: str = Query(""),
) -> dict:
stmt = select(models.Attachment)
if job:
stmt = stmt.where(models.Attachment.job == job)
if work:
stmt = stmt.where(models.Attachment.work == work)
# 批注/审批意见随附的图片与文件不在这份清单里:它们跟着那条批注一起看,
# 混进单据附件面板会把「正式附件」和「随手贴的截图」搅成一锅。
stmt = stmt.where(models.Attachment.type.notin_(list(models.Attachment.KIND_LINKED)))
rows = db.execute(stmt.order_by(models.Attachment.order_number, models.Attachment.create_time)).scalars().all()
return ok([serializers.attachment(r) for r in rows])
@router.delete("/attachment/{attachment_id}")
def delete_attachment(
attachment_id: str, user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)
) -> dict:
row = db.get(models.Attachment, attachment_id)
if row is None:
raise not_found("附件不存在")
if row.person != user.person_id and not user.is_admin:
raise bad_request("无权删除该附件")
if row.storage:
try:
resolve_uri(row.storage).delete(row.storage)
except StorageError as exc:
# 文件删不掉不该挡住业务,记录本身还是要删掉;留条日志,不然对象成了孤儿也没人知道
logger.warning("附件文件删除失败 %s:%s", row.storage, exc)
db.delete(row)
db.commit()
return ok({"success": True})
# --------------------------------- drafts --------------------------------
@router.get("/draft")
def list_drafts(user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)) -> dict:
rows = db.execute(
select(models.Draft).where(models.Draft.person == user.person_id).order_by(models.Draft.update_time.desc())
).scalars().all()
return ok([serializers.draft(r) for r in rows])
# 建草稿的全部口径在 service/drafts.py:认流程、算标题、查发起范围、整型明细表、
# 报还差哪几项,一处算完。下面三个接口只做三件事——拿当前登录人、把请求体递进去、
# 把提醒和页面路径一起回出去。为什么不就地写:开放平台也要建草稿(外部系统替员工铺
# 一张待提交的单),两处各写一遍,迟早漂成"页面存的草稿和接口存的不一样"。
@router.get("/draft/types")
def list_draft_types(
process: str = Query("", description="只看某一个类型:流程 id / 名称 / 别名 /「分类/流程名」/ 关键词"),
keyword: str = Query(""),
category: str = Query(""),
params: bool = Query(True, description="要不要带回参数清单(字段名、类型、必填、可选值)"),
user: CurrentUser = Depends(current_user),
db: Session = Depends(get_db),
) -> dict:
"""能建草稿的流程类型,以及每一类要传哪些参数。
接口号称"传对应参数就能建草稿",前提是先知道参数是哪几个——这一个是给调用方查的,
界面上的发起页用不到它(那边直接拿流程详情渲染表单)。只列这个人发得起来的类型:
发不起的列出去也建不了,``POST /draft`` 那道发起范围的闸会挡回来。
"""
actor = actor_of(user)
if process:
row = drafts.resolve_process(db, process, category=category)
drafts.guard_startable(db, row, actor)
return ok(drafts.type_view(db, row, with_params=params))
rows = drafts.creatable(db, keyword=keyword, category=category)
can = starters.startable_map(
db, rows,
identities=None if user.is_admin else starters.actor_identities(db, actor),
is_admin=user.is_admin,
)
cache = dicts.DictCache(db)
items = [
drafts.type_view(db, row, with_params=params, cache=cache)
for row in rows
if user.is_admin or can.get(row.id)
]
return ok({"total": len(items), "items": items})
@router.post("/draft")
def create_draft(
body: schemas.DraftBody, user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)
) -> dict:
"""建一张流程草稿:任意已发布流程 + 一份表单数据,草稿箱立刻能看到它。
``process`` 写名称就行(五种写法的口径见 :mod:`app.service.drafts`),``data``
原样存进草稿,缺必填不拦——草稿本来就是"先存一半"。一起回出去的 ``notices``
说的是"还差哪几项、哪几个字段这条流程不认识",不是错误,界面上不当警告弹。
``dry_run=true`` 时库里一个字都不写,只回这份体检结果。
"""
process = drafts.resolve_process(db, body.process, category=body.category)
actor = actor_of(user)
if body.dry_run:
title, inspection = drafts.preview(
db, process=process, actor=actor, data=body.data, title=body.title
)
return ok({
"dry_run": True,
"process": process.id,
"process_name": process.name,
"title": title,
"data": inspection.data,
"notices": inspection.notices,
"page_path": drafts.page_path(process.id),
})
row, inspection = drafts.create(db, process=process, actor=actor, data=body.data, title=body.title)
return ok({**drafts.with_page(db, row), "notices": inspection.notices})
@router.put("/draft/{draft_id}")
def update_draft(
draft_id: str,
body: schemas.DraftBody,
user: CurrentUser = Depends(current_user),
db: Session = Depends(get_db),
) -> dict:
row = db.get(models.Draft, draft_id)
if row is None:
raise not_found("草稿不存在")
if row.person != user.person_id:
raise bad_request("无权修改该草稿")
# 不带 process 就是原地改数据(发起页保存草稿就是这么调的);带了就把流程一起换掉,
# 调用方发现类型选错了,换一条流程重存比让他删了重建友好。
process = drafts.resolve_process(db, body.process or row.process, category=body.category)
actor = actor_of(user)
if body.dry_run:
title, inspection = drafts.preview(
db, process=process, actor=actor, data=body.data, title=body.title, current=row.title
)
return ok({
"dry_run": True,
"id": row.id,
"process": process.id,
"process_name": process.name,
"title": title,
"data": inspection.data,
"notices": inspection.notices,
"page_path": drafts.page_path(process.id, row.id),
})
drafts.guard_startable(db, process, actor)
_row, inspection = drafts.build(db, process=process, actor=actor, data=body.data, title=body.title, draft=row)
db.commit()
return ok({**drafts.with_page(db, row), "notices": inspection.notices})
@router.delete("/draft/{draft_id}")
def delete_draft(
draft_id: str, user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)
) -> dict:
row = db.get(models.Draft, draft_id)
if row is None:
raise not_found("草稿不存在")
if row.person != user.person_id and not user.is_admin:
raise bad_request("无权删除该草稿")
db.delete(row)
db.commit()
return ok({"success": True})
# ------------------------------ notifications ----------------------------
@router.get("/notification")
def list_notifications(
user: CurrentUser = Depends(current_user),
db: Session = Depends(get_db),
unread_only: bool = Query(False),
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=100),
) -> dict:
stmt = select(models.Notification).where(models.Notification.identity == user.identity)
if unread_only:
stmt = stmt.where(models.Notification.read.is_(False))
total = int(db.execute(select(func.count()).select_from(stmt.subquery())).scalar() or 0)
rows = db.execute(
stmt.order_by(models.Notification.create_time.desc()).offset((page - 1) * page_size).limit(page_size)
).scalars().all()
return ok(serializers.page([serializers.notification(r) for r in rows], total, page, page_size))
@router.get("/notification/unread/count")
def unread_count(user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)) -> dict:
count = int(
db.execute(
select(func.count(models.Notification.id)).where(
models.Notification.identity == user.identity, models.Notification.read.is_(False)
)
).scalar()
or 0
)
return ok({"count": count})
@router.post("/notification/{notification_id}/read")
def read_notification(
notification_id: str, user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)
) -> dict:
row = db.get(models.Notification, notification_id)
if row is None:
raise not_found("消息不存在")
row.read = True
row.read_time = datetime.now()
db.commit()
return ok({"success": True})
@router.post("/notification/read/all")
def read_all_notifications(user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)) -> dict:
rows = db.execute(
select(models.Notification).where(
models.Notification.identity == user.identity, models.Notification.read.is_(False)
)
).scalars().all()
now = datetime.now()
for row in rows:
row.read = True
row.read_time = now
db.commit()
return ok({"count": len(rows)})
# ------------------------------- statistics ------------------------------
@router.get("/statistics/workbench")
def workbench(user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)) -> dict:
def count(model, *conditions) -> int:
return int(db.execute(select(func.count(model.id)).where(*conditions)).scalar() or 0)
month_start = datetime.now().replace(day=1, hour=0, minute=0, second=0, microsecond=0)
return ok(
{
"processing": count(models.Task, models.Task.identity == user.identity),
"expired": count(models.Task, models.Task.identity == user.identity, models.Task.expired.is_(True)),
"completed": count(models.TaskCompleted, models.TaskCompleted.identity == user.identity),
"created": count(models.Work, models.Work.creator_identity == user.identity),
"created_completed": count(models.WorkCompleted, models.WorkCompleted.creator_identity == user.identity),
"created_total": count(models.Work, models.Work.creator_identity == user.identity)
+ count(models.WorkCompleted, models.WorkCompleted.creator_identity == user.identity),
"read": count(models.Read, models.Read.identity == user.identity),
"unread": count(models.Notification, models.Notification.identity == user.identity, models.Notification.read.is_(False)),
"draft": count(models.Draft, models.Draft.person == user.person_id),
"month_completed": count(models.WorkCompleted, models.WorkCompleted.finish_time >= month_start),
"process_count": count(models.Process, models.Process.enabled.is_(True)),
}
)
@router.get("/statistics/overview")
def overview(
db: Session = Depends(get_db),
user: CurrentUser = Depends(require_permission("statistics:view")),
days: int = Query(30, ge=1, le=365),
) -> dict:
since = datetime.now() - timedelta(days=days)
# 统计口径跟着数据范围走,否则部门主管的报表会把全公司都算进去。
identities = permissions.scope_identity_values(db, user)
def scope(column) -> list:
clause = permissions.in_scope_clause(column, identities)
return [] if clause is None else [clause]
started = db.execute(
select(models.Work.start_time_month, func.count(models.Work.id))
.where(models.Work.start_time >= since, *scope(models.Work.creator_identity))
.group_by(models.Work.start_time_month)
).all()
completed_by_process = db.execute(
select(models.WorkCompleted.process_name, func.count(models.WorkCompleted.id))
.where(models.WorkCompleted.finish_time >= since, *scope(models.WorkCompleted.creator_identity))
.group_by(models.WorkCompleted.process_name)
.order_by(func.count(models.WorkCompleted.id).desc())
.limit(10)
).all()
running_by_process = db.execute(
select(models.Work.process_name, func.count(models.Work.id))
.where(*scope(models.Work.creator_identity))
.group_by(models.Work.process_name)
.order_by(func.count(models.Work.id).desc())
.limit(10)
).all()
daily = db.execute(
select(models.WorkCompleted.finish_time, models.WorkCompleted.duration)
.where(models.WorkCompleted.finish_time >= since, *scope(models.WorkCompleted.creator_identity))
).all()
buckets: dict[str, dict[str, float]] = {}
for finish_time, duration in daily:
if finish_time is None:
continue
key = finish_time.strftime("%Y-%m-%d")
bucket = buckets.setdefault(key, {"count": 0, "duration": 0})
bucket["count"] += 1
bucket["duration"] += duration or 0
trend = [
{
"date": key,
"count": int(value["count"]),
"avg_hours": round(value["duration"] / value["count"] / 3600, 2) if value["count"] else 0,
}
for key, value in sorted(buckets.items())
]
avg_duration = db.execute(
select(func.avg(models.WorkCompleted.duration)).where(
models.WorkCompleted.finish_time >= since, *scope(models.WorkCompleted.creator_identity)
)
).scalar()
return ok(
{
"started_by_month": [{"month": m or "", "count": int(c)} for m, c in started],
"completed_by_process": [{"name": n or "", "count": int(c)} for n, c in completed_by_process],
"running_by_process": [{"name": n or "", "count": int(c)} for n, c in running_by_process],
"trend": trend,
"total_running": int(
db.execute(
select(func.count(models.Work.id)).where(*scope(models.Work.creator_identity))
).scalar()
or 0
),
"total_completed": int(
db.execute(
select(func.count(models.WorkCompleted.id)).where(
*scope(models.WorkCompleted.creator_identity)
)
).scalar()
or 0
),
"avg_duration_hours": round(float(avg_duration or 0) / 3600, 2),
}
)
@router.get("/statistics/process/{process_id}")
def process_statistics(
process_id: str,
db: Session = Depends(get_db),
_: CurrentUser = Depends(require_permission("statistics:view")),
) -> dict:
process = db.get(models.Process, process_id)
if process is None:
raise not_found("流程不存在")
running = int(db.execute(
select(func.count(models.Work.id)).where(models.Work.process == process_id)
).scalar() or 0)
completed_rows = db.execute(
select(models.WorkCompleted.status, func.count(models.WorkCompleted.id))
.where(models.WorkCompleted.process == process_id)
.group_by(models.WorkCompleted.status)
).all()
by_activity = db.execute(
select(models.Task.activity_name, func.count(models.Task.id))
.where(models.Task.process == process_id)
.group_by(models.Task.activity_name)
).all()
avg = db.execute(
select(func.avg(models.WorkCompleted.duration)).where(models.WorkCompleted.process == process_id)
).scalar()
return ok(
{
"process": serializers.process(process),
"running": running,
"completed_by_status": {status: int(count) for status, count in completed_rows},
"pending_by_activity": {name or "": int(count) for name, count in by_activity},
"avg_duration_hours": round(float(avg or 0) / 3600, 2),
}
)
# -------------------------------- settings -------------------------------
@router.get("/settings/public")
def public_settings() -> dict:
"""登录页与浏览器标题要的公开信息。
站点信息存在库里(``config:site``),系统设置页改完保存,这里下一次调用就是
新值,不用重启后端;库里还没有的项回落到 ``backend/config.toml`` 的 ``[site]`` 段。
"""
cfg = hubconfig.get()
return ok(
{
"site_name": settings.site_name,
"site_logo": settings.site_logo,
"site_description": settings.site_description,
"register_enabled": settings.register_enabled,
# 登录页据此决定要不要取验证码、要不要提示"账号由统一身份平台管理",
# 以及"只允许免登"时要不要把用户送回统一门户
"hub": {
"login_enabled": cfg.login_on,
"login_mode": cfg.hub_login_mode,
"auto_provision": cfg.hub_auto_provision,
# sso_enabled:能走免登(地址+应用编码+应用密钥齐了);
# sso_only:本系统不再收账号密码,登录页只留"去统一门户"。
# 应用密钥本身从不出接口,这里只说"配齐没有"。
"sso_enabled": cfg.sso_on,
"sso_configured": cfg.sso_ready,
"sso_only": cfg.sso_only,
"portal_url": cfg.portal_url,
"state_required": cfg.hub_sso_state_required,
},
# 本地会话生命周期归本系统管(对接指南第 8 节:Hub 登出不回收下游会话),
# 前端据此决定要不要跑心跳与空闲计时;0 表示没开
"session": {"idle_minutes": session_idle_minutes()},
}
)
@router.get("/system/info")
def system_info(
db: Session = Depends(get_db),
_: CurrentUser = Depends(require_permission("system:setting")),
) -> dict:
"""当前生效的运行配置快照。
运行配置存在 ``oa_system_setting`` 的 ``config:*`` 行里,在系统设置页改完保存
**立刻生效**,不用重启服务;写入口是 ``PUT /api/v1/config/{组名}``。
只有"引导配置"(MySQL 地址、监听端口、JWT 签名密钥、内置超管初始口令)必须
留在 ``backend/config.toml`` 里——连上数据库之前就得知道它们——那几项改完要重启。
密钥与口令永不外泄,只回"配了没有"。
"""
from .. import dbconfig
snapshot = dbconfig.view()
return ok(
{
"config": {
"kind": "database",
"table": dbconfig.SETTING_TABLE,
"rows": snapshot["store"]["groups"],
"restart_required": False,
"hint": "改配置就在系统设置页保存,存库即生效;引导项在 backend/config.toml,改了要重启",
"revision": snapshot["cache"]["revision"],
"cache_seconds": snapshot["cache"]["seconds"],
"env_overrides": snapshot["env_overrides"],
"env_locks": snapshot["env_locks"],
},
"bootstrap": {
"file": snapshot["bootstrap"]["file"],
"loaded": snapshot["bootstrap"]["loaded"],
"restart_required": True,
**config_module.bootstrap_view(),
},
"site": {
"name": settings.site_name,
"logo": settings.site_logo,
"description": settings.site_description,
"register_enabled": settings.register_enabled,
},
"server": {
"host": settings.host,
"port": settings.port,
"api_prefix": "/api/v1",
"cors_origins": list(settings.cors_origins),
},
"database": {
"host": settings.db_host,
"port": settings.db_port,
"name": settings.db_name,
"connected": ping(),
"auto_create_schema": settings.auto_create_schema,
},
# 令牌参数只回时长与算法,jwt_secret 永不外泄
"security": {
"algorithm": settings.jwt_algorithm,
"access_token_minutes": settings.access_token_minutes,
"refresh_token_days": settings.refresh_token_days,
},
"seed": {"admin_account": settings.admin_account, "demo_data": settings.seed_demo},
"stored": {row["key"]: row["stored_count"] for row in dbconfig.rows_overview(db)},
}
)
# -------------------------------- audit log ------------------------------# -------------------------------- audit log ------------------------------
@router.get("/operation-logs")
def list_operation_logs(
db: Session = Depends(get_db),
user: CurrentUser = Depends(require_permission("log:view")),
action: str = Query(""),
keyword: str = Query(""),
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=200),
) -> dict:
stmt = permissions.scoped(
select(models.OperationLog), user, models.OperationLog.person, permissions.scope_person_ids(db, user)
)
if action:
stmt = stmt.where(models.OperationLog.action == action)
if keyword:
like = f"%{keyword}%"
stmt = stmt.where(or_(models.OperationLog.target.like(like), models.OperationLog.detail.like(like)))
total = int(db.execute(select(func.count()).select_from(stmt.subquery())).scalar() or 0)
rows = db.execute(
stmt.order_by(models.OperationLog.create_time.desc()).offset((page - 1) * page_size).limit(page_size)
).scalars().all()
return ok(serializers.page([serializers.operation_log(r) for r in rows], total, page, page_size))
# ------------------------------ 存储配置 ---------------------------------
@router.get("/system/storage")
def storage_status(_: CurrentUser = Depends(require_permission("system:setting"))) -> dict:
"""文件现在放在哪儿:每个用途走哪个后端、连不连得上、配置存在哪一行。
附件与信息资讯固定进 MinIO,网盘文件走本地磁盘;MinIO 的地址、密钥、桶、
上传路径存在库里的 ``config:storage``,在系统设置页保存即生效
(``PUT /api/v1/config/storage``)。想先验证一组还没保存的 MinIO 参数,用下面的探活接口。
"""
return ok(storage.status_report())
@router.post("/system/storage/reload")
def storage_reload(_: CurrentUser = Depends(require_permission("system:setting"))) -> dict:
"""丢掉存储客户端与探活缓存,按库里的配置重建。
正常情况下不用手动调:界面上保存配置时已经顺手重建过了。多进程部署里想让
某个进程立刻跟上,用 ``POST /api/v1/config/reload``。
"""
from .. import dbconfig
dbconfig.reload()
storage.reset_cache()
return ok(storage.status_report())
@router.post("/system/storage/test")
def storage_test(
backend: str = Query("minio"),
body: schemas.StorageMinioBody | None = None,
_: CurrentUser = Depends(require_permission("system:setting")),
) -> dict:
"""即时探活某个后端。带上表单里的 MinIO 参数就能试还没保存的配置,探活本身不写库。"""
overrides = storage.minio_config_from((body or schemas.StorageMinioBody()).model_dump(exclude_none=True))
return ok(storage.test_backend(backend, overrides if backend == "minio" else None))