提交
This commit is contained in:
1 parent
80138c6388
commit
693e8a678e
682 files changed
+211375
-5306
No files matched your search
@@ -11,12 +11,14 @@ from app.core.database import get_db
|
||||
from app.core.response import error_response, success_response
|
||||
from app.crud.user import user_crud
|
||||
from app.services.issue_user_tokens import issue_tokens_for_user
|
||||
from app.services.wechat_login_service import resolve_wechat_login_user
|
||||
from app.services.wechat_mini_auth import (
|
||||
WechatMiniAuthError,
|
||||
code2session,
|
||||
get_phone_number,
|
||||
)
|
||||
|
||||
|
||||
router = APIRouter(prefix="/mini/auth", tags=["小程序鉴权"])
|
||||
|
||||
|
||||
@@ -34,7 +36,7 @@ async def _resolve_user_id(request: Request, db: Session) -> str:
|
||||
|
||||
@router.post("/wechat-login", response_model=dict)
|
||||
async def wechat_login(body: dict, db: Session = Depends(get_db)):
|
||||
"""微信授权登录:优先 openid;未绑定则用手机号匹配员工并绑定。"""
|
||||
"""微信授权登录:须授权手机号;openid 已绑定也须与账号 phone_no 一致。"""
|
||||
login_code = (body.get("loginCode") or "").strip()
|
||||
phone_code = (body.get("phoneCode") or "").strip() or None
|
||||
|
||||
@@ -43,15 +45,6 @@ async def wechat_login(body: dict, db: Session = Depends(get_db)):
|
||||
except WechatMiniAuthError as exc:
|
||||
return error_response(400, str(exc))
|
||||
|
||||
openid = sess["openid"]
|
||||
user = user_crud.get_by_wx_openid(db, openid)
|
||||
if user:
|
||||
try:
|
||||
data = await issue_tokens_for_user(db, user)
|
||||
except ValueError as exc:
|
||||
return error_response(403, str(exc))
|
||||
return success_response(data)
|
||||
|
||||
if not phone_code:
|
||||
return error_response(400, "请授权手机号登录,或使用账号密码登录")
|
||||
|
||||
@@ -60,27 +53,11 @@ async def wechat_login(body: dict, db: Session = Depends(get_db)):
|
||||
except WechatMiniAuthError as exc:
|
||||
return error_response(400, str(exc))
|
||||
|
||||
users = user_crud.list_active_by_phone_no(db, phone)
|
||||
if not users:
|
||||
return error_response(
|
||||
401, "未找到与该手机号匹配的员工账号,请使用账号密码登录"
|
||||
)
|
||||
if len(users) > 1:
|
||||
return error_response(400, "手机号对应多个账号,请使用账号密码登录")
|
||||
|
||||
user = users[0]
|
||||
other = user_crud.get_by_wx_openid(db, openid)
|
||||
if other and other.id != user.id:
|
||||
return error_response(409, "该微信已绑定其他账号")
|
||||
existing_oid = (getattr(user, "wx_openid", None) or "").strip()
|
||||
if existing_oid and existing_oid != openid:
|
||||
return error_response(409, "该账号已绑定其他微信,请联系管理员")
|
||||
|
||||
user.wx_openid = openid
|
||||
user.update_time = datetime.now()
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
user, err_msg, err_code = resolve_wechat_login_user(
|
||||
db, openid=sess["openid"], phone=phone
|
||||
)
|
||||
if err_msg:
|
||||
return error_response(err_code or 400, err_msg)
|
||||
|
||||
try:
|
||||
data = await issue_tokens_for_user(db, user)
|
||||
|
||||
+28
-37
@@ -1,8 +1,9 @@
|
||||
"""公共接口(Web 登录、刷新 Token、登出;用户模型对齐 docs/sql/zkxw.sql 基线)"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, UploadFile, File
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, UploadFile, File
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -37,43 +38,11 @@ from app.services.web_auth_roles import (
|
||||
)
|
||||
from app.schemas.auth import ProfileUpdateRequest
|
||||
from app.crud.user import update_user, change_password
|
||||
from app.services.issue_user_tokens import build_user_info_payload
|
||||
|
||||
router = APIRouter(prefix="", tags=["公共接口"])
|
||||
|
||||
|
||||
def _avatar_url_field(user: SysUser) -> Optional[str]:
|
||||
"""返回库中原始头像路径,由前端按 VITE_MINIO_BASE_URL 拼展示 URL。"""
|
||||
raw = getattr(user, "avatar", None)
|
||||
if not raw:
|
||||
return None
|
||||
s = str(raw).strip()
|
||||
return s if s else None
|
||||
|
||||
|
||||
def _build_user_info_payload(user: SysUser, web_role: str, role_names: list = None) -> dict:
|
||||
"""与 web-admin `userInfo` 字段约定一致。"""
|
||||
phone = (getattr(user, "phone_no", None) or "").strip() or None
|
||||
return {
|
||||
"id": user.id,
|
||||
"username": user.user_no,
|
||||
"realName": user.nick_name,
|
||||
"phone": phone,
|
||||
"email": (getattr(user, "email", None) or "").strip() or None,
|
||||
"hireDate": user.hire_date.strftime("%Y-%m-%d") if getattr(user, "hire_date", None) else None,
|
||||
"probationMonths": getattr(user, "probation_months", None),
|
||||
"lastWorkDay": user.last_work_day.strftime("%Y-%m-%d")
|
||||
if getattr(user, "last_work_day", None)
|
||||
else None,
|
||||
"sex": getattr(user, "sex", None) or "0",
|
||||
"remark": (getattr(user, "remark", None) or "").strip() or None,
|
||||
"role": web_role,
|
||||
"roleNames": role_names or [],
|
||||
"regionId": user.dept_id,
|
||||
"regionName": None,
|
||||
"avatarUrl": _avatar_url_field(user),
|
||||
}
|
||||
|
||||
|
||||
def _build_current_user_payload(current_user: dict) -> dict:
|
||||
"""组装 current-user 接口响应。"""
|
||||
au = current_user.get("avatar_url")
|
||||
@@ -90,7 +59,9 @@ def _build_current_user_payload(current_user: dict) -> dict:
|
||||
"roleNames": current_user.get("role_names") or current_user.get("roleNames") or [],
|
||||
"isSuperAdmin": current_user.get("role") == "super_admin",
|
||||
"regionId": current_user.get("region_id"),
|
||||
"regionName": None,
|
||||
"regionName": current_user.get("region_name") or current_user.get("dept_name"),
|
||||
"deptName": current_user.get("dept_name") or current_user.get("region_name"),
|
||||
"postNames": current_user.get("post_names") or [],
|
||||
"regionIds": [],
|
||||
"isActive": current_user.get("is_active"),
|
||||
"avatarUrl": avatar_url if avatar_url else None,
|
||||
@@ -179,7 +150,7 @@ async def web_login(
|
||||
"token": access_token,
|
||||
"refreshToken": refresh_token,
|
||||
"expiresIn": settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
|
||||
"userInfo": _build_user_info_payload(user, web_role, role_names),
|
||||
"userInfo": build_user_info_payload(user, web_role, role_names, db=db),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -305,7 +276,7 @@ async def update_current_user_profile(
|
||||
return error_response(404, "用户不存在")
|
||||
web_role = resolve_web_role_for_user(db, user.id)
|
||||
role_names = get_user_role_names(db, user.id)
|
||||
return success_response(_build_user_info_payload(user, web_role, role_names))
|
||||
return success_response(build_user_info_payload(user, web_role, role_names, db=db))
|
||||
except HTTPException:
|
||||
return error_response(401, "Token无效或已过期")
|
||||
except ValueError as exc:
|
||||
@@ -416,3 +387,23 @@ async def get_web_auth_menu_codes(request: Request, db: Session = Depends(get_db
|
||||
)
|
||||
except HTTPException:
|
||||
return error_response(401, "Token无效或已过期")
|
||||
|
||||
|
||||
@router.get("/cn-holiday/range", response_model=dict)
|
||||
def cn_holiday_range(
|
||||
start: str = Query(..., description="YYYY-MM-DD"),
|
||||
end: str = Query(..., description="YYYY-MM-DD"),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""查询闭区间内每日节假日/休息日标志(只读本地缓存表)。"""
|
||||
try:
|
||||
start_d = datetime.strptime(start.strip(), "%Y-%m-%d").date()
|
||||
end_d = datetime.strptime(end.strip(), "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="start/end 须为 YYYY-MM-DD")
|
||||
if end_d < start_d:
|
||||
raise HTTPException(status_code=400, detail="end 不能早于 start")
|
||||
from app.services.cn_holiday import list_day_flags
|
||||
|
||||
days = list_day_flags(db, start_d, end_d)
|
||||
return success_response({"days": days})
|
||||
@@ -232,6 +232,10 @@ async def get_current_user_by_token(
|
||||
s = str(avatar_raw).strip()
|
||||
avatar_stored = s if s else None
|
||||
|
||||
from app.services.issue_user_tokens import resolve_user_org_labels
|
||||
|
||||
dept_name, post_names = resolve_user_org_labels(db, user)
|
||||
|
||||
current_user_dept_id.set(user.dept_id or "")
|
||||
|
||||
return {
|
||||
@@ -240,7 +244,11 @@ async def get_current_user_by_token(
|
||||
"real_name": user.nick_name,
|
||||
"role": web_role,
|
||||
"role_names": role_names,
|
||||
"tenant_no": (getattr(user, "tenant_no", None) or "").strip() or None,
|
||||
"region_id": user.dept_id,
|
||||
"region_name": dept_name,
|
||||
"dept_name": dept_name,
|
||||
"post_names": post_names,
|
||||
"phone": phone,
|
||||
"email": email,
|
||||
"sex": getattr(user, "sex", None) or "0",
|
||||
|
||||
@@ -143,6 +143,11 @@ class Settings(BaseSettings):
|
||||
"/api/invoice/download"
|
||||
)
|
||||
|
||||
# 中国节假日日历(ailcc)同步
|
||||
CN_HOLIDAY_API_BASE: str = "https://holiday.ailcc.com"
|
||||
CN_HOLIDAY_HTTP_TIMEOUT_SEC: int = 15
|
||||
CN_HOLIDAY_HTTP_RETRIES: int = 2
|
||||
|
||||
class Config:
|
||||
# 支持通过 ENV_FILE 指定环境文件;未指定时回退到 backend/.env
|
||||
_default_env_file = Path(__file__).resolve().parents[2] / ".env"
|
||||
|
||||
@@ -209,6 +209,9 @@ def list_apps(
|
||||
like = f"%{kw}%"
|
||||
q = q.filter(OaApp.app_name.like(like))
|
||||
rows = q.order_by(OaApp.order_num.asc(), OaApp.create_time.desc()).all()
|
||||
if not rows:
|
||||
return []
|
||||
|
||||
group_ids = list({r.group_id for r in rows if r.group_id})
|
||||
group_names: Dict[str, str] = {}
|
||||
if group_ids:
|
||||
@@ -218,37 +221,46 @@ def list_apps(
|
||||
.all()
|
||||
):
|
||||
group_names[g.id] = g.group_name
|
||||
out: List[Dict[str, Any]] = []
|
||||
for r in rows:
|
||||
draft = (
|
||||
db.query(OaAppVersion.id)
|
||||
|
||||
app_ids = [r.id for r in rows]
|
||||
# 批量取草稿/最新发布版本号,避免 N+1,且不拉取 form/flow 大 JSON
|
||||
draft_app_ids = {
|
||||
app_id
|
||||
for (app_id,) in (
|
||||
db.query(OaAppVersion.app_id)
|
||||
.filter(
|
||||
OaAppVersion.app_id == r.id,
|
||||
OaAppVersion.app_id.in_(app_ids),
|
||||
OaAppVersion.tenant_no == tenant_no,
|
||||
OaAppVersion.status == "draft",
|
||||
OaAppVersion.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
pub = (
|
||||
db.query(OaAppVersion)
|
||||
}
|
||||
latest_published: Dict[str, int] = {
|
||||
app_id: version_no
|
||||
for app_id, version_no in (
|
||||
db.query(OaAppVersion.app_id, OaAppVersion.version_no)
|
||||
.filter(
|
||||
OaAppVersion.app_id == r.id,
|
||||
OaAppVersion.app_id.in_(app_ids),
|
||||
OaAppVersion.tenant_no == tenant_no,
|
||||
OaAppVersion.is_latest_published == "1",
|
||||
OaAppVersion.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
.all()
|
||||
)
|
||||
out.append(
|
||||
_app_to_dict(
|
||||
r,
|
||||
group_name=group_names.get(r.group_id or "", ""),
|
||||
has_draft=bool(draft),
|
||||
latest_published=pub.version_no if pub else None,
|
||||
)
|
||||
}
|
||||
|
||||
return [
|
||||
_app_to_dict(
|
||||
r,
|
||||
group_name=group_names.get(r.group_id or "", ""),
|
||||
has_draft=r.id in draft_app_ids,
|
||||
latest_published=latest_published.get(r.id),
|
||||
)
|
||||
return out
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def _create_version(
|
||||
|
||||
+161
-23
@@ -289,41 +289,179 @@ def _empty_user_relation_fields(d: Dict[str, Any]) -> None:
|
||||
|
||||
|
||||
def _attach_user_relations(db: Session, d: Dict[str, Any], user_id: str) -> None:
|
||||
"""为用户 dict 补全职位/角色关联字段(与详情接口字段一致)。"""
|
||||
from app.services.web_auth_roles import (
|
||||
get_effective_role_ids,
|
||||
get_post_inherited_role_ids,
|
||||
get_role_names_by_ids,
|
||||
)
|
||||
|
||||
role_ids = [
|
||||
r.role_id
|
||||
for r in db.query(SysUserRole)
|
||||
.filter(and_(SysUserRole.user_id == user_id, SysUserRole.del_flag == 0))
|
||||
.all()
|
||||
]
|
||||
post_ids = list_post_ids_for_user(db, user_id)
|
||||
effective_role_ids = get_effective_role_ids(db, user_id)
|
||||
post_inherited_role_ids = get_post_inherited_role_ids(db, user_id)
|
||||
d["roleIds"] = role_ids
|
||||
d["postIds"] = post_ids
|
||||
d["postInheritedRoleIds"] = post_inherited_role_ids
|
||||
d["effectiveRoleIds"] = effective_role_ids
|
||||
d["effectiveRoleNames"] = get_role_names_by_ids(db, effective_role_ids)
|
||||
"""为单个用户 dict 补全职位/角色关联字段(与详情接口字段一致)。"""
|
||||
if not d.get("id"):
|
||||
d["id"] = user_id
|
||||
enrich_user_dicts_with_relations(db, [d])
|
||||
|
||||
|
||||
def enrich_user_dicts_with_relations(
|
||||
db: Session, items: List[Dict[str, Any]]
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""批量就地补全列表项的职位/角色关联字段,供列表列展示。"""
|
||||
"""批量就地补全列表项的职位/角色关联字段,供列表列展示。
|
||||
|
||||
使用固定次数的 IN 查询,避免按用户 N+1(远程库 RTT 下可达数秒)。
|
||||
"""
|
||||
if not items:
|
||||
return items
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models.models import SysPost, SysPostRole, SysRole
|
||||
|
||||
tenant = settings.DEFAULT_TENANT_NO
|
||||
user_ids: List[str] = []
|
||||
seen_uids: set = set()
|
||||
for d in items:
|
||||
uid = str(d.get("id") or "").strip()
|
||||
if not uid:
|
||||
_empty_user_relation_fields(d)
|
||||
continue
|
||||
_attach_user_relations(db, d, uid)
|
||||
if uid not in seen_uids:
|
||||
seen_uids.add(uid)
|
||||
user_ids.append(uid)
|
||||
|
||||
if not user_ids:
|
||||
return items
|
||||
|
||||
role_ids_by_user: Dict[str, List[str]] = {uid: [] for uid in user_ids}
|
||||
for row in (
|
||||
db.query(SysUserRole.user_id, SysUserRole.role_id)
|
||||
.filter(SysUserRole.user_id.in_(user_ids), SysUserRole.del_flag == 0)
|
||||
.all()
|
||||
):
|
||||
uid, rid = str(row[0] or ""), str(row[1] or "")
|
||||
if uid in role_ids_by_user and rid:
|
||||
role_ids_by_user[uid].append(rid)
|
||||
|
||||
post_ids_by_user: Dict[str, List[str]] = {uid: [] for uid in user_ids}
|
||||
all_post_ids: List[str] = []
|
||||
seen_posts: set = set()
|
||||
for row in (
|
||||
db.query(SysUserPost.user_id, SysUserPost.post_id)
|
||||
.filter(SysUserPost.user_id.in_(user_ids), SysUserPost.del_flag == 0)
|
||||
.all()
|
||||
):
|
||||
uid, pid = str(row[0] or ""), str(row[1] or "")
|
||||
if uid in post_ids_by_user and pid:
|
||||
post_ids_by_user[uid].append(pid)
|
||||
if pid not in seen_posts:
|
||||
seen_posts.add(pid)
|
||||
all_post_ids.append(pid)
|
||||
|
||||
enabled_post_ids: set = set()
|
||||
if all_post_ids:
|
||||
enabled_post_ids = {
|
||||
str(r[0])
|
||||
for r in db.query(SysPost.id)
|
||||
.filter(
|
||||
SysPost.id.in_(all_post_ids),
|
||||
SysPost.del_flag == 0,
|
||||
SysPost.status == "1",
|
||||
SysPost.tenant_no == tenant,
|
||||
)
|
||||
.all()
|
||||
if r[0]
|
||||
}
|
||||
|
||||
post_role_ids: Dict[str, List[str]] = {pid: [] for pid in enabled_post_ids}
|
||||
if enabled_post_ids:
|
||||
for row in (
|
||||
db.query(SysPostRole.post_id, SysRole.id)
|
||||
.join(SysRole, SysRole.id == SysPostRole.role_id)
|
||||
.filter(
|
||||
SysPostRole.post_id.in_(list(enabled_post_ids)),
|
||||
SysPostRole.del_flag == 0,
|
||||
SysPostRole.tenant_no == tenant,
|
||||
SysRole.del_flag == 0,
|
||||
SysRole.status == "1",
|
||||
SysRole.tenant_no == tenant,
|
||||
)
|
||||
.order_by(SysRole.create_time.desc())
|
||||
.all()
|
||||
):
|
||||
pid, rid = str(row[0] or ""), str(row[1] or "")
|
||||
if pid in post_role_ids and rid and rid not in post_role_ids[pid]:
|
||||
post_role_ids[pid].append(rid)
|
||||
|
||||
enabled_direct_by_user: Dict[str, List[str]] = {uid: [] for uid in user_ids}
|
||||
for row in (
|
||||
db.query(SysUserRole.user_id, SysRole.id)
|
||||
.join(SysRole, SysRole.id == SysUserRole.role_id)
|
||||
.filter(
|
||||
SysUserRole.user_id.in_(user_ids),
|
||||
SysUserRole.del_flag == 0,
|
||||
SysUserRole.tenant_no == tenant,
|
||||
SysRole.del_flag == 0,
|
||||
SysRole.status == "1",
|
||||
SysRole.tenant_no == tenant,
|
||||
)
|
||||
.order_by(SysRole.create_time.desc())
|
||||
.all()
|
||||
):
|
||||
uid, rid = str(row[0] or ""), str(row[1] or "")
|
||||
if uid in enabled_direct_by_user and rid and rid not in enabled_direct_by_user[uid]:
|
||||
enabled_direct_by_user[uid].append(rid)
|
||||
|
||||
inherited_by_user: Dict[str, List[str]] = {}
|
||||
effective_by_user: Dict[str, List[str]] = {}
|
||||
all_effective: List[str] = []
|
||||
seen_eff: set = set()
|
||||
for uid in user_ids:
|
||||
post_inherited: List[str] = []
|
||||
seen_inh: set = set()
|
||||
for pid in post_ids_by_user.get(uid, []):
|
||||
if pid not in enabled_post_ids:
|
||||
continue
|
||||
for rid in post_role_ids.get(pid, []):
|
||||
if rid not in seen_inh:
|
||||
seen_inh.add(rid)
|
||||
post_inherited.append(rid)
|
||||
inherited_by_user[uid] = post_inherited
|
||||
effective: List[str] = []
|
||||
seen_e: set = set()
|
||||
for rid in enabled_direct_by_user.get(uid, []) + post_inherited:
|
||||
if rid not in seen_e:
|
||||
seen_e.add(rid)
|
||||
effective.append(rid)
|
||||
effective_by_user[uid] = effective
|
||||
for rid in effective:
|
||||
if rid not in seen_eff:
|
||||
seen_eff.add(rid)
|
||||
all_effective.append(rid)
|
||||
|
||||
name_by_id: Dict[str, str] = {}
|
||||
if all_effective:
|
||||
for rid, name in (
|
||||
db.query(SysRole.id, SysRole.role_name)
|
||||
.filter(
|
||||
SysRole.id.in_(all_effective),
|
||||
SysRole.del_flag == 0,
|
||||
SysRole.status == "1",
|
||||
SysRole.tenant_no == tenant,
|
||||
)
|
||||
.all()
|
||||
):
|
||||
if rid and name:
|
||||
name_by_id[str(rid).strip()] = str(name).strip()
|
||||
|
||||
for d in items:
|
||||
uid = str(d.get("id") or "").strip()
|
||||
if not uid:
|
||||
continue
|
||||
effective = effective_by_user.get(uid, [])
|
||||
d["roleIds"] = role_ids_by_user.get(uid, [])
|
||||
d["postIds"] = post_ids_by_user.get(uid, [])
|
||||
d["postInheritedRoleIds"] = inherited_by_user.get(uid, [])
|
||||
d["effectiveRoleIds"] = effective
|
||||
names: List[str] = []
|
||||
seen_n: set = set()
|
||||
for rid in effective:
|
||||
name = name_by_id.get(rid)
|
||||
if name and name not in seen_n:
|
||||
seen_n.add(name)
|
||||
names.append(name)
|
||||
d["effectiveRoleNames"] = names
|
||||
|
||||
return items
|
||||
|
||||
|
||||
|
||||
@@ -30,8 +30,20 @@ async def lifespan(app: FastAPI):
|
||||
except Exception as e:
|
||||
logging.warning("定时任务调度器启动失败: %s", e)
|
||||
|
||||
from app.services.cn_holiday_sync import start_cn_holiday_sync_loop, stop_cn_holiday_sync_loop
|
||||
|
||||
try:
|
||||
start_cn_holiday_sync_loop(SessionLocal)
|
||||
except Exception as e:
|
||||
logging.warning("节假日同步线程启动失败: %s", e)
|
||||
|
||||
yield
|
||||
|
||||
try:
|
||||
stop_cn_holiday_sync_loop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
from app.tasks import shutdown_scheduler
|
||||
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""中国节假日日历缓存模型"""
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import Column, Date, DateTime, SmallInteger, String, Text, UniqueConstraint
|
||||
|
||||
from app.core.database import Base
|
||||
|
||||
|
||||
class SysCnHolidayDay(Base):
|
||||
"""中国节假日日历缓存 sys_cn_holiday_day"""
|
||||
|
||||
__tablename__ = "sys_cn_holiday_day"
|
||||
__table_args__ = (UniqueConstraint("day_date", name="uk_day_date"),)
|
||||
|
||||
id = Column(String(64), primary_key=True, comment="UUID")
|
||||
day_date = Column(Date, nullable=False, comment="日历日")
|
||||
day_type = Column(SmallInteger, nullable=False, comment="0工作日1周末2节日3调休放假4补班")
|
||||
day_name = Column(String(64), nullable=True, comment="名称")
|
||||
week = Column(SmallInteger, nullable=True, comment="1-7周一到周日")
|
||||
is_rest_day = Column(SmallInteger, nullable=False, default=0, comment="1休息0工作")
|
||||
raw_json = Column(Text, nullable=True, comment="原始JSON片段")
|
||||
sync_time = Column(DateTime, nullable=True, comment="同步时间")
|
||||
create_time = Column(DateTime, nullable=True, default=datetime.now, comment="创建时间")
|
||||
update_time = Column(DateTime, nullable=True, default=datetime.now, onupdate=datetime.now, comment="更新时间")
|
||||
@@ -3949,3 +3949,4 @@ from app.models.material import ( # noqa: E402,F401
|
||||
BizMaterialStockLog,
|
||||
)
|
||||
from app.models.clinical_payment import BizPilotPayment # noqa: E402,F401
|
||||
from app.models.cn_holiday import SysCnHolidayDay # noqa: E402,F401
|
||||
@@ -0,0 +1,65 @@
|
||||
"""中国节假日日历只读服务"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.cn_holiday import SysCnHolidayDay
|
||||
|
||||
|
||||
def is_rest_day(db: Session, d: date) -> bool:
|
||||
"""查表判定是否休息日;无行则按周六日回退。"""
|
||||
row: Optional[SysCnHolidayDay] = (
|
||||
db.query(SysCnHolidayDay).filter(SysCnHolidayDay.day_date == d).first()
|
||||
)
|
||||
if row is None:
|
||||
return d.weekday() >= 5
|
||||
if row.is_rest_day is not None:
|
||||
return int(row.is_rest_day) == 1
|
||||
return int(row.day_type or 0) in (1, 2, 3)
|
||||
|
||||
|
||||
def list_day_flags(db: Session, start: date, end: date) -> List[Dict[str, Any]]:
|
||||
"""返回 [start, end] 闭区间每日标志;缺行用周末回退补齐。"""
|
||||
if end < start:
|
||||
return []
|
||||
|
||||
rows = (
|
||||
db.query(SysCnHolidayDay)
|
||||
.filter(SysCnHolidayDay.day_date >= start, SysCnHolidayDay.day_date <= end)
|
||||
.all()
|
||||
)
|
||||
by_date = {r.day_date: r for r in rows}
|
||||
|
||||
out: List[Dict[str, Any]] = []
|
||||
cur = start
|
||||
while cur <= end:
|
||||
row = by_date.get(cur)
|
||||
if row is not None:
|
||||
rest = (
|
||||
int(row.is_rest_day) == 1
|
||||
if row.is_rest_day is not None
|
||||
else int(row.day_type or 0) in (1, 2, 3)
|
||||
)
|
||||
out.append(
|
||||
{
|
||||
"dayDate": cur.isoformat(),
|
||||
"dayType": int(row.day_type),
|
||||
"isRestDay": rest,
|
||||
"dayName": row.day_name,
|
||||
}
|
||||
)
|
||||
else:
|
||||
is_weekend = cur.weekday() >= 5
|
||||
out.append(
|
||||
{
|
||||
"dayDate": cur.isoformat(),
|
||||
"dayType": 1 if is_weekend else 0,
|
||||
"isRestDay": is_weekend,
|
||||
"dayName": None,
|
||||
}
|
||||
)
|
||||
cur += timedelta(days=1)
|
||||
return out
|
||||
@@ -0,0 +1,243 @@
|
||||
"""中国节假日日历同步(ailcc batch)与进程内后台循环"""
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from app.core.config import settings
|
||||
from app.models.cn_holiday import SysCnHolidayDay
|
||||
|
||||
logger = logging.getLogger("sqxp.cn_holiday_sync")
|
||||
|
||||
_sync_lock = threading.Lock()
|
||||
_stop_event: Optional[threading.Event] = None
|
||||
_thread: Optional[threading.Thread] = None
|
||||
_loop_lock = threading.Lock()
|
||||
|
||||
|
||||
def _is_rest_from_type(day_type: int) -> int:
|
||||
return 1 if int(day_type) in (1, 2, 3) else 0
|
||||
|
||||
|
||||
def map_ailcc_day_row(
|
||||
date_str: str,
|
||||
holiday: Optional[Dict[str, Any]],
|
||||
type_info: Optional[Dict[str, Any]],
|
||||
) -> Dict[str, Any]:
|
||||
"""Normalize one day for upsert fields."""
|
||||
d = datetime.strptime(date_str, "%Y-%m-%d").date()
|
||||
if type_info and type_info.get("type") is not None:
|
||||
day_type = int(type_info["type"])
|
||||
day_name = type_info.get("name") or (holiday or {}).get("name")
|
||||
week = type_info.get("week")
|
||||
if week is None:
|
||||
week = d.isoweekday()
|
||||
else:
|
||||
week = int(week)
|
||||
else:
|
||||
# Infer from weekday: Sat/Sun → weekend(1), else workday(0)
|
||||
is_weekend = d.weekday() >= 5
|
||||
day_type = 1 if is_weekend else 0
|
||||
day_name = (holiday or {}).get("name") if holiday else None
|
||||
week = d.isoweekday()
|
||||
|
||||
raw = {"date": date_str, "holiday": holiday, "type": type_info}
|
||||
return {
|
||||
"day_date": d,
|
||||
"day_type": day_type,
|
||||
"day_name": day_name,
|
||||
"week": week,
|
||||
"is_rest_day": _is_rest_from_type(day_type),
|
||||
"raw_json": json.dumps(raw, ensure_ascii=False),
|
||||
}
|
||||
|
||||
|
||||
def iter_month_dates(year: int, month: int) -> List[str]:
|
||||
_, last = calendar.monthrange(year, month)
|
||||
return [date(year, month, day).isoformat() for day in range(1, last + 1)]
|
||||
|
||||
|
||||
def _years_to_sync(today: Optional[date] = None) -> List[int]:
|
||||
today = today or date.today()
|
||||
return [today.year, today.year + 1]
|
||||
|
||||
|
||||
def _months_for_year(year: int) -> List[Tuple[int, int]]:
|
||||
return [(year, m) for m in range(1, 13)]
|
||||
|
||||
|
||||
def _fetch_batch(date_strs: List[str]) -> Dict[str, Any]:
|
||||
"""GET batch API with retries. Raises on persistent failure."""
|
||||
base = (settings.CN_HOLIDAY_API_BASE or "").rstrip("/")
|
||||
params = urlencode({"d": ",".join(date_strs), "type": "Y"})
|
||||
url = f"{base}/api/holiday/batch?{params}"
|
||||
timeout = int(settings.CN_HOLIDAY_HTTP_TIMEOUT_SEC or 15)
|
||||
retries = max(0, int(settings.CN_HOLIDAY_HTTP_RETRIES or 0))
|
||||
last_err: Optional[BaseException] = None
|
||||
for attempt in range(retries + 1):
|
||||
try:
|
||||
req = Request(url, method="GET", headers={"Accept": "application/json"})
|
||||
with urlopen(req, timeout=timeout) as resp:
|
||||
body = resp.read().decode("utf-8")
|
||||
data = json.loads(body)
|
||||
if not isinstance(data, dict) or int(data.get("code", -1)) != 0:
|
||||
raise RuntimeError(f"ailcc batch unexpected response: {body[:500]}")
|
||||
return data
|
||||
except Exception as exc: # noqa: BLE001 — retry then raise
|
||||
last_err = exc
|
||||
logger.warning(
|
||||
"cn_holiday batch fetch failed attempt=%s/%s: %s",
|
||||
attempt + 1,
|
||||
retries + 1,
|
||||
exc,
|
||||
)
|
||||
if attempt < retries:
|
||||
time.sleep(0.5 * (attempt + 1))
|
||||
assert last_err is not None
|
||||
raise last_err
|
||||
|
||||
|
||||
def _days_in_year(year: int) -> int:
|
||||
return 366 if calendar.isleap(year) else 365
|
||||
|
||||
|
||||
def is_year_calendar_complete(session: Any, year: int) -> bool:
|
||||
"""True when the year already has one row per calendar day."""
|
||||
start = date(year, 1, 1)
|
||||
end = date(year, 12, 31)
|
||||
cnt = (
|
||||
session.query(SysCnHolidayDay)
|
||||
.filter(SysCnHolidayDay.day_date >= start, SysCnHolidayDay.day_date <= end)
|
||||
.count()
|
||||
)
|
||||
return int(cnt) >= _days_in_year(year)
|
||||
|
||||
|
||||
def sync_cn_holidays(db_session_factory: Callable[[], Any]) -> int:
|
||||
"""Fetch current + next year month-by-month; upsert by day_date. Return rows written.
|
||||
|
||||
Skip any year that already has a full calendar (row count >= days in that year).
|
||||
"""
|
||||
with _sync_lock:
|
||||
written = 0
|
||||
session = db_session_factory()
|
||||
try:
|
||||
now = datetime.now()
|
||||
for year in _years_to_sync():
|
||||
if is_year_calendar_complete(session, year):
|
||||
logger.info("cn_holiday skip year=%s (calendar already complete)", year)
|
||||
continue
|
||||
for y, month in _months_for_year(year):
|
||||
date_strs = iter_month_dates(y, month)
|
||||
payload = _fetch_batch(date_strs)
|
||||
holiday_map = payload.get("holiday") or {}
|
||||
type_map = payload.get("type") or {}
|
||||
for ds in date_strs:
|
||||
holiday = holiday_map.get(ds)
|
||||
type_info = type_map.get(ds)
|
||||
mapped = map_ailcc_day_row(ds, holiday, type_info)
|
||||
existing = (
|
||||
session.query(SysCnHolidayDay)
|
||||
.filter(SysCnHolidayDay.day_date == mapped["day_date"])
|
||||
.first()
|
||||
)
|
||||
if existing is None:
|
||||
row = SysCnHolidayDay(
|
||||
id=uuid.uuid4().hex,
|
||||
day_date=mapped["day_date"],
|
||||
day_type=mapped["day_type"],
|
||||
day_name=mapped["day_name"],
|
||||
week=mapped["week"],
|
||||
is_rest_day=mapped["is_rest_day"],
|
||||
raw_json=mapped["raw_json"],
|
||||
sync_time=now,
|
||||
create_time=now,
|
||||
update_time=now,
|
||||
)
|
||||
session.add(row)
|
||||
else:
|
||||
existing.day_type = mapped["day_type"]
|
||||
existing.day_name = mapped["day_name"]
|
||||
existing.week = mapped["week"]
|
||||
existing.is_rest_day = mapped["is_rest_day"]
|
||||
existing.raw_json = mapped["raw_json"]
|
||||
existing.sync_time = now
|
||||
existing.update_time = now
|
||||
written += 1
|
||||
session.commit()
|
||||
logger.info("cn_holiday sync ok rows=%s", written)
|
||||
return written
|
||||
except Exception:
|
||||
session.rollback()
|
||||
logger.exception("cn_holiday sync failed")
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def seconds_until_next_local_midnight(now: Optional[datetime] = None) -> float:
|
||||
now = now or datetime.now()
|
||||
# Always wait until the next calendar midnight (if already 00:00:00 → +1 day)
|
||||
nxt = now.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1)
|
||||
return max(0.0, (nxt - now).total_seconds())
|
||||
|
||||
|
||||
def _loop_body(db_session_factory: Callable[[], Any], stop_event: threading.Event) -> None:
|
||||
try:
|
||||
sync_cn_holidays(db_session_factory)
|
||||
except Exception:
|
||||
logger.exception("cn_holiday initial sync failed; will retry at next midnight")
|
||||
while not stop_event.is_set():
|
||||
wait_sec = seconds_until_next_local_midnight()
|
||||
# Wait in chunks so stop responds quickly
|
||||
end_at = time.time() + wait_sec
|
||||
while not stop_event.is_set():
|
||||
remaining = end_at - time.time()
|
||||
if remaining <= 0:
|
||||
break
|
||||
stop_event.wait(timeout=min(remaining, 1.0))
|
||||
if stop_event.is_set():
|
||||
break
|
||||
try:
|
||||
sync_cn_holidays(db_session_factory)
|
||||
except Exception:
|
||||
logger.exception("cn_holiday midnight sync failed; keep old cache")
|
||||
|
||||
|
||||
def start_cn_holiday_sync_loop(db_session_factory: Callable[[], Any]) -> None:
|
||||
"""Start daemon thread if not running: sync immediately, then each local midnight."""
|
||||
global _stop_event, _thread
|
||||
with _loop_lock:
|
||||
if _thread is not None and _thread.is_alive():
|
||||
return
|
||||
_stop_event = threading.Event()
|
||||
t = threading.Thread(
|
||||
target=_loop_body,
|
||||
args=(db_session_factory, _stop_event),
|
||||
name="cn-holiday-sync",
|
||||
daemon=True,
|
||||
)
|
||||
_thread = t
|
||||
t.start()
|
||||
|
||||
|
||||
def stop_cn_holiday_sync_loop(timeout: float = 2.0) -> None:
|
||||
"""Set stop event and join the sync thread."""
|
||||
global _stop_event, _thread
|
||||
with _loop_lock:
|
||||
ev = _stop_event
|
||||
t = _thread
|
||||
if ev is not None:
|
||||
ev.set()
|
||||
if t is not None and t.is_alive():
|
||||
t.join(timeout=timeout)
|
||||
_thread = None
|
||||
_stop_event = None
|
||||
@@ -1,7 +1,7 @@
|
||||
"""为已通过校验的 SysUser 签发与 web 登录一致的 JWT 会话包。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
@@ -13,7 +13,8 @@ from app.core.auth import (
|
||||
)
|
||||
from app.core.config import settings
|
||||
from app.core.utils import generate_uuid
|
||||
from app.models.models import SysUser
|
||||
from app.crud.user import list_post_ids_for_user
|
||||
from app.models.models import SysDept, SysPost, SysUser
|
||||
from app.services.web_auth_roles import (
|
||||
get_user_role_names,
|
||||
resolve_web_role_for_user,
|
||||
@@ -29,8 +30,48 @@ def _avatar_url_field(user: SysUser) -> Optional[str]:
|
||||
return s if s else None
|
||||
|
||||
|
||||
def build_user_info_payload(user: SysUser, web_role: str, role_names: list = None) -> dict:
|
||||
def resolve_user_org_labels(db: Session, user: SysUser) -> Tuple[Optional[str], List[str]]:
|
||||
"""解析用户所属部门名称与职位名称列表(保序)。"""
|
||||
dept_name: Optional[str] = None
|
||||
dept_id = (getattr(user, "dept_id", None) or "").strip()
|
||||
if dept_id:
|
||||
dept = (
|
||||
db.query(SysDept)
|
||||
.filter(SysDept.id == dept_id, SysDept.del_flag == 0)
|
||||
.first()
|
||||
)
|
||||
if dept and (dept.dept_name or "").strip():
|
||||
dept_name = str(dept.dept_name).strip()
|
||||
|
||||
post_names: List[str] = []
|
||||
post_ids = list_post_ids_for_user(db, user.id)
|
||||
if post_ids:
|
||||
posts = (
|
||||
db.query(SysPost)
|
||||
.filter(SysPost.id.in_(post_ids), SysPost.del_flag == 0)
|
||||
.all()
|
||||
)
|
||||
name_map = {
|
||||
p.id: str(p.post_name).strip()
|
||||
for p in posts
|
||||
if p.id and (p.post_name or "").strip()
|
||||
}
|
||||
post_names = [name_map[pid] for pid in post_ids if pid in name_map]
|
||||
return dept_name, post_names
|
||||
|
||||
|
||||
def build_user_info_payload(
|
||||
user: SysUser,
|
||||
web_role: str,
|
||||
role_names: list = None,
|
||||
*,
|
||||
db: Session = None,
|
||||
) -> dict:
|
||||
phone = (getattr(user, "phone_no", None) or "").strip() or None
|
||||
dept_name: Optional[str] = None
|
||||
post_names: List[str] = []
|
||||
if db is not None:
|
||||
dept_name, post_names = resolve_user_org_labels(db, user)
|
||||
return {
|
||||
"id": user.id,
|
||||
"username": user.user_no,
|
||||
@@ -47,7 +88,9 @@ def build_user_info_payload(user: SysUser, web_role: str, role_names: list = Non
|
||||
"role": web_role,
|
||||
"roleNames": role_names or [],
|
||||
"regionId": user.dept_id,
|
||||
"regionName": None,
|
||||
"regionName": dept_name,
|
||||
"deptName": dept_name,
|
||||
"postNames": post_names,
|
||||
"avatarUrl": _avatar_url_field(user),
|
||||
}
|
||||
|
||||
@@ -98,5 +141,5 @@ async def issue_tokens_for_user(db: Session, user: SysUser) -> dict:
|
||||
"token": access_token,
|
||||
"refreshToken": refresh_token,
|
||||
"expiresIn": settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
|
||||
"userInfo": build_user_info_payload(user, web_role, role_names),
|
||||
"userInfo": build_user_info_payload(user, web_role, role_names, db=db),
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
"""加班套件:工作日/休息日窗口重叠小时(与前端 oa-overtime-hours.ts 对齐)"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
|
||||
Interval = Tuple[float, float]
|
||||
|
||||
_DT_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})$")
|
||||
_HM_RE = re.compile(r"^(\d{1,2}):(\d{2})$")
|
||||
|
||||
DEFAULT_OVERTIME_WINDOWS = {
|
||||
"workdayOvertimeStart": "17:30",
|
||||
"workdayOvertimeEnd": "08:30",
|
||||
"restBreakStart": "11:30",
|
||||
"restBreakEnd": "13:30",
|
||||
}
|
||||
|
||||
MANUAL_PREFIX = "__manual_"
|
||||
|
||||
|
||||
def _parse_hm(hm: Any) -> Optional[int]:
|
||||
m = _HM_RE.match(str(hm or "").strip())
|
||||
if not m:
|
||||
return None
|
||||
h, mi = int(m.group(1)), int(m.group(2))
|
||||
if h < 0 or h > 23 or mi < 0 or mi > 59:
|
||||
return None
|
||||
return h * 60 + mi
|
||||
|
||||
|
||||
def _parse_dt(s: Any) -> Optional[datetime]:
|
||||
m = _DT_RE.match(str(s or "").strip())
|
||||
if not m:
|
||||
return None
|
||||
try:
|
||||
return datetime(
|
||||
int(m.group(1)),
|
||||
int(m.group(2)),
|
||||
int(m.group(3)),
|
||||
int(m.group(4)),
|
||||
int(m.group(5)),
|
||||
)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _format_ymd(d: datetime) -> str:
|
||||
return d.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _day_start_ms(d: datetime) -> float:
|
||||
day0 = datetime(d.year, d.month, d.day)
|
||||
return day0.timestamp() * 1000
|
||||
|
||||
|
||||
def _day_at_minutes(d: datetime, minutes: int) -> float:
|
||||
return _day_start_ms(d) + minutes * 60000
|
||||
|
||||
|
||||
def _merge_intervals(intervals: List[Interval]) -> List[Interval]:
|
||||
if not intervals:
|
||||
return []
|
||||
sorted_iv = sorted(intervals, key=lambda x: x[0])
|
||||
merged: List[Interval] = [(sorted_iv[0][0], sorted_iv[0][1])]
|
||||
for s, e in sorted_iv[1:]:
|
||||
last = merged[-1]
|
||||
if s <= last[1]:
|
||||
merged[-1] = (last[0], max(last[1], e))
|
||||
else:
|
||||
merged.append((s, e))
|
||||
return merged
|
||||
|
||||
|
||||
def _intersect_interval(a: Interval, b: Interval) -> Optional[Interval]:
|
||||
lo = max(a[0], b[0])
|
||||
hi = min(a[1], b[1])
|
||||
return (lo, hi) if hi > lo else None
|
||||
|
||||
|
||||
def _subtract_interval(base: Interval, sub: Interval) -> List[Interval]:
|
||||
bs, be = base
|
||||
ss, se = sub
|
||||
if se <= bs or ss >= be:
|
||||
return [base]
|
||||
out: List[Interval] = []
|
||||
if ss > bs:
|
||||
out.append((bs, ss))
|
||||
if se < be:
|
||||
out.append((se, be))
|
||||
return out
|
||||
|
||||
|
||||
def _subtract_intervals(base: Interval, subs: List[Interval]) -> List[Interval]:
|
||||
result: List[Interval] = [base]
|
||||
for sub in subs:
|
||||
nxt: List[Interval] = []
|
||||
for r in result:
|
||||
nxt.extend(_subtract_interval(r, sub))
|
||||
result = nxt
|
||||
return result
|
||||
|
||||
|
||||
def _interval_minutes(intervals: List[Interval]) -> float:
|
||||
return sum((b - a) / 60000 for a, b in intervals)
|
||||
|
||||
|
||||
def _build_workday_windows(anchor_day: datetime, windows: Dict[str, str]) -> Optional[Interval]:
|
||||
start_min = _parse_hm(windows.get("workdayOvertimeStart"))
|
||||
end_min = _parse_hm(windows.get("workdayOvertimeEnd"))
|
||||
if start_min is None or end_min is None:
|
||||
return None
|
||||
anchor_start = _day_at_minutes(anchor_day, start_min)
|
||||
next_day = anchor_day + timedelta(days=1)
|
||||
anchor_end = _day_at_minutes(next_day, end_min)
|
||||
if anchor_end <= anchor_start:
|
||||
return None
|
||||
return (anchor_start, anchor_end)
|
||||
|
||||
|
||||
def _build_rest_day_segments(day: datetime, windows: Dict[str, str]) -> List[Interval]:
|
||||
break_start = _parse_hm(windows.get("restBreakStart"))
|
||||
break_end = _parse_hm(windows.get("restBreakEnd"))
|
||||
if break_start is None or break_end is None:
|
||||
return []
|
||||
|
||||
day0 = _day_start_ms(day)
|
||||
next_day = day + timedelta(days=1)
|
||||
day_end = _day_start_ms(next_day)
|
||||
|
||||
segments: List[Interval] = []
|
||||
if break_start > 0:
|
||||
segments.append((day0, _day_at_minutes(day, break_start)))
|
||||
if break_end < 24 * 60:
|
||||
segments.append((_day_at_minutes(day, break_end), day_end))
|
||||
return [(a, b) for a, b in segments if b > a]
|
||||
|
||||
|
||||
def calc_overtime_hours(
|
||||
start_str: Any,
|
||||
end_str: Any,
|
||||
windows: Optional[Dict[str, str]] = None,
|
||||
is_rest_day_fn: Optional[Callable[[str], bool]] = None,
|
||||
) -> Optional[float]:
|
||||
"""返回 1 位小数小时;非法或 end<=start 返回 None。"""
|
||||
if is_rest_day_fn is None:
|
||||
raise TypeError("is_rest_day_fn is required")
|
||||
|
||||
win = dict(DEFAULT_OVERTIME_WINDOWS)
|
||||
if isinstance(windows, dict):
|
||||
win.update({k: str(windows.get(k) or win[k]) for k in DEFAULT_OVERTIME_WINDOWS})
|
||||
|
||||
start = _parse_dt(start_str)
|
||||
end = _parse_dt(end_str)
|
||||
if not start or not end or end <= start:
|
||||
return None
|
||||
|
||||
query: Interval = (start.timestamp() * 1000, end.timestamp() * 1000)
|
||||
start_day = datetime(start.year, start.month, start.day)
|
||||
end_day = datetime(end.year, end.month, end.day)
|
||||
|
||||
workday_intervals: List[Interval] = []
|
||||
anchor = start_day - timedelta(days=1)
|
||||
last_anchor = end_day
|
||||
while anchor <= last_anchor:
|
||||
ymd = _format_ymd(anchor)
|
||||
if not is_rest_day_fn(ymd):
|
||||
win_iv = _build_workday_windows(anchor, win)
|
||||
if win_iv:
|
||||
hit = _intersect_interval(win_iv, query)
|
||||
if hit:
|
||||
workday_intervals.append(hit)
|
||||
anchor += timedelta(days=1)
|
||||
|
||||
workday_merged = _merge_intervals(workday_intervals)
|
||||
|
||||
rest_intervals: List[Interval] = []
|
||||
day = start_day
|
||||
while day <= end_day:
|
||||
ymd = _format_ymd(day)
|
||||
if is_rest_day_fn(ymd):
|
||||
for seg in _build_rest_day_segments(day, win):
|
||||
hit = _intersect_interval(seg, query)
|
||||
if hit:
|
||||
rest_intervals.extend(_subtract_intervals(hit, workday_merged))
|
||||
day += timedelta(days=1)
|
||||
|
||||
total_minutes = _interval_minutes(workday_merged) + _interval_minutes(rest_intervals)
|
||||
return round(total_minutes / 60.0, 1)
|
||||
|
||||
|
||||
def _extract_rules(form_schema: Any) -> List[Dict[str, Any]]:
|
||||
if isinstance(form_schema, list):
|
||||
return [r for r in form_schema if isinstance(r, dict)]
|
||||
if isinstance(form_schema, dict):
|
||||
rules = form_schema.get("rule") or form_schema.get("rules") or form_schema.get("fields")
|
||||
if isinstance(rules, list):
|
||||
return [r for r in rules if isinstance(r, dict)]
|
||||
if form_schema.get("type") or form_schema.get("field"):
|
||||
return [form_schema]
|
||||
return []
|
||||
|
||||
|
||||
def _walk(rules: List[Dict[str, Any]], out: List[Dict[str, Any]]) -> None:
|
||||
for r in rules:
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
out.append(r)
|
||||
children = r.get("children")
|
||||
if isinstance(children, list):
|
||||
_walk([c for c in children if isinstance(c, dict)], out)
|
||||
props = r.get("props") if isinstance(r.get("props"), dict) else {}
|
||||
nested = props.get("rule")
|
||||
if isinstance(nested, list):
|
||||
_walk([c for c in nested if isinstance(c, dict)], out)
|
||||
|
||||
|
||||
def _kit_child_fields(kit: Dict[str, Any]) -> Tuple[Optional[str], Optional[str], Optional[str]]:
|
||||
"""返回 (start_field, end_field, duration_field)。"""
|
||||
props = kit.get("props") if isinstance(kit.get("props"), dict) else {}
|
||||
start_f = props.get("startField")
|
||||
end_f = props.get("endField")
|
||||
dur_f = props.get("durationField")
|
||||
if start_f and end_f and dur_f:
|
||||
return str(start_f), str(end_f), str(dur_f)
|
||||
|
||||
children = kit.get("children")
|
||||
if not isinstance(children, list):
|
||||
children = []
|
||||
p_rule = props.get("rule")
|
||||
if isinstance(p_rule, list):
|
||||
children = p_rule
|
||||
|
||||
start_field: Optional[str] = None
|
||||
end_field: Optional[str] = None
|
||||
duration_field: Optional[str] = None
|
||||
date_fields: List[str] = []
|
||||
|
||||
for c in children:
|
||||
if not isinstance(c, dict):
|
||||
continue
|
||||
field = c.get("field")
|
||||
if not field:
|
||||
continue
|
||||
c_props = c.get("props") if isinstance(c.get("props"), dict) else {}
|
||||
kit_field = c_props.get("_fc_kit_field")
|
||||
if kit_field == "overtimeStart":
|
||||
start_field = str(field)
|
||||
continue
|
||||
if kit_field == "overtimeEnd":
|
||||
end_field = str(field)
|
||||
continue
|
||||
if kit_field == "overtimeDuration":
|
||||
duration_field = str(field)
|
||||
continue
|
||||
t = str(c.get("type") or "")
|
||||
if t in ("datePicker", "date", "timePicker", "time"):
|
||||
date_fields.append(str(field))
|
||||
elif t in ("inputNumber", "number") and duration_field is None:
|
||||
duration_field = str(field)
|
||||
elif t in ("inputNumber", "number") and "时长" in str(c.get("title") or ""):
|
||||
duration_field = str(field)
|
||||
|
||||
if start_field is None and len(date_fields) >= 1:
|
||||
start_field = date_fields[0]
|
||||
if end_field is None and len(date_fields) >= 2:
|
||||
end_field = date_fields[1]
|
||||
return start_field, end_field, duration_field
|
||||
|
||||
|
||||
def _round1(v: Any) -> Optional[float]:
|
||||
try:
|
||||
n = float(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if n < 0:
|
||||
return None
|
||||
return round(n, 1)
|
||||
|
||||
|
||||
def apply_overtime_kit_hours(
|
||||
form_schema: Any,
|
||||
form_data: Dict[str, Any],
|
||||
is_rest_day_fn: Callable[[str], bool],
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
遍历 overtimeKit:未手改则覆盖时长;已手改(form_data[__manual_<durationField>])则仅规范化一位小数。
|
||||
"""
|
||||
data = dict(form_data or {})
|
||||
flat: List[Dict[str, Any]] = []
|
||||
_walk(_extract_rules(form_schema), flat)
|
||||
for rule in flat:
|
||||
if str(rule.get("type") or "") != "overtimeKit":
|
||||
continue
|
||||
start_f, end_f, dur_f = _kit_child_fields(rule)
|
||||
if not start_f or not end_f or not dur_f:
|
||||
continue
|
||||
props = rule.get("props") if isinstance(rule.get("props"), dict) else {}
|
||||
win = {
|
||||
"workdayOvertimeStart": str(
|
||||
props.get("workdayOvertimeStart") or DEFAULT_OVERTIME_WINDOWS["workdayOvertimeStart"]
|
||||
),
|
||||
"workdayOvertimeEnd": str(
|
||||
props.get("workdayOvertimeEnd") or DEFAULT_OVERTIME_WINDOWS["workdayOvertimeEnd"]
|
||||
),
|
||||
"restBreakStart": str(
|
||||
props.get("restBreakStart") or DEFAULT_OVERTIME_WINDOWS["restBreakStart"]
|
||||
),
|
||||
"restBreakEnd": str(
|
||||
props.get("restBreakEnd") or DEFAULT_OVERTIME_WINDOWS["restBreakEnd"]
|
||||
),
|
||||
}
|
||||
manual_key = MANUAL_PREFIX + dur_f
|
||||
is_manual = bool(data.get(manual_key))
|
||||
if is_manual:
|
||||
rounded = _round1(data.get(dur_f))
|
||||
if rounded is not None:
|
||||
data[dur_f] = rounded
|
||||
continue
|
||||
hours = calc_overtime_hours(data.get(start_f), data.get(end_f), win, is_rest_day_fn)
|
||||
if hours is not None:
|
||||
data[dur_f] = hours
|
||||
return data
|
||||
|
||||
|
||||
def validate_overtime_kit_form_values(form_schema: Any, form_data: Dict[str, Any]) -> List[str]:
|
||||
"""提交校验:结束>开始;手改时长合法。"""
|
||||
errors: List[str] = []
|
||||
data = form_data or {}
|
||||
flat: List[Dict[str, Any]] = []
|
||||
_walk(_extract_rules(form_schema), flat)
|
||||
for rule in flat:
|
||||
if str(rule.get("type") or "") != "overtimeKit":
|
||||
continue
|
||||
start_f, end_f, dur_f = _kit_child_fields(rule)
|
||||
if not start_f or not end_f or not dur_f:
|
||||
continue
|
||||
start = _parse_dt(data.get(start_f))
|
||||
end = _parse_dt(data.get(end_f))
|
||||
if data.get(start_f) and data.get(end_f):
|
||||
if not start or not end:
|
||||
errors.append("加班起止时间格式须为 YYYY-MM-DD HH:mm")
|
||||
elif end <= start:
|
||||
errors.append("加班结束时间须晚于开始时间")
|
||||
if MANUAL_PREFIX + dur_f in data or data.get(MANUAL_PREFIX + dur_f):
|
||||
if data.get(dur_f) is not None and data.get(dur_f) != "":
|
||||
if _round1(data.get(dur_f)) is None:
|
||||
errors.append("加班时长须为非负数字(1 位小数)")
|
||||
return errors
|
||||
@@ -3,15 +3,39 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
from app.models.models import OaApp, OaAppVersion, OaInstance
|
||||
from app.services.oa_engine import OaEngineError, _loads
|
||||
from app.models.models import OaApp, OaAppVersion, OaInstance, OaTask
|
||||
from app.services.oa_engine import OaEngineError, _dept_name, _loads, _user_name_map
|
||||
|
||||
LAYOUT_SKIP = frozenset(
|
||||
{"fcRow", "fcTable", "col", "row", "elCard", "space", "divider", "html", "title", "text", "tag"}
|
||||
{
|
||||
"fcRow",
|
||||
"fcTable",
|
||||
"col",
|
||||
"row",
|
||||
"elCard",
|
||||
"space",
|
||||
"divider",
|
||||
"html",
|
||||
"title",
|
||||
"text",
|
||||
"tag",
|
||||
"card",
|
||||
"group",
|
||||
"object",
|
||||
"leaveKit",
|
||||
"confirmationKit",
|
||||
"overtimeKit",
|
||||
"resignationKit",
|
||||
"tripKit",
|
||||
}
|
||||
)
|
||||
UPLOAD_TYPES = frozenset({"upload", "fcUpload", "image", "oaAttachment"})
|
||||
LONG_TYPES = frozenset({"textarea", "input"})
|
||||
|
||||
_ACCOUNT_TYPE_LABEL = {
|
||||
"alipay": "支付宝",
|
||||
"personal": "个人银行卡",
|
||||
"corporate": "对公银行账户",
|
||||
}
|
||||
|
||||
def _walk_rules(rules: Any, out: List[dict]) -> None:
|
||||
if not isinstance(rules, list):
|
||||
@@ -69,6 +93,57 @@ def _extract_upload_urls(raw: Any) -> List[str]:
|
||||
return urls
|
||||
|
||||
|
||||
def _upload_display_name(raw_item: Any, fallback_url: str = "") -> str:
|
||||
"""打印/摘要:优先对象 name,否则取路径最后一段文件名。"""
|
||||
if isinstance(raw_item, dict):
|
||||
named = str(raw_item.get("name") or "").strip()
|
||||
if named:
|
||||
return named
|
||||
u = str(fallback_url or raw_item or "").strip()
|
||||
if not u:
|
||||
return ""
|
||||
path = u.split("?", 1)[0]
|
||||
base = path.rsplit("/", 1)[-1]
|
||||
if not base:
|
||||
return u
|
||||
try:
|
||||
from urllib.parse import unquote
|
||||
|
||||
return unquote(base) or base
|
||||
except Exception:
|
||||
return base
|
||||
|
||||
|
||||
def _format_upload_display(raw: Any) -> str:
|
||||
if raw is None or raw == "" or raw == []:
|
||||
return "0 个"
|
||||
if isinstance(raw, list):
|
||||
items: List[Any] = raw
|
||||
elif isinstance(raw, str):
|
||||
items = [x.strip() for x in raw.split(",") if x.strip()]
|
||||
elif isinstance(raw, dict):
|
||||
items = [raw]
|
||||
else:
|
||||
items = [raw]
|
||||
names: List[str] = []
|
||||
for it in items:
|
||||
if it is None or it == "":
|
||||
continue
|
||||
if isinstance(it, dict):
|
||||
named = str(it.get("name") or "").strip()
|
||||
if named:
|
||||
names.append(named)
|
||||
continue
|
||||
urls = _extract_upload_urls(it)
|
||||
if urls:
|
||||
names.append(_upload_display_name(it, urls[0]))
|
||||
continue
|
||||
s = str(it).strip()
|
||||
if s:
|
||||
names.append(_upload_display_name(s, s))
|
||||
return "、".join(names) if names else "0 个"
|
||||
|
||||
|
||||
def _normalize_related_ids(raw: Any) -> List[str]:
|
||||
"""Order-preserving dedupe of related approval instance ids."""
|
||||
if isinstance(raw, list):
|
||||
@@ -88,14 +163,167 @@ def _normalize_related_ids(raw: Any) -> List[str]:
|
||||
return out
|
||||
|
||||
|
||||
def _format_trip_leg(leg: Dict[str, Any], index: int) -> str:
|
||||
transport = str(leg.get("transport") or "").strip() or "-"
|
||||
trip_type = str(leg.get("tripType") or "").strip()
|
||||
from_city = str(leg.get("fromCity") or "").strip() or "-"
|
||||
to_city = str(leg.get("toCity") or "").strip() or "-"
|
||||
start_date = str(leg.get("startDate") or "").strip()
|
||||
start_half = str(leg.get("startHalf") or "").strip()
|
||||
end_date = str(leg.get("endDate") or "").strip()
|
||||
end_half = str(leg.get("endHalf") or "").strip()
|
||||
duration = leg.get("duration")
|
||||
if duration is None or duration == "":
|
||||
duration_text = "-"
|
||||
else:
|
||||
try:
|
||||
duration_text = f"{float(duration):g}天"
|
||||
except (TypeError, ValueError):
|
||||
duration_text = f"{duration}天"
|
||||
route = f"{from_city} → {to_city}"
|
||||
if start_date and end_date:
|
||||
period = (
|
||||
f"{start_date}{(' ' + start_half) if start_half else ''}"
|
||||
f" ~ {end_date}{(' ' + end_half) if end_half else ''}"
|
||||
)
|
||||
else:
|
||||
period = "-"
|
||||
type_part = f" · {trip_type}" if trip_type else ""
|
||||
return f"行程{index + 1}:{transport}{type_part} · {route} · {period} · {duration_text}"
|
||||
|
||||
|
||||
def _format_trip_itinerary(raw: Any) -> str:
|
||||
if isinstance(raw, dict):
|
||||
legs = [raw]
|
||||
elif isinstance(raw, list):
|
||||
legs = [x for x in raw if isinstance(x, dict)]
|
||||
else:
|
||||
return ""
|
||||
if not legs:
|
||||
return ""
|
||||
return ";".join(_format_trip_leg(leg, i) for i, leg in enumerate(legs))
|
||||
|
||||
|
||||
def _format_receive_account(raw: Any) -> str:
|
||||
if isinstance(raw, dict):
|
||||
items = [raw]
|
||||
elif isinstance(raw, list):
|
||||
items = [x for x in raw if isinstance(x, dict)]
|
||||
else:
|
||||
return ""
|
||||
lines: List[str] = []
|
||||
for it in items:
|
||||
at = str(it.get("accountType") or "").strip()
|
||||
type_label = _ACCOUNT_TYPE_LABEL.get(at, at)
|
||||
parts = [
|
||||
type_label,
|
||||
str(it.get("accountName") or "").strip(),
|
||||
str(it.get("accountNo") or "").strip(),
|
||||
]
|
||||
if at in ("personal", "corporate"):
|
||||
bank = str(it.get("bankName") or "").strip()
|
||||
if bank:
|
||||
parts.append(bank)
|
||||
prov = str(it.get("bankProvince") or "").strip()
|
||||
city = str(it.get("bankCity") or "").strip()
|
||||
if prov and city:
|
||||
parts.append(f"{prov} / {city}")
|
||||
elif prov or city:
|
||||
parts.append(prov or city)
|
||||
branch = str(it.get("bankBranch") or "").strip()
|
||||
if branch:
|
||||
parts.append(branch)
|
||||
remark = str(it.get("remark") or "").strip()
|
||||
if remark:
|
||||
parts.append(remark)
|
||||
line = " · ".join(p for p in parts if p)
|
||||
if line:
|
||||
lines.append(line)
|
||||
return ";".join(lines)
|
||||
|
||||
|
||||
def _format_region_like(raw: Any) -> str:
|
||||
"""省市区 / 级联:string[] 或 {province,city,district} 等。"""
|
||||
if raw is None or raw == "":
|
||||
return ""
|
||||
if isinstance(raw, str):
|
||||
return raw.strip()
|
||||
if isinstance(raw, list):
|
||||
parts: List[str] = []
|
||||
for x in raw:
|
||||
if x is None or x == "":
|
||||
continue
|
||||
if isinstance(x, dict):
|
||||
n = str(
|
||||
x.get("label") or x.get("name") or x.get("text") or x.get("value") or ""
|
||||
).strip()
|
||||
if n:
|
||||
parts.append(n)
|
||||
continue
|
||||
parts.append(str(x).strip())
|
||||
return " / ".join(p for p in parts if p)
|
||||
if isinstance(raw, dict):
|
||||
path = [
|
||||
str(
|
||||
raw.get("province")
|
||||
or raw.get("provinceName")
|
||||
or raw.get("province_name")
|
||||
or ""
|
||||
).strip(),
|
||||
str(raw.get("city") or raw.get("cityName") or raw.get("city_name") or "").strip(),
|
||||
str(
|
||||
raw.get("district")
|
||||
or raw.get("districtName")
|
||||
or raw.get("area")
|
||||
or raw.get("areaName")
|
||||
or raw.get("district_name")
|
||||
or ""
|
||||
).strip(),
|
||||
]
|
||||
path = [p for p in path if p]
|
||||
if path:
|
||||
return " / ".join(path)
|
||||
return _format_unknown_object(raw)
|
||||
return str(raw).strip()
|
||||
|
||||
|
||||
def _format_unknown_object(raw: Dict[str, Any]) -> str:
|
||||
"""Never dump full dict/JSON; prefer common display keys then scalar values."""
|
||||
named = str(
|
||||
raw.get("label") or raw.get("name") or raw.get("text") or raw.get("value") or ""
|
||||
).strip()
|
||||
if named:
|
||||
return named
|
||||
if raw.get("accountType") or raw.get("accountNo") or raw.get("accountName"):
|
||||
return _format_receive_account(raw)
|
||||
if raw.get("fromCity") or raw.get("toCity") or raw.get("transport"):
|
||||
return _format_trip_leg(raw, 0)
|
||||
skip_keys = {
|
||||
"id",
|
||||
"uuid",
|
||||
"key",
|
||||
"durationManual",
|
||||
"manual",
|
||||
"__manual",
|
||||
}
|
||||
parts: List[str] = []
|
||||
for k, v in raw.items():
|
||||
ks = str(k)
|
||||
if ks in skip_keys or ks.startswith("__") or ks.lower().endswith("id"):
|
||||
continue
|
||||
if isinstance(v, bool) or v is None or v == "":
|
||||
continue
|
||||
if isinstance(v, (str, int, float)) and not isinstance(v, bool):
|
||||
parts.append(str(v).strip())
|
||||
return "、".join(p for p in parts if p)
|
||||
|
||||
|
||||
def _format_value(typ: str, raw: Any) -> Tuple[str, bool]:
|
||||
"""returns (text, fullWidth)"""
|
||||
if typ in UPLOAD_TYPES:
|
||||
urls = _extract_upload_urls(raw)
|
||||
if not urls:
|
||||
return "0 个", False
|
||||
# 展示附件地址(多条用中文顿号);地址较长默认占满一行
|
||||
return "、".join(urls), True
|
||||
text = _format_upload_display(raw)
|
||||
# 展示附件文件名(多条用中文顿号);较长时占满一行
|
||||
return text, True
|
||||
if typ == "relatedApproval":
|
||||
if isinstance(raw, list):
|
||||
n = len([x for x in raw if str(x).strip()])
|
||||
@@ -127,10 +355,38 @@ def _format_value(typ: str, raw: Any) -> Tuple[str, bool]:
|
||||
return str(raw), False
|
||||
text = f"{v:,.2f}"
|
||||
return text, False
|
||||
if typ == "tripItinerary":
|
||||
text = _format_trip_itinerary(raw)
|
||||
return text, True
|
||||
if typ == "receiveAccount":
|
||||
text = _format_receive_account(raw)
|
||||
return text, True
|
||||
if typ in ("region", "cascader"):
|
||||
return _format_region_like(raw), False
|
||||
if typ in ("dateRange", "timeRange") or (
|
||||
typ in ("datePicker", "date", "timePicker", "time") and isinstance(raw, list)
|
||||
):
|
||||
if isinstance(raw, list) and len(raw) >= 2:
|
||||
a = str(raw[0] or "").strip()
|
||||
b = str(raw[1] or "").strip()
|
||||
if a or b:
|
||||
return f"{a or '-'} ~ {b or '-'}", False
|
||||
if isinstance(raw, list):
|
||||
return "、".join(str(x).strip() for x in raw if x is not None and str(x).strip()), False
|
||||
if isinstance(raw, list):
|
||||
text = "、".join(str(x) for x in raw if x is not None and str(x) != "")
|
||||
parts: List[str] = []
|
||||
for x in raw:
|
||||
if x is None or str(x) == "":
|
||||
continue
|
||||
if isinstance(x, dict):
|
||||
n = _format_unknown_object(x)
|
||||
if n:
|
||||
parts.append(n)
|
||||
continue
|
||||
parts.append(str(x))
|
||||
text = "、".join(parts)
|
||||
elif isinstance(raw, dict):
|
||||
text = str(raw.get("label") or raw.get("value") or raw)
|
||||
text = _format_unknown_object(raw)
|
||||
else:
|
||||
text = "" if raw is None else str(raw)
|
||||
full = typ in LONG_TYPES and len(text) > 40
|
||||
@@ -217,13 +473,109 @@ def merge_relation_targets(
|
||||
return result
|
||||
|
||||
|
||||
def assert_linkable_instance(inst: OaInstance, *, user_id: str, tenant_no: str) -> None:
|
||||
_DONE_TASK_STATUSES = ("approved", "rejected", "returned", "transferred")
|
||||
|
||||
|
||||
def _user_can_link_instance(db, *, inst: OaInstance, user_id: str, tenant_no: str) -> bool:
|
||||
if (inst.initiator_user_id or "") == user_id:
|
||||
return True
|
||||
if db is None:
|
||||
return False
|
||||
done = (
|
||||
db.query(OaTask.id)
|
||||
.filter(
|
||||
OaTask.tenant_no == tenant_no,
|
||||
OaTask.del_flag == 0,
|
||||
OaTask.instance_id == inst.id,
|
||||
OaTask.assignee_user_id == user_id,
|
||||
OaTask.task_type == "approval",
|
||||
OaTask.status.in_(_DONE_TASK_STATUSES),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if done:
|
||||
return True
|
||||
cc = (
|
||||
db.query(OaTask.id)
|
||||
.filter(
|
||||
OaTask.tenant_no == tenant_no,
|
||||
OaTask.del_flag == 0,
|
||||
OaTask.instance_id == inst.id,
|
||||
OaTask.assignee_user_id == user_id,
|
||||
OaTask.task_type == "cc",
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return bool(cc)
|
||||
|
||||
|
||||
def assert_linkable_instance(
|
||||
inst: OaInstance,
|
||||
*,
|
||||
user_id: str,
|
||||
tenant_no: str,
|
||||
db=None,
|
||||
) -> None:
|
||||
if not inst or inst.del_flag != 0 or inst.tenant_no != tenant_no:
|
||||
raise OaEngineError("关联的审批单不存在")
|
||||
if (inst.initiator_user_id or "") != user_id:
|
||||
raise OaEngineError("只能关联本人发起的审批单")
|
||||
if (inst.status or "") != "completed":
|
||||
raise OaEngineError("只能关联已通过的审批单")
|
||||
if not _user_can_link_instance(db, inst=inst, user_id=user_id, tenant_no=tenant_no):
|
||||
raise OaEngineError("无权关联该审批单")
|
||||
|
||||
|
||||
_STATUS_TEXT = {
|
||||
"running": "处理中",
|
||||
"completed": "已通过",
|
||||
"rejected": "已拒绝",
|
||||
"returned": "已打回",
|
||||
"cancelled": "已撤销",
|
||||
}
|
||||
|
||||
|
||||
def related_status_text(status: str) -> str:
|
||||
s = (status or "").strip()
|
||||
return _STATUS_TEXT.get(s, s or "-")
|
||||
|
||||
|
||||
def related_display_title(initiator_name: str, app_name: str, title: str) -> str:
|
||||
name = (initiator_name or "").strip()
|
||||
app = (app_name or "").strip()
|
||||
if name and app:
|
||||
return f"{name}提交的{app}"
|
||||
return app or (title or "").strip() or "审批单"
|
||||
|
||||
|
||||
def _instance_ids_for_tab(db, *, tenant_no: str, user_id: str, tab: str) -> Optional[List[str]]:
|
||||
"""Return instance id list for done/cc tabs; None means mine (filter on initiator)."""
|
||||
if tab == "mine":
|
||||
return None
|
||||
if tab == "done":
|
||||
rows = (
|
||||
db.query(OaTask.instance_id)
|
||||
.filter(
|
||||
OaTask.tenant_no == tenant_no,
|
||||
OaTask.del_flag == 0,
|
||||
OaTask.assignee_user_id == user_id,
|
||||
OaTask.task_type == "approval",
|
||||
OaTask.status.in_(_DONE_TASK_STATUSES),
|
||||
)
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
return [r[0] for r in rows if r[0]]
|
||||
if tab == "cc":
|
||||
rows = (
|
||||
db.query(OaTask.instance_id)
|
||||
.filter(
|
||||
OaTask.tenant_no == tenant_no,
|
||||
OaTask.del_flag == 0,
|
||||
OaTask.assignee_user_id == user_id,
|
||||
OaTask.task_type == "cc",
|
||||
)
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
return [r[0] for r in rows if r[0]]
|
||||
raise OaEngineError(f"不支持的选单类型: {tab}")
|
||||
|
||||
|
||||
def list_related_candidates(
|
||||
@@ -231,20 +583,31 @@ def list_related_candidates(
|
||||
*,
|
||||
tenant_no: str,
|
||||
user_id: str,
|
||||
tab: str = "mine",
|
||||
keyword: str = "",
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> Dict[str, Any]:
|
||||
from sqlalchemy import or_
|
||||
|
||||
tab_n = (tab or "mine").strip() or "mine"
|
||||
if tab_n not in ("mine", "done", "cc"):
|
||||
raise OaEngineError(f"不支持的选单类型: {tab_n}")
|
||||
|
||||
q = db.query(OaInstance).filter(
|
||||
OaInstance.tenant_no == tenant_no,
|
||||
OaInstance.del_flag == 0,
|
||||
OaInstance.initiator_user_id == user_id,
|
||||
OaInstance.status == "completed",
|
||||
)
|
||||
tab_ids = _instance_ids_for_tab(db, tenant_no=tenant_no, user_id=user_id, tab=tab_n)
|
||||
if tab_ids is None:
|
||||
q = q.filter(OaInstance.initiator_user_id == user_id)
|
||||
else:
|
||||
if not tab_ids:
|
||||
return {"list": [], "total": 0, "page": max(1, int(page or 1)), "pageSize": min(100, max(1, int(page_size or 20)))}
|
||||
q = q.filter(OaInstance.id.in_(tab_ids))
|
||||
|
||||
kw = (keyword or "").strip()
|
||||
if kw:
|
||||
from sqlalchemy import or_
|
||||
|
||||
app_ids = [
|
||||
row[0]
|
||||
for row in db.query(OaApp.id)
|
||||
@@ -259,6 +622,7 @@ def list_related_candidates(
|
||||
if app_ids:
|
||||
clauses.append(OaInstance.app_id.in_(app_ids))
|
||||
q = q.filter(or_(*clauses))
|
||||
|
||||
total = q.count()
|
||||
page = max(1, int(page or 1))
|
||||
page_size = min(100, max(1, int(page_size or 20)))
|
||||
@@ -268,20 +632,80 @@ def list_related_candidates(
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
app_map = {}
|
||||
ids = list({r.app_id for r in rows if r.app_id})
|
||||
if ids:
|
||||
for a in db.query(OaApp).filter(OaApp.id.in_(ids)).all():
|
||||
|
||||
app_map: Dict[str, str] = {}
|
||||
app_ids_page = list({r.app_id for r in rows if r.app_id})
|
||||
if app_ids_page:
|
||||
for a in db.query(OaApp).filter(OaApp.id.in_(app_ids_page)).all():
|
||||
app_map[a.id] = a.app_name or ""
|
||||
items = []
|
||||
|
||||
initiator_ids = [r.initiator_user_id for r in rows if r.initiator_user_id]
|
||||
inst_ids = [r.id for r in rows]
|
||||
pending_tasks = (
|
||||
db.query(OaTask)
|
||||
.filter(
|
||||
OaTask.tenant_no == tenant_no,
|
||||
OaTask.del_flag == 0,
|
||||
OaTask.instance_id.in_(inst_ids),
|
||||
OaTask.task_type == "approval",
|
||||
OaTask.status == "pending",
|
||||
)
|
||||
.all()
|
||||
if inst_ids
|
||||
else []
|
||||
)
|
||||
pending_by_inst: Dict[str, List[OaTask]] = {}
|
||||
for t in pending_tasks:
|
||||
pending_by_inst.setdefault(t.instance_id, []).append(t)
|
||||
if t.assignee_user_id:
|
||||
initiator_ids.append(t.assignee_user_id)
|
||||
name_map = _user_name_map(db, initiator_ids)
|
||||
|
||||
ver_ids = list({r.app_version_id for r in rows if r.app_version_id})
|
||||
ver_by_id: Dict[str, OaAppVersion] = {}
|
||||
if ver_ids:
|
||||
for v in (
|
||||
db.query(OaAppVersion)
|
||||
.filter(OaAppVersion.id.in_(ver_ids), OaAppVersion.del_flag == 0)
|
||||
.all()
|
||||
):
|
||||
ver_by_id[v.id] = v
|
||||
|
||||
items: List[Dict[str, Any]] = []
|
||||
for r in rows:
|
||||
app_name = app_map.get(r.app_id, "")
|
||||
initiator_name = name_map.get(r.initiator_user_id or "", "") or ""
|
||||
status = r.status or ""
|
||||
approver_names = ""
|
||||
if status == "running":
|
||||
names: List[str] = []
|
||||
for t in pending_by_inst.get(r.id, []):
|
||||
uid = (t.assignee_user_id or "").strip()
|
||||
if uid:
|
||||
names.append(name_map.get(uid, uid))
|
||||
approver_names = "、".join(names)
|
||||
ver = ver_by_id.get(r.app_version_id or "")
|
||||
schema = _loads(ver.form_schema_json, {}) if ver else {}
|
||||
form_data = _loads(r.form_data_json, {}) if r.form_data_json else {}
|
||||
preview = [
|
||||
{"label": f.get("label") or "", "value": f.get("value") or ""}
|
||||
for f in flatten_form_fields_for_summary(schema, form_data)[:2]
|
||||
]
|
||||
items.append(
|
||||
{
|
||||
"id": r.id,
|
||||
"appName": app_map.get(r.app_id, ""),
|
||||
"appName": app_name,
|
||||
"title": r.title or "",
|
||||
"displayTitle": related_display_title(initiator_name, app_name, r.title or ""),
|
||||
"initiatorUserName": initiator_name,
|
||||
"initiatorDeptName": _dept_name(
|
||||
db, getattr(r, "initiator_dept_id", None), tenant_no=tenant_no
|
||||
),
|
||||
"applyTime": r.create_time.strftime("%Y-%m-%d %H:%M:%S") if r.create_time else "",
|
||||
"status": r.status or "",
|
||||
"status": status,
|
||||
"statusText": related_status_text(status),
|
||||
"currentApproverNames": approver_names,
|
||||
"previewFields": preview,
|
||||
}
|
||||
)
|
||||
return {"list": items, "total": total, "page": page, "pageSize": page_size}
|
||||
@@ -326,7 +750,7 @@ def build_related_summaries(
|
||||
continue
|
||||
if mode == "picker":
|
||||
try:
|
||||
assert_linkable_instance(inst, user_id=user_id, tenant_no=tenant_no)
|
||||
assert_linkable_instance(inst, user_id=user_id, tenant_no=tenant_no, db=db)
|
||||
except OaEngineError:
|
||||
out.append(
|
||||
{
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""微信小程序登录业务:openid + 手机号一致性校验。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.crud.user import user_crud
|
||||
from app.models.models import SysUser
|
||||
from app.services.wechat_mini_auth import normalize_cn_mobile, phones_match
|
||||
|
||||
|
||||
def resolve_wechat_login_user(
|
||||
db: Session, *, openid: str, phone: str
|
||||
) -> Tuple[Optional[SysUser], Optional[str], Optional[int]]:
|
||||
"""
|
||||
根据 openid + 本次授权手机号解析可登录员工。
|
||||
|
||||
Returns:
|
||||
(user, error_message, error_code)
|
||||
成功时 error_message/error_code 为 None;失败时 user 为 None。
|
||||
"""
|
||||
oid = (openid or "").strip()
|
||||
if not oid:
|
||||
return None, "微信未返回 openid", 400
|
||||
if not normalize_cn_mobile(phone):
|
||||
return None, "请授权手机号登录,或使用账号密码登录", 400
|
||||
|
||||
bound = user_crud.get_by_wx_openid(db, oid)
|
||||
if bound:
|
||||
if not phones_match(getattr(bound, "phone_no", None), phone):
|
||||
return (
|
||||
None,
|
||||
"授权手机号与绑定账号不一致,请使用账号密码登录或联系管理员",
|
||||
401,
|
||||
)
|
||||
return bound, None, None
|
||||
|
||||
users = user_crud.list_active_by_phone_no(db, phone)
|
||||
if not users:
|
||||
return None, "未找到与该手机号匹配的员工账号,请使用账号密码登录", 401
|
||||
if len(users) > 1:
|
||||
return None, "手机号对应多个账号,请使用账号密码登录", 400
|
||||
|
||||
user = users[0]
|
||||
other = user_crud.get_by_wx_openid(db, oid)
|
||||
if other and other.id != user.id:
|
||||
return None, "该微信已绑定其他账号", 409
|
||||
existing_oid = (getattr(user, "wx_openid", None) or "").strip()
|
||||
if existing_oid and existing_oid != oid:
|
||||
return None, "该账号已绑定其他微信,请联系管理员", 409
|
||||
|
||||
user.wx_openid = oid
|
||||
user.update_time = datetime.now()
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return user, None, None
|
||||
@@ -33,6 +33,13 @@ def normalize_cn_mobile(raw: Optional[str]) -> str:
|
||||
return s
|
||||
|
||||
|
||||
def phones_match(account_phone: Optional[str], authorized_phone: Optional[str]) -> bool:
|
||||
"""账号手机号与本次微信授权手机号是否一致(规范化后比较)。"""
|
||||
a = normalize_cn_mobile(account_phone)
|
||||
b = normalize_cn_mobile(authorized_phone)
|
||||
return bool(a) and bool(b) and a == b
|
||||
|
||||
|
||||
def _require_mini_credentials() -> tuple:
|
||||
appid = (settings.WXPAY_MINI_APPID or "").strip()
|
||||
secret = (settings.WXPAY_SECRET or "").strip()
|
||||
|
||||
Reference in new issue
Block a user