新增材料上传进度,一楼活动全员可见仅作记录并支持成员补充材料
This commit is contained in:
+73
-16
@@ -176,9 +176,14 @@ def activity_public(row: Any) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def normal_activity_clause():
|
||||
return activities.c.id.not_in(select(center_activity_meta.c.activity_id))
|
||||
|
||||
|
||||
def visible_clause(viewer_id: str):
|
||||
"""一条活动对当前账号可见的条件:公开活动、自己发起的、自己参加过的。"""
|
||||
"""一楼记录对登录成员全员可见;普通活动沿用公开、发起人和参加者规则。"""
|
||||
return or_(
|
||||
activities.c.id.in_(select(center_activity_meta.c.activity_id)),
|
||||
activities.c.visibility == "public",
|
||||
activities.c.organizer_id == viewer_id,
|
||||
activities.c.id.in_(
|
||||
@@ -215,6 +220,17 @@ async def fetch_activity(db: AsyncSession, activity_id: str):
|
||||
return row
|
||||
|
||||
|
||||
async def is_center_activity(db: AsyncSession, activity_id: str) -> bool:
|
||||
return (await db.execute(select(center_activity_meta.c.activity_id).where(
|
||||
center_activity_meta.c.activity_id == activity_id
|
||||
))).first() is not None
|
||||
|
||||
|
||||
async def require_participatory_activity(db: AsyncSession, activity_id: str):
|
||||
if await is_center_activity(db, activity_id):
|
||||
raise HTTPException(409, '赋能中心一楼活动仅作记录,不接受参加或参加状态变更')
|
||||
|
||||
|
||||
async def participant_rows(db: AsyncSession, activity_ids: list[str]) -> dict[str, list[dict]]:
|
||||
"""一次性取出若干活动的参加者,按活动 id 分组,避免逐条查询。"""
|
||||
grouped: dict[str, list[dict]] = {}
|
||||
@@ -249,6 +265,7 @@ async def serialize_activities(db: AsyncSession, rows: list[Any], viewer_id: str
|
||||
meta_rows = (await db.execute(select(center_activity_meta).where(center_activity_meta.c.activity_id.in_(ids)))).mappings().all() if ids else []
|
||||
photos = {r['activity_id']: json.loads(r['photo_ids']) for r in meta_rows}
|
||||
materials = {r['activity_id']: r['material_id'] for r in meta_rows}
|
||||
packages = await center.activity_materials(db, list(photos))
|
||||
|
||||
organizer_ids = {row["organizer_id"] for row in rows}
|
||||
organizers: dict[str, dict] = {}
|
||||
@@ -258,14 +275,18 @@ async def serialize_activities(db: AsyncSession, rows: list[Any], viewer_id: str
|
||||
|
||||
items = []
|
||||
for row in rows:
|
||||
members = people.get(row["id"], [])
|
||||
is_center = row['id'] in photos
|
||||
members = [] if is_center else people.get(row["id"], [])
|
||||
mine = next((m for m in members if m["user_id"] == viewer_id), None)
|
||||
items.append(
|
||||
{
|
||||
**activity_public(row),
|
||||
"record_type": "center" if row['id'] in photos else "normal",
|
||||
"record_type": "center" if is_center else "normal",
|
||||
"visibility": "public" if is_center else row['visibility'],
|
||||
"capacity": None if is_center else row['capacity'],
|
||||
"photo_ids": photos.get(row['id'], []),
|
||||
"material_id": materials.get(row['id']),
|
||||
"materials": packages.get(row['id'], []) if is_center else [],
|
||||
"organizer": organizers.get(row["organizer_id"]),
|
||||
"participants": members,
|
||||
"participant_count": len(members),
|
||||
@@ -273,6 +294,8 @@ async def serialize_activities(db: AsyncSession, rows: list[Any], viewer_id: str
|
||||
"my_participation": mine,
|
||||
}
|
||||
)
|
||||
for item in items:
|
||||
item['photo_ids'] = list(dict.fromkeys([*item['photo_ids'], *(photo for package in item['materials'] for photo in package['photo_ids'])]))
|
||||
return items
|
||||
|
||||
|
||||
@@ -281,14 +304,14 @@ async def user_stats(db: AsyncSession, user_id: str, *, public_only: bool = Fals
|
||||
stmt = (
|
||||
select(participations.c.status, activities.c.start_at, activities.c.visibility)
|
||||
.join(activities, activities.c.id == participations.c.activity_id)
|
||||
.where(and_(participations.c.user_id == user_id, participations.c.status != "pending"))
|
||||
.where(and_(participations.c.user_id == user_id, participations.c.status != "pending", normal_activity_clause()))
|
||||
)
|
||||
if public_only:
|
||||
stmt = stmt.where(activities.c.visibility == "public")
|
||||
rows = (await db.execute(stmt)).mappings().all()
|
||||
|
||||
organized_stmt = select(func.count()).select_from(activities).where(
|
||||
activities.c.organizer_id == user_id
|
||||
activities.c.organizer_id == user_id, normal_activity_clause()
|
||||
)
|
||||
if public_only:
|
||||
organized_stmt = organized_stmt.where(activities.c.visibility == "public")
|
||||
@@ -533,6 +556,7 @@ async def _require_participant(db: AsyncSession, activity_id: str, user_id: str)
|
||||
|
||||
|
||||
async def _add_participant(db: AsyncSession, activity: Any, user_id: str, role: str, status: str, note: str = "") -> None:
|
||||
await require_participatory_activity(db, activity['id'])
|
||||
if activity["capacity"] is not None:
|
||||
current = int(
|
||||
(
|
||||
@@ -571,6 +595,10 @@ async def lifespan(_app: FastAPI):
|
||||
if 'material_id' not in columns:
|
||||
await conn.execute(text('ALTER TABLE center_activity_meta ADD COLUMN material_id VARCHAR(32)'))
|
||||
await _migrate_legacy(conn)
|
||||
# 一楼历史活动统一作为公开记录,历史参加数据保留存档但不再参与统计。
|
||||
center_ids = select(center_activity_meta.c.activity_id)
|
||||
await conn.execute(update(activities).where(activities.c.id.in_(center_ids)).values(visibility='public', capacity=None))
|
||||
await conn.execute(update(join_links).where(join_links.c.activity_id.in_(center_ids), join_links.c.used == 0).values(used=2))
|
||||
backup_task: asyncio.Task | None = None
|
||||
if BACKUP_ENABLED:
|
||||
hour, minute = parse_time(BACKUP_TIME)
|
||||
@@ -853,6 +881,8 @@ async def _notify_new_activity(activity_id: str, organizer_name: str, base_url:
|
||||
row = (await db.execute(select(activities).where(activities.c.id == activity_id))).mappings().first()
|
||||
if row is None: # 活动可能已被删除
|
||||
return
|
||||
if await is_center_activity(db, activity_id):
|
||||
return
|
||||
if row["visibility"] != "public":
|
||||
return # 私密活动不群发
|
||||
recipients = (
|
||||
@@ -1441,7 +1471,7 @@ async def overview(db: AsyncSession = Depends(get_db), _viewer: dict = Depends(c
|
||||
(
|
||||
await db.execute(
|
||||
select(func.count()).select_from(activities)
|
||||
.where(activities.c.visibility == "public")
|
||||
.where(activities.c.visibility == "public", normal_activity_clause())
|
||||
)
|
||||
).scalar()
|
||||
or 0
|
||||
@@ -1452,7 +1482,7 @@ async def overview(db: AsyncSession = Depends(get_db), _viewer: dict = Depends(c
|
||||
select(func.count())
|
||||
.select_from(participations)
|
||||
.join(activities, activities.c.id == participations.c.activity_id)
|
||||
.where(participations.c.status != "pending", activities.c.visibility == "public")
|
||||
.where(participations.c.status != "pending", activities.c.visibility == "public", normal_activity_clause())
|
||||
)
|
||||
).scalar()
|
||||
or 0
|
||||
@@ -1461,7 +1491,7 @@ async def overview(db: AsyncSession = Depends(get_db), _viewer: dict = Depends(c
|
||||
(
|
||||
await db.execute(
|
||||
select(func.count()).select_from(activities)
|
||||
.where(and_(activities.c.visibility == "public", activities.c.start_at >= now_ms()))
|
||||
.where(and_(activities.c.visibility == "public", activities.c.start_at >= now_ms(), normal_activity_clause()))
|
||||
)
|
||||
).scalar()
|
||||
or 0
|
||||
@@ -1501,7 +1531,7 @@ async def list_users(q: str = "", department: str = "", db: AsyncSession = Depen
|
||||
.join(activities, activities.c.id == participations.c.activity_id)
|
||||
.where(and_(participations.c.user_id.in_(user_ids),
|
||||
activities.c.visibility == "public",
|
||||
participations.c.status != "pending"))
|
||||
participations.c.status != "pending", normal_activity_clause()))
|
||||
.group_by(participations.c.user_id)
|
||||
)
|
||||
).all()
|
||||
@@ -1513,7 +1543,7 @@ async def list_users(q: str = "", department: str = "", db: AsyncSession = Depen
|
||||
.join(activities, activities.c.id == participations.c.activity_id)
|
||||
.where(and_(participations.c.user_id.in_(user_ids),
|
||||
activities.c.visibility == "public",
|
||||
participations.c.status == "attended"))
|
||||
participations.c.status == "attended", normal_activity_clause()))
|
||||
.group_by(participations.c.user_id)
|
||||
)
|
||||
).all()
|
||||
@@ -1523,7 +1553,7 @@ async def list_users(q: str = "", department: str = "", db: AsyncSession = Depen
|
||||
await db.execute(
|
||||
select(activities.c.organizer_id, func.count())
|
||||
.where(and_(activities.c.organizer_id.in_(user_ids),
|
||||
activities.c.visibility == "public"))
|
||||
activities.c.visibility == "public", normal_activity_clause()))
|
||||
.group_by(activities.c.organizer_id)
|
||||
)
|
||||
).all()
|
||||
@@ -1597,11 +1627,11 @@ async def list_activities(
|
||||
if scope == "mine":
|
||||
stmt = stmt.where(activities.c.organizer_id == viewer["id"])
|
||||
elif scope == "joined":
|
||||
stmt = stmt.where(
|
||||
stmt = stmt.where(normal_activity_clause(),
|
||||
activities.c.id.in_(select(participations.c.activity_id).where(participations.c.user_id == viewer["id"]))
|
||||
)
|
||||
elif scope == "upcoming":
|
||||
stmt = stmt.where(activities.c.start_at >= now_ms())
|
||||
stmt = stmt.where(activities.c.start_at >= now_ms(), normal_activity_clause())
|
||||
if department:
|
||||
# 按部门过滤:该部门成员发起或参加的活动
|
||||
dept_user_ids = select(users.c.id).where(users.c.department == department)
|
||||
@@ -1633,6 +1663,8 @@ async def create_activity(payload: ActivityIn, request: Request, db: AsyncSessio
|
||||
if payload.record_type == 'center':
|
||||
if not payload.material_id: raise HTTPException(422, '一楼活动须提交包含照片的ZIP材料包')
|
||||
payload.photo_ids = await center.material_photos(db, payload.material_id, viewer['id'])
|
||||
payload.visibility = 'public'
|
||||
payload.capacity = None
|
||||
elif payload.photo_ids: raise HTTPException(422, '请先选择赋能中心一楼活动记录')
|
||||
dup_since = now_ms() - DUPLICATE_WINDOW_MS
|
||||
dup = (
|
||||
@@ -1671,12 +1703,13 @@ async def create_activity(payload: ActivityIn, request: Request, db: AsyncSessio
|
||||
activity = await fetch_activity(db, activity_id)
|
||||
await center.save_meta(db, activity_id, payload.record_type, payload.photo_ids, viewer['id'], payload.material_id)
|
||||
# 发起人自己就是这条记录的主人(不算"报名")
|
||||
await _add_participant(db, activity, viewer["id"], "organizer", "attended" if payload.start_at <= stamp else "joined")
|
||||
if payload.record_type != 'center':
|
||||
await _add_participant(db, activity, viewer["id"], "organizer", "attended" if payload.start_at <= stamp else "joined")
|
||||
await db.commit()
|
||||
items = await serialize_activities(db, [activity], viewer["id"])
|
||||
|
||||
# 通知其他已注册用户(公开活动):后台任务发邮件,不阻塞响应、不影响创建结果
|
||||
if NOTIFY_ENABLED and payload.visibility == "public" and not DEV_MODE:
|
||||
if NOTIFY_ENABLED and payload.record_type != 'center' and payload.visibility == "public" and not DEV_MODE:
|
||||
base_url = _site_base_url(request)
|
||||
organizer_name = viewer.get("display_name") or viewer.get("username") or "有成员"
|
||||
asyncio.create_task(_notify_new_activity(activity_id, organizer_name, base_url))
|
||||
@@ -1687,7 +1720,7 @@ async def create_activity(payload: ActivityIn, request: Request, db: AsyncSessio
|
||||
@app.get("/api/activities/{activity_id}")
|
||||
async def get_activity(activity_id: str, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||||
row = await fetch_activity(db, activity_id)
|
||||
if row["visibility"] != "public" and row["organizer_id"] != viewer["id"]:
|
||||
if row["visibility"] != "public" and row["organizer_id"] != viewer["id"] and not await is_center_activity(db, activity_id):
|
||||
member = await _require_participant(db, activity_id, viewer["id"])
|
||||
if member is None or member["status"] == "pending":
|
||||
raise HTTPException(status_code=403, detail="这是一条私密活动,你没有查看权限")
|
||||
@@ -1712,10 +1745,17 @@ async def update_activity(
|
||||
if kind == 'center' and not old_meta and not material_id: raise HTTPException(422, '一楼活动须提交包含照片的ZIP材料包')
|
||||
if kind == 'center': await center.validate_photos(db, photo_ids, viewer['id'], json.loads(old_meta['photo_ids']) if old_meta else [])
|
||||
elif photo_ids and payload.record_type != 'normal': raise HTTPException(422, '请先选择赋能中心一楼活动记录')
|
||||
if old_meta and old_meta['material_id']:
|
||||
await center.link_material(db, activity_id, old_meta['material_id'])
|
||||
await db.execute(delete(center_activity_meta).where(center_activity_meta.c.activity_id == activity_id))
|
||||
if kind == 'center':
|
||||
await db.execute(insert(center_activity_meta).values(activity_id=activity_id,photo_ids=json.dumps(photo_ids),material_id=material_id))
|
||||
if material_id: await center.link_material(db, activity_id, material_id)
|
||||
changes.update(visibility='public', capacity=None)
|
||||
await db.execute(update(join_links).where(join_links.c.activity_id == activity_id, join_links.c.used == 0).values(used=2))
|
||||
if not changes.get('location', row['location']).strip(): changes['location'] = '赋能中心一楼'
|
||||
elif old_meta and await _require_participant(db, activity_id, viewer['id']) is None:
|
||||
await _add_participant(db, row, viewer['id'], 'organizer', 'attended' if changes.get('start_at', row['start_at']) <= now_ms() else 'joined')
|
||||
if "title" in changes:
|
||||
changes["title"] = changes["title"].strip()
|
||||
if not changes["title"]:
|
||||
@@ -1729,6 +1769,17 @@ async def update_activity(
|
||||
return {"activity": items[0]}
|
||||
|
||||
|
||||
@app.post('/api/activities/{activity_id}/materials')
|
||||
async def add_activity_material(activity_id: str, payload: center.MaterialIn, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||||
row = await fetch_activity(db, activity_id)
|
||||
if not await is_center_activity(db, activity_id):
|
||||
raise HTTPException(409, '仅赋能中心一楼活动支持成员补充材料')
|
||||
await center.material_photos(db, payload.material_id, viewer['id'])
|
||||
await center.link_material(db, activity_id, payload.material_id)
|
||||
await db.commit()
|
||||
return {'activity': (await serialize_activities(db, [row], viewer['id']))[0]}
|
||||
|
||||
|
||||
@app.delete("/api/activities/{activity_id}")
|
||||
async def delete_activity(activity_id: str, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||||
row = await fetch_activity(db, activity_id)
|
||||
@@ -1744,6 +1795,7 @@ async def delete_activity(activity_id: str, db: AsyncSession = Depends(get_db),
|
||||
async def claim_activity(activity_id: str, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||||
""""我也参加过":立即加入这条记录,不再需要管理员确认。"""
|
||||
row = await fetch_activity(db, activity_id)
|
||||
await require_participatory_activity(db, activity_id)
|
||||
if row["visibility"] != "public":
|
||||
raise HTTPException(status_code=403, detail="私密活动需要由发起人添加你参加")
|
||||
if await _require_participant(db, activity_id, viewer["id"]) is not None:
|
||||
@@ -1758,6 +1810,7 @@ async def claim_activity(activity_id: str, db: AsyncSession = Depends(get_db), v
|
||||
@app.post("/api/activities/{activity_id}/leave")
|
||||
async def leave_activity(activity_id: str, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)) -> dict:
|
||||
row = await fetch_activity(db, activity_id)
|
||||
await require_participatory_activity(db, activity_id)
|
||||
if row["organizer_id"] == viewer["id"]:
|
||||
raise HTTPException(status_code=400, detail="发起人不能退出自己的活动,可以选择删除该活动")
|
||||
mine = await _require_participant(db, activity_id, viewer["id"])
|
||||
@@ -1777,6 +1830,7 @@ async def remove_participant(
|
||||
activity_id: str, user_id: str, db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user)
|
||||
) -> dict:
|
||||
row = await fetch_activity(db, activity_id)
|
||||
await require_participatory_activity(db, activity_id)
|
||||
if user_id == row["organizer_id"]:
|
||||
raise HTTPException(status_code=400, detail="发起人不能被移除")
|
||||
if row["organizer_id"] != viewer["id"] and user_id != viewer["id"]:
|
||||
@@ -1799,6 +1853,7 @@ async def update_participation(
|
||||
db: AsyncSession = Depends(get_db), viewer: dict = Depends(current_user),
|
||||
) -> dict:
|
||||
row = await fetch_activity(db, activity_id)
|
||||
await require_participatory_activity(db, activity_id)
|
||||
is_organizer = row["organizer_id"] == viewer["id"]
|
||||
if not is_organizer and user_id != viewer["id"]:
|
||||
raise HTTPException(status_code=403, detail="只能修改自己的参加状态")
|
||||
@@ -1880,6 +1935,8 @@ async def join_by_email_link(token: str, request: Request, db: AsyncSession = De
|
||||
user = (await db.execute(select(users).where(users.c.id == link["user_id"]))).mappings().first()
|
||||
if row is None or user is None:
|
||||
return HTMLResponse(_join_page("这条活动记录已被删除。", "err"), status_code=200)
|
||||
if await is_center_activity(db, row['id']):
|
||||
return HTMLResponse(_join_page('赋能中心一楼活动仅作记录,无需参加。', 'ok', row['title']))
|
||||
if row["visibility"] != "public":
|
||||
return HTMLResponse(_join_page("活动已改为私密,该邀请已失效。", "err"))
|
||||
if request.method == "GET":
|
||||
|
||||
Reference in New Issue
Block a user