admin.py
10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
"""管理员路由:用户管理、密码重置、岗位模板维护。
全部接口要求 role=admin。
"""
import logging
from datetime import datetime
from fastapi import APIRouter, Body, Depends, HTTPException, Query, status
from sqlalchemy import func, or_, select
from config import DEFAULT_USER_PASSWORD
from src.database.models import WikiPosition, WikiUser, WikiUserProfile
from src.database.session import AsyncSessionLocal
from src.services.identity.local import build_password_fields
from src.services.identity.tokens import require_admin
logger = logging.getLogger(__name__)
router = APIRouter()
def _position_payload(position: WikiPosition) -> dict:
return {
"id": position.id,
"name": position.name,
"deptL1": position.dept_l1,
"deptL2": position.dept_l2,
"dutyTemplate": position.duty_template,
"commonOpsTemplate": position.common_ops_template,
"templateMissing": bool(position.template_missing),
}
# ==================================== 用户管理 ====================================
@router.get("/admin/users")
async def list_users(
keyword: str = Query(default="", description="按姓名/账号/手机号模糊搜索"),
limit: int = Query(default=50, ge=1, le=200),
offset: int = Query(default=0, ge=0),
_: WikiUser = Depends(require_admin),
):
"""用户列表,支持关键字搜索与分页。"""
async with AsyncSessionLocal() as session:
stmt = select(WikiUser)
count_stmt = select(func.count()).select_from(WikiUser)
keyword = (keyword or "").strip()
if keyword:
pattern = f"%{keyword}%"
condition = or_(
WikiUser.display_name.like(pattern),
WikiUser.username.like(pattern),
WikiUser.phone.like(pattern),
)
stmt = stmt.where(condition)
count_stmt = count_stmt.where(condition)
total = (await session.execute(count_stmt)).scalar() or 0
stmt = stmt.order_by(WikiUser.created_at.desc()).limit(limit).offset(offset)
users = (await session.execute(stmt)).scalars().all()
# 一次性把岗位名查出来,避免逐行查询
position_ids = {u.position_id for u in users if u.position_id}
positions: dict[str, str] = {}
if position_ids:
rows = await session.execute(
select(WikiPosition.id, WikiPosition.name).where(WikiPosition.id.in_(position_ids))
)
positions = {pid: name for pid, name in rows}
items = [
{
"id": u.id,
"username": u.username,
"displayName": u.display_name,
"phone": u.phone,
"email": u.email,
"role": u.role,
"status": u.status,
"storeName": u.store_name,
"positionId": u.position_id,
"positionName": positions.get(u.position_id),
"lastLoginAt": u.last_login_at.isoformat() if u.last_login_at else None,
}
for u in users
]
return {"success": True, "total": total, "items": items}
@router.post("/admin/users")
async def create_user(
data: dict = Body(...),
_: WikiUser = Depends(require_admin),
):
"""新建用户。账号统一使用手机号,初始密码取 DEFAULT_USER_PASSWORD。"""
phone = (data.get("phone") or "").strip()
display_name = (data.get("displayName") or "").strip()
position_id = (data.get("positionId") or "").strip() or None
store_name = (data.get("storeName") or "").strip() or None
role = (data.get("role") or "user").strip()
if not phone:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="手机号不能为空")
if not display_name:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="姓名不能为空")
if role not in ("user", "admin"):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="角色只能是 user 或 admin")
async with AsyncSessionLocal() as session:
exists = await session.execute(
select(WikiUser).where(or_(WikiUser.username == phone, WikiUser.phone == phone))
)
if exists.scalars().first() is not None:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="该手机号已存在")
if position_id is not None:
if await session.get(WikiPosition, position_id) is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="岗位不存在")
password_hash, password_salt = build_password_fields(DEFAULT_USER_PASSWORD)
user = WikiUser(
username=phone,
phone=phone,
display_name=display_name,
email=(data.get("email") or "").strip() or None,
password_hash=password_hash,
password_salt=password_salt,
position_id=position_id,
store_name=store_name,
role=role,
status="active",
created_at=datetime.now(),
)
session.add(user)
await session.flush()
session.add(WikiUserProfile(user_id=user.id, profile_generated=False))
await session.commit()
user_id = user.id
logger.info("[Admin] 新建用户: %s(%s)", display_name, phone)
return {"success": True, "id": user_id, "initialPassword": DEFAULT_USER_PASSWORD}
@router.post("/admin/users/{user_id}/reset-password")
async def reset_password(
user_id: str,
_: WikiUser = Depends(require_admin),
):
"""把指定用户的密码重置为初始密码。"""
password_hash, password_salt = build_password_fields(DEFAULT_USER_PASSWORD)
async with AsyncSessionLocal() as session:
user = await session.get(WikiUser, user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
user.password_hash = password_hash
user.password_salt = password_salt
await session.commit()
username = user.username
logger.info("[Admin] 重置用户密码: %s", username)
return {"success": True, "initialPassword": DEFAULT_USER_PASSWORD}
@router.patch("/admin/users/{user_id}")
async def update_user(
user_id: str,
data: dict = Body(...),
_: WikiUser = Depends(require_admin),
):
"""更新用户的岗位、门店、角色或启用状态。"""
async with AsyncSessionLocal() as session:
user = await session.get(WikiUser, user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
if "positionId" in data:
position_id = (data.get("positionId") or "").strip() or None
if position_id is not None and await session.get(WikiPosition, position_id) is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="岗位不存在")
# 岗位变更后画像需要重新生成
if position_id != user.position_id:
profile = (
await session.execute(
select(WikiUserProfile).where(WikiUserProfile.user_id == user_id)
)
).scalars().first()
if profile is not None:
profile.profile_generated = False
user.position_id = position_id
if "storeName" in data:
user.store_name = (data.get("storeName") or "").strip() or None
if "displayName" in data:
new_name = (data.get("displayName") or "").strip()
if new_name:
user.display_name = new_name
if "role" in data:
role = (data.get("role") or "").strip()
if role not in ("user", "admin"):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="角色只能是 user 或 admin")
user.role = role
if "status" in data:
new_status = (data.get("status") or "").strip()
if new_status not in ("active", "disabled"):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="状态只能是 active 或 disabled")
user.status = new_status
await session.commit()
return {"success": True}
# ==================================== 岗位模板 ====================================
@router.get("/admin/positions")
async def list_positions(
only_missing: bool = Query(default=False, description="只看缺职责模板的岗位"),
_: WikiUser = Depends(require_admin),
):
"""岗位列表。`only_missing=true` 用于筛出需要人工补模板的岗位。"""
async with AsyncSessionLocal() as session:
stmt = select(WikiPosition)
if only_missing:
stmt = stmt.where(WikiPosition.template_missing.is_(True))
stmt = stmt.order_by(WikiPosition.dept_l1, WikiPosition.dept_l2, WikiPosition.name)
positions = (await session.execute(stmt)).scalars().all()
items = [_position_payload(p) for p in positions]
return {"success": True, "total": len(items), "items": items}
@router.patch("/admin/positions/{position_id}")
async def update_position(
position_id: str,
data: dict = Body(...),
_: WikiUser = Depends(require_admin),
):
"""维护岗位的职责与常用操作模板。"""
async with AsyncSessionLocal() as session:
position = await session.get(WikiPosition, position_id)
if position is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="岗位不存在")
if "dutyTemplate" in data:
position.duty_template = data.get("dutyTemplate") or None
if "commonOpsTemplate" in data:
position.common_ops_template = data.get("commonOpsTemplate") or None
# 职责模板补齐后自动摘掉「待补充」标记
position.template_missing = not bool((position.duty_template or "").strip())
await session.commit()
payload = _position_payload(position)
return {"success": True, "position": payload}