Chuiguohuang commited on
Commit
837a707
·
verified ·
1 Parent(s): 6e876c1

feat(admin,stats): 管理员可编辑任意队员数据 + 门将扑救统计与扑救榜

Browse files
Files changed (9) hide show
  1. app.py +48 -2
  2. src/db.py +27 -2
  3. src/models.py +4 -0
  4. src/repo.py +25 -3
  5. src/seed.py +19 -1
  6. src/view_admin.py +58 -3
  7. src/view_home.py +26 -4
  8. src/view_me.py +16 -5
  9. src/views.py +6 -1
app.py CHANGED
@@ -41,6 +41,10 @@ def server(input: Inputs, output: Outputs, session: Session) -> None:
41
  u = current_user.get()
42
  return bool(u and u["is_admin"])
43
 
 
 
 
 
44
  # ------------------------------------------------------------------ 页面主体
45
  @render.ui
46
  def app_body():
@@ -98,6 +102,10 @@ def server(input: Inputs, output: Outputs, session: Session) -> None:
98
  scorers = sorted(agg, key=lambda x: (-x["goals"], -x["assists"]))
99
  assisters = sorted(agg, key=lambda x: (-x["assists"], -x["goals"]))
100
  attend = sorted(agg, key=lambda x: (-x["attended"], -x["goals"]))
 
 
 
 
101
  mvp = repo.mvp_ranking(season)
102
 
103
  def rowsify(items, valuefn):
@@ -109,6 +117,8 @@ def server(input: Inputs, output: Outputs, session: Session) -> None:
109
  ("出勤榜", rowsify(attend, lambda x: f'{x["attended"]}/{x["total"]}')),
110
  ("MVP 榜", rowsify(mvp, lambda x: f'{x["votes"]} 票')),
111
  ]
 
 
112
  yield export_img.render_leaderboard_png(
113
  config.TEAM_NAME, label, dt.date.today().isoformat(), boards
114
  )
@@ -128,7 +138,7 @@ def server(input: Inputs, output: Outputs, session: Session) -> None:
128
  u = current_user.get()
129
  if not u:
130
  return ui.div()
131
- return views.my_form_view(repo.player_matchlog(u["id"]))
132
 
133
  @render.ui
134
  def my_trend():
@@ -146,11 +156,13 @@ def server(input: Inputs, output: Outputs, session: Session) -> None:
146
  u = current_user.get()
147
  if not u:
148
  return
 
149
  for m in repo.player_matchlog(u["id"]):
150
  mid = m["id"]
 
151
  repo.upsert_stat(
152
  u["id"], mid,
153
- input[f"g_{mid}"](), input[f"a_{mid}"](), input[f"att_{mid}"](),
154
  )
155
  bump()
156
  ui.notification_show("已保存你的数据 ✅", type="message")
@@ -219,6 +231,39 @@ def server(input: Inputs, output: Outputs, session: Session) -> None:
219
  return ui.div()
220
  return views.admin_players_view(repo.list_users())
221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  @reactive.effect
223
  @reactive.event(input.btn_add_match, ignore_init=True)
224
  def _add_match():
@@ -276,6 +321,7 @@ def server(input: Inputs, output: Outputs, session: Session) -> None:
276
  input.p_user(), input.p_name(),
277
  input.p_pw() or config.DEFAULT_PASSWORD,
278
  jersey, is_admin=bool(input.p_admin()), is_player=True,
 
279
  )
280
  except ValueError as e:
281
  ui.notification_show(str(e), type="error")
 
41
  u = current_user.get()
42
  return bool(u and u["is_admin"])
43
 
44
+ def user_is_gk(uid: int) -> bool:
45
+ """实时查询某队员当前是否门将(避免依赖登录时的旧状态)。"""
46
+ return any(x["id"] == uid and x["is_goalkeeper"] for x in repo.list_users())
47
+
48
  # ------------------------------------------------------------------ 页面主体
49
  @render.ui
50
  def app_body():
 
102
  scorers = sorted(agg, key=lambda x: (-x["goals"], -x["assists"]))
103
  assisters = sorted(agg, key=lambda x: (-x["assists"], -x["goals"]))
104
  attend = sorted(agg, key=lambda x: (-x["attended"], -x["goals"]))
105
+ keepers = sorted(
106
+ [r for r in agg if r.get("is_goalkeeper")],
107
+ key=lambda x: (-x["saves"], -x["attended"]),
108
+ )
109
  mvp = repo.mvp_ranking(season)
110
 
111
  def rowsify(items, valuefn):
 
117
  ("出勤榜", rowsify(attend, lambda x: f'{x["attended"]}/{x["total"]}')),
118
  ("MVP 榜", rowsify(mvp, lambda x: f'{x["votes"]} 票')),
119
  ]
120
+ if keepers: # 有门将才加扑救榜
121
+ boards.append(("扑救榜", rowsify(keepers, lambda x: f'{x["saves"]} 救')))
122
  yield export_img.render_leaderboard_png(
123
  config.TEAM_NAME, label, dt.date.today().isoformat(), boards
124
  )
 
138
  u = current_user.get()
139
  if not u:
140
  return ui.div()
141
+ return views.my_form_view(repo.player_matchlog(u["id"]), user_is_gk(u["id"]))
142
 
143
  @render.ui
144
  def my_trend():
 
156
  u = current_user.get()
157
  if not u:
158
  return
159
+ is_gk = user_is_gk(u["id"])
160
  for m in repo.player_matchlog(u["id"]):
161
  mid = m["id"]
162
+ saves = input[f"sv_{mid}"]() if is_gk else 0
163
  repo.upsert_stat(
164
  u["id"], mid,
165
+ input[f"g_{mid}"](), input[f"a_{mid}"](), input[f"att_{mid}"](), saves,
166
  )
167
  bump()
168
  ui.notification_show("已保存你的数据 ✅", type="message")
 
231
  return ui.div()
232
  return views.admin_players_view(repo.list_users())
233
 
234
+ # ------------------------------------------------------------------ 管理:编辑任意队员数据
235
+ @render.ui
236
+ def admin_edit_player():
237
+ data_version.get()
238
+ if not is_admin():
239
+ return ui.div()
240
+ uid_raw = input.ae_user()
241
+ if not uid_raw:
242
+ return ui.div("请选择要编辑的队员。", class_="sde-empty")
243
+ uid = int(uid_raw)
244
+ return views.admin_edit_player_view(repo.player_matchlog(uid), user_is_gk(uid))
245
+
246
+ @reactive.effect
247
+ @reactive.event(input.btn_ae_save, ignore_init=True)
248
+ def _ae_save():
249
+ if not input.btn_ae_save() or not is_admin():
250
+ return
251
+ uid_raw = input.ae_user()
252
+ if not uid_raw:
253
+ ui.notification_show("请先选择队员", type="warning")
254
+ return
255
+ uid = int(uid_raw)
256
+ repo.set_goalkeeper(uid, bool(input.ae_gk()))
257
+ for m in repo.player_matchlog(uid):
258
+ mid = m["id"]
259
+ repo.upsert_stat(
260
+ uid, mid,
261
+ input[f"ag_{mid}"](), input[f"aa_{mid}"](),
262
+ input[f"aatt_{mid}"](), input[f"asv_{mid}"](),
263
+ )
264
+ bump()
265
+ ui.notification_show("已保存该队员数据 ✅", type="message")
266
+
267
  @reactive.effect
268
  @reactive.event(input.btn_add_match, ignore_init=True)
269
  def _add_match():
 
321
  input.p_user(), input.p_name(),
322
  input.p_pw() or config.DEFAULT_PASSWORD,
323
  jersey, is_admin=bool(input.p_admin()), is_player=True,
324
+ is_goalkeeper=bool(input.p_gk()),
325
  )
326
  except ValueError as e:
327
  ui.notification_show(str(e), type="error")
src/db.py CHANGED
@@ -10,7 +10,7 @@ import logging
10
  from contextlib import contextmanager
11
  from typing import Iterator
12
 
13
- from sqlalchemy import create_engine
14
  from sqlalchemy.orm import Session, sessionmaker
15
 
16
  from .config import DATABASE_URL
@@ -43,7 +43,32 @@ def get_session() -> Iterator[Session]:
43
  session.close()
44
 
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  def init_db() -> None:
47
- """创建所有表(幂等)。"""
48
  Base.metadata.create_all(engine)
 
49
  logger.info("数据库已就绪:%s", DATABASE_URL)
 
10
  from contextlib import contextmanager
11
  from typing import Iterator
12
 
13
+ from sqlalchemy import create_engine, inspect, text
14
  from sqlalchemy.orm import Session, sessionmaker
15
 
16
  from .config import DATABASE_URL
 
43
  session.close()
44
 
45
 
46
+ def _run_light_migrations() -> None:
47
+ """轻量迁移:给「已存在的表」补上后期新增的列(幂等)。
48
+
49
+ create_all 只建缺失的表,不会给已有表加列;线上 Neon / 本地 SQLite 都已有
50
+ 历史数据,故这里用 inspector 检测缺列并 ALTER 补齐。区分方言以兼容布尔默认值
51
+ (Postgres 用 false,SQLite 用 0)。新增列均带默认值,老数据零影响。
52
+ """
53
+ insp = inspect(engine)
54
+ existing = set(insp.get_table_names())
55
+ bool_false = "false" if engine.dialect.name == "postgresql" else "0"
56
+ wanted = [
57
+ ("users", "is_goalkeeper", f"BOOLEAN NOT NULL DEFAULT {bool_false}"),
58
+ ("stats", "saves", "INTEGER NOT NULL DEFAULT 0"),
59
+ ]
60
+ for table, col, ddl in wanted:
61
+ if table not in existing:
62
+ continue # 新库由 create_all 直接建好(已含新列)
63
+ if col in {c["name"] for c in insp.get_columns(table)}:
64
+ continue
65
+ with engine.begin() as conn:
66
+ conn.execute(text(f"ALTER TABLE {table} ADD COLUMN {col} {ddl}"))
67
+ logger.info("迁移:已为 %s 表新增列 %s", table, col)
68
+
69
+
70
  def init_db() -> None:
71
+ """创建所有表(幂等)并执行轻量迁移补列。"""
72
  Base.metadata.create_all(engine)
73
+ _run_light_migrations()
74
  logger.info("数据库已就绪:%s", DATABASE_URL)
src/models.py CHANGED
@@ -38,6 +38,8 @@ class User(Base):
38
  is_admin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
39
  # is_player=True 才计入球员榜单;领队/教练等可设为 False
40
  is_player: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
 
 
41
  active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
42
  created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now)
43
 
@@ -64,6 +66,8 @@ class Stat(Base):
64
  match_id: Mapped[int] = mapped_column(ForeignKey("matches.id"), nullable=False)
65
  goals: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
66
  assists: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
 
 
67
  attended: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
68
  updated_at: Mapped[datetime] = mapped_column(
69
  DateTime, default=datetime.now, onupdate=datetime.now
 
38
  is_admin: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
39
  # is_player=True 才计入球员榜单;领队/教练等可设为 False
40
  is_player: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
41
+ # is_goalkeeper=True 的球员才显示/统计扑救数据,并出现在扑救榜
42
+ is_goalkeeper: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
43
  active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
44
  created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.now)
45
 
 
66
  match_id: Mapped[int] = mapped_column(ForeignKey("matches.id"), nullable=False)
67
  goals: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
68
  assists: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
69
+ # saves 扑救数:仅门将有意义,但所有行统一存储(默认 0),避免为门将单开一张表
70
+ saves: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
71
  attended: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
72
  updated_at: Mapped[datetime] = mapped_column(
73
  DateTime, default=datetime.now, onupdate=datetime.now
src/repo.py CHANGED
@@ -35,6 +35,7 @@ def authenticate(username: str, password: str) -> Optional[dict[str, Any]]:
35
  "username": u.username,
36
  "display_name": u.display_name,
37
  "is_admin": u.is_admin,
 
38
  "jersey": u.jersey_number,
39
  }
40
  return None
@@ -53,6 +54,7 @@ def list_users(active_only: bool = False) -> list[dict[str, Any]]:
53
  "jersey": u.jersey_number,
54
  "is_admin": u.is_admin,
55
  "is_player": u.is_player,
 
56
  "active": u.active,
57
  }
58
  for u in q.all()
@@ -66,6 +68,7 @@ def add_user(
66
  jersey: Optional[int] = None,
67
  is_admin: bool = False,
68
  is_player: bool = True,
 
69
  ) -> None:
70
  username = (username or "").strip()
71
  display_name = (display_name or "").strip()
@@ -82,11 +85,20 @@ def add_user(
82
  jersey_number=jersey,
83
  is_admin=bool(is_admin),
84
  is_player=bool(is_player),
 
85
  active=True,
86
  )
87
  )
88
 
89
 
 
 
 
 
 
 
 
 
90
  def reset_password(user_id: int, new_password: str) -> None:
91
  if not new_password:
92
  raise ValueError("新密码不能为空")
@@ -179,7 +191,12 @@ def clear_matches_and_stats() -> int:
179
 
180
  # ----------------------------------------------------------------------------- 个人数据录入
181
  def upsert_stat(
182
- user_id: int, match_id: int, goals: Any, assists: Any, attended: Any
 
 
 
 
 
183
  ) -> None:
184
  with get_session() as s:
185
  st = s.query(Stat).filter_by(user_id=user_id, match_id=match_id).one_or_none()
@@ -188,6 +205,7 @@ def upsert_stat(
188
  s.add(st)
189
  st.goals = max(0, int(goals or 0))
190
  st.assists = max(0, int(assists or 0))
 
191
  st.attended = bool(attended)
192
 
193
 
@@ -244,23 +262,26 @@ def player_aggregate(season: Optional[int] = None) -> list[dict[str, Any]]:
244
 
245
  agg: dict[int, dict[str, int]] = {}
246
  for st in stats:
247
- a = agg.setdefault(st.user_id, {"g": 0, "a": 0, "absent": 0})
248
  a["g"] += st.goals or 0
249
  a["a"] += st.assists or 0
 
250
  if not st.attended:
251
  a["absent"] += 1
252
 
253
  out: list[dict[str, Any]] = []
254
  for u in users:
255
- a = agg.get(u.id, {"g": 0, "a": 0, "absent": 0})
256
  out.append(
257
  {
258
  "user_id": u.id,
259
  "name": u.display_name,
260
  "jersey": u.jersey_number,
261
  "is_admin": u.is_admin,
 
262
  "goals": a["g"],
263
  "assists": a["a"],
 
264
  "ga": a["g"] + a["a"],
265
  "attended": total - a["absent"],
266
  "total": total,
@@ -284,6 +305,7 @@ def player_matchlog(user_id: int) -> list[dict[str, Any]]:
284
  "attended": st.attended if st else True,
285
  "goals": st.goals if st else 0,
286
  "assists": st.assists if st else 0,
 
287
  "has_record": st is not None,
288
  }
289
  )
 
35
  "username": u.username,
36
  "display_name": u.display_name,
37
  "is_admin": u.is_admin,
38
+ "is_goalkeeper": u.is_goalkeeper,
39
  "jersey": u.jersey_number,
40
  }
41
  return None
 
54
  "jersey": u.jersey_number,
55
  "is_admin": u.is_admin,
56
  "is_player": u.is_player,
57
+ "is_goalkeeper": u.is_goalkeeper,
58
  "active": u.active,
59
  }
60
  for u in q.all()
 
68
  jersey: Optional[int] = None,
69
  is_admin: bool = False,
70
  is_player: bool = True,
71
+ is_goalkeeper: bool = False,
72
  ) -> None:
73
  username = (username or "").strip()
74
  display_name = (display_name or "").strip()
 
85
  jersey_number=jersey,
86
  is_admin=bool(is_admin),
87
  is_player=bool(is_player),
88
+ is_goalkeeper=bool(is_goalkeeper),
89
  active=True,
90
  )
91
  )
92
 
93
 
94
+ def set_goalkeeper(user_id: int, is_goalkeeper: bool) -> None:
95
+ """标记/取消某队员为门将(决定是否显示扑救录入、是否进扑救榜)。"""
96
+ with get_session() as s:
97
+ u = s.get(User, user_id)
98
+ if u:
99
+ u.is_goalkeeper = bool(is_goalkeeper)
100
+
101
+
102
  def reset_password(user_id: int, new_password: str) -> None:
103
  if not new_password:
104
  raise ValueError("新密码不能为空")
 
191
 
192
  # ----------------------------------------------------------------------------- 个人数据录入
193
  def upsert_stat(
194
+ user_id: int,
195
+ match_id: int,
196
+ goals: Any,
197
+ assists: Any,
198
+ attended: Any,
199
+ saves: Any = 0,
200
  ) -> None:
201
  with get_session() as s:
202
  st = s.query(Stat).filter_by(user_id=user_id, match_id=match_id).one_or_none()
 
205
  s.add(st)
206
  st.goals = max(0, int(goals or 0))
207
  st.assists = max(0, int(assists or 0))
208
+ st.saves = max(0, int(saves or 0))
209
  st.attended = bool(attended)
210
 
211
 
 
262
 
263
  agg: dict[int, dict[str, int]] = {}
264
  for st in stats:
265
+ a = agg.setdefault(st.user_id, {"g": 0, "a": 0, "sv": 0, "absent": 0})
266
  a["g"] += st.goals or 0
267
  a["a"] += st.assists or 0
268
+ a["sv"] += st.saves or 0
269
  if not st.attended:
270
  a["absent"] += 1
271
 
272
  out: list[dict[str, Any]] = []
273
  for u in users:
274
+ a = agg.get(u.id, {"g": 0, "a": 0, "sv": 0, "absent": 0})
275
  out.append(
276
  {
277
  "user_id": u.id,
278
  "name": u.display_name,
279
  "jersey": u.jersey_number,
280
  "is_admin": u.is_admin,
281
+ "is_goalkeeper": u.is_goalkeeper,
282
  "goals": a["g"],
283
  "assists": a["a"],
284
+ "saves": a["sv"],
285
  "ga": a["g"] + a["a"],
286
  "attended": total - a["absent"],
287
  "total": total,
 
305
  "attended": st.attended if st else True,
306
  "goals": st.goals if st else 0,
307
  "assists": st.assists if st else 0,
308
+ "saves": st.saves if st else 0,
309
  "has_record": st is not None,
310
  }
311
  )
src/seed.py CHANGED
@@ -36,6 +36,9 @@ SEED_PLAYERS = [
36
  ("linjl", "Lin J.L.", 78),
37
  ]
38
 
 
 
 
39
  # 领队(管理员,不计入球员榜单)
40
  MANAGER = ("admin", "领队", None)
41
 
@@ -58,6 +61,11 @@ SEED_STATS = {
58
  "meng": [(2, 0, 0, False)], # 第 3 场缺勤
59
  }
60
 
 
 
 
 
 
61
 
62
  def ensure_seed() -> bool:
63
  """数据库为空时写入名单 + 示例数据。返回是否实际执行。"""
@@ -67,7 +75,11 @@ def ensure_seed() -> bool:
67
  return False
68
 
69
  for username, name, jersey in SEED_PLAYERS:
70
- add_user(username, name, DEFAULT_PASSWORD, jersey, is_admin=False, is_player=True)
 
 
 
 
71
  add_user(MANAGER[0], MANAGER[1], DEFAULT_PASSWORD, MANAGER[2], is_admin=True, is_player=False)
72
 
73
  _seed_demo_matches()
@@ -88,6 +100,12 @@ def _seed_demo_matches() -> None:
88
  continue
89
  for idx, goals, assists, attended in records:
90
  upsert_stat(uid[username], match_ids[idx], goals, assists, attended)
 
 
 
 
 
 
91
 
92
 
93
  def reset_demo() -> None:
 
36
  ("linjl", "Lin J.L.", 78),
37
  ]
38
 
39
+ # 示例门将(球衣 30):标记为门将后会出现在扑救榜并可录扑救
40
+ GK_USERNAMES = {"sunny"}
41
+
42
  # 领队(管理员,不计入球员榜单)
43
  MANAGER = ("admin", "领队", None)
44
 
 
61
  "meng": [(2, 0, 0, False)], # 第 3 场缺勤
62
  }
63
 
64
+ # 示例门将扑救:username -> [(场次下标, 扑救数), ...]
65
+ SEED_SAVES = {
66
+ "sunny": [(0, 4), (1, 6), (2, 3), (3, 5)],
67
+ }
68
+
69
 
70
  def ensure_seed() -> bool:
71
  """数据库为空时写入名单 + 示例数据。返回是否实际执行。"""
 
75
  return False
76
 
77
  for username, name, jersey in SEED_PLAYERS:
78
+ add_user(
79
+ username, name, DEFAULT_PASSWORD, jersey,
80
+ is_admin=False, is_player=True,
81
+ is_goalkeeper=(username in GK_USERNAMES),
82
+ )
83
  add_user(MANAGER[0], MANAGER[1], DEFAULT_PASSWORD, MANAGER[2], is_admin=True, is_player=False)
84
 
85
  _seed_demo_matches()
 
100
  continue
101
  for idx, goals, assists, attended in records:
102
  upsert_stat(uid[username], match_ids[idx], goals, assists, attended)
103
+ # 门将示例扑救(场次默认出勤、0 球 0 助攻、N 次扑救)
104
+ for username, records in SEED_SAVES.items():
105
+ if username not in uid:
106
+ continue
107
+ for idx, saves in records:
108
+ upsert_stat(uid[username], match_ids[idx], 0, 0, True, saves)
109
 
110
 
111
  def reset_demo() -> None:
src/view_admin.py CHANGED
@@ -49,12 +49,24 @@ def _admin_panel(user_choices: dict[str, str]) -> ui.Tag:
49
  ui.layout_columns(
50
  ui.input_text("p_pw", "初始密码", value=config.DEFAULT_PASSWORD),
51
  ui.input_switch("p_admin", "设为管理员", value=False),
52
- col_widths=[6, 6],
 
53
  fill=False,
54
  ),
55
  ui.input_action_button("btn_add_player", "➕ 添加队员", class_="btn-primary"),
56
  icon="➕",
57
  )
 
 
 
 
 
 
 
 
 
 
 
58
  reset_pw = theme.card(
59
  "重置密码",
60
  ui.layout_columns(
@@ -76,7 +88,9 @@ def _admin_panel(user_choices: dict[str, str]) -> ui.Tag:
76
  ui.input_action_button("btn_clear_demo", "🧹 清空比赛与数据", class_="btn-danger"),
77
  icon="🧹",
78
  )
79
- return ui.div(add_match, manage_match, roster, add_player, reset_pw, danger)
 
 
80
 
81
 
82
  def admin_match_editor(matches: list[dict[str, Any]]) -> ui.Tag:
@@ -112,7 +126,7 @@ def admin_match_editor(matches: list[dict[str, Any]]) -> ui.Tag:
112
 
113
 
114
  def admin_players_view(users: list[dict[str, Any]]) -> ui.Tag:
115
- head = ui.tags.tr(*[ui.tags.th(h) for h in ["#", "昵称", "登录名", "角色"]])
116
  body = []
117
  for u in users:
118
  body.append(
@@ -121,9 +135,50 @@ def admin_players_view(users: list[dict[str, Any]]) -> ui.Tag:
121
  ui.tags.td(u["display_name"]),
122
  ui.tags.td(ui.tags.code(u["username"])),
123
  ui.tags.td("领队" if u["is_admin"] else "球员"),
 
124
  )
125
  )
126
  return ui.div(
127
  ui.tags.table(ui.tags.thead(head), ui.tags.tbody(*body), class_="sde-table"),
128
  class_="sde-table-wrap",
129
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  ui.layout_columns(
50
  ui.input_text("p_pw", "初始密码", value=config.DEFAULT_PASSWORD),
51
  ui.input_switch("p_admin", "设为管理员", value=False),
52
+ ui.input_switch("p_gk", "门将", value=False),
53
+ col_widths=[6, 3, 3],
54
  fill=False,
55
  ),
56
  ui.input_action_button("btn_add_player", "➕ 添加队员", class_="btn-primary"),
57
  icon="➕",
58
  )
59
+ edit_player = theme.card(
60
+ "编辑队员数据",
61
+ ui.div(
62
+ "选择队员后可逐场修改其 出勤/进球/助攻/扑救;勾选「门将」该队员将进入扑救榜。改完点保存。",
63
+ class_="sde-sub",
64
+ ),
65
+ ui.input_select("ae_user", "选择队员", user_choices),
66
+ ui.output_ui("admin_edit_player"),
67
+ ui.input_action_button("btn_ae_save", "💾 保存该队员数据", class_="btn-primary"),
68
+ icon="✏️",
69
+ )
70
  reset_pw = theme.card(
71
  "重置密码",
72
  ui.layout_columns(
 
88
  ui.input_action_button("btn_clear_demo", "🧹 清空比赛与数据", class_="btn-danger"),
89
  icon="🧹",
90
  )
91
+ return ui.div(
92
+ add_match, manage_match, roster, edit_player, add_player, reset_pw, danger
93
+ )
94
 
95
 
96
  def admin_match_editor(matches: list[dict[str, Any]]) -> ui.Tag:
 
126
 
127
 
128
  def admin_players_view(users: list[dict[str, Any]]) -> ui.Tag:
129
+ head = ui.tags.tr(*[ui.tags.th(h) for h in ["#", "昵称", "登录名", "角色", "门将"]])
130
  body = []
131
  for u in users:
132
  body.append(
 
135
  ui.tags.td(u["display_name"]),
136
  ui.tags.td(ui.tags.code(u["username"])),
137
  ui.tags.td("领队" if u["is_admin"] else "球员"),
138
+ ui.tags.td("🧤" if u.get("is_goalkeeper") else "—"),
139
  )
140
  )
141
  return ui.div(
142
  ui.tags.table(ui.tags.thead(head), ui.tags.tbody(*body), class_="sde-table"),
143
  class_="sde-table-wrap",
144
  )
145
+
146
+
147
+ def admin_edit_player_view(matchlog: list[dict[str, Any]], is_gk: bool) -> ui.Tag:
148
+ """管理员逐场编辑某队员数据:门将开关 + 出勤/进球/助攻/扑救。
149
+
150
+ 输入 id 用 a 前缀(aatt_/ag_/aa_/asv_),与队员本人录入的 id 不冲突。
151
+ """
152
+ gk_switch = ui.input_switch(
153
+ "ae_gk", "该队员是门将(计入扑救榜,可录扑救)", value=bool(is_gk)
154
+ )
155
+ if not matchlog:
156
+ return ui.div(
157
+ gk_switch, ui.div("该队员暂无可编辑比赛,请先录入比赛。", class_="sde-empty")
158
+ )
159
+ head = ui.tags.tr(
160
+ *[ui.tags.th(h) for h in ["日期", "对手", "出勤", "进球", "助攻", "扑救"]]
161
+ )
162
+ body = []
163
+ for m in matchlog:
164
+ mid = m["id"]
165
+ body.append(
166
+ ui.tags.tr(
167
+ ui.tags.td(m["date"]),
168
+ ui.tags.td(m["opponent"]),
169
+ ui.tags.td(ui.input_checkbox(f"aatt_{mid}", "", value=bool(m["attended"]))),
170
+ ui.tags.td(ui.input_numeric(f"ag_{mid}", None, int(m["goals"]), min=0, max=99, width="70px")),
171
+ ui.tags.td(ui.input_numeric(f"aa_{mid}", None, int(m["assists"]), min=0, max=99, width="70px")),
172
+ ui.tags.td(ui.input_numeric(f"asv_{mid}", None, int(m["saves"]), min=0, max=99, width="70px")),
173
+ )
174
+ )
175
+ return ui.div(
176
+ gk_switch,
177
+ ui.div(
178
+ ui.tags.table(
179
+ ui.tags.thead(head), ui.tags.tbody(*body),
180
+ class_="sde-table sde-form-table",
181
+ ),
182
+ class_="sde-table-wrap",
183
+ ),
184
+ )
src/view_home.py CHANGED
@@ -32,15 +32,24 @@ def home_view(
32
  scorers = sorted(agg, key=lambda x: (-x["goals"], -x["assists"], -x["attended"]))
33
  assisters = sorted(agg, key=lambda x: (-x["assists"], -x["goals"]))
34
  attend = sorted(agg, key=lambda x: (-x["attended"], -x["goals"]))
 
 
 
 
35
 
36
- boards = ui.layout_columns(
37
  theme.card("射手榜", _board_goals(scorers, me_id), icon="⚽"),
38
  theme.card("助攻榜", _board_assists(assisters, me_id), icon="🎯"),
39
  theme.card("出勤榜", _board_attend(attend, me_id), icon="📋"),
40
  theme.card("MVP 榜", _board_mvp(mvp, me_id), icon="🏅", sub="队员投票"),
41
- col_widths=[3, 3, 3, 3],
42
- fill=False,
43
- )
 
 
 
 
 
44
  return ui.div(
45
  theme.card("球队战绩", stats, icon="🏆"),
46
  theme.card(
@@ -119,6 +128,19 @@ def _board_attend(rows: list[dict], me_id: Optional[int]) -> ui.Tag:
119
  )
120
 
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  def _board_mvp(rows: list[dict], me_id: Optional[int]) -> ui.Tag:
123
  return _rank_table(
124
  rows,
 
32
  scorers = sorted(agg, key=lambda x: (-x["goals"], -x["assists"], -x["attended"]))
33
  assisters = sorted(agg, key=lambda x: (-x["assists"], -x["goals"]))
34
  attend = sorted(agg, key=lambda x: (-x["attended"], -x["goals"]))
35
+ keepers = sorted(
36
+ [r for r in agg if r.get("is_goalkeeper")],
37
+ key=lambda x: (-x["saves"], -x["attended"]),
38
+ )
39
 
40
+ board_cards = [
41
  theme.card("射手榜", _board_goals(scorers, me_id), icon="⚽"),
42
  theme.card("助攻榜", _board_assists(assisters, me_id), icon="🎯"),
43
  theme.card("出勤榜", _board_attend(attend, me_id), icon="📋"),
44
  theme.card("MVP 榜", _board_mvp(mvp, me_id), icon="🏅", sub="队员投票"),
45
+ ]
46
+ widths = [3, 3, 3, 3]
47
+ if keepers: # 有门将才显示扑救榜;3+2 两行更均衡
48
+ board_cards.append(
49
+ theme.card("扑救榜", _board_saves(keepers, me_id), icon="🧤", sub="仅门将")
50
+ )
51
+ widths = [4, 4, 4, 6, 6]
52
+ boards = ui.layout_columns(*board_cards, col_widths=widths, fill=False)
53
  return ui.div(
54
  theme.card("球队战绩", stats, icon="🏆"),
55
  theme.card(
 
128
  )
129
 
130
 
131
+ def _board_saves(rows: list[dict], me_id: Optional[int]) -> ui.Tag:
132
+ return _rank_table(
133
+ rows,
134
+ [
135
+ ("#", lambda r, i: _medal(i), "sde-rank"),
136
+ ("门将", lambda r, i: _player_cell(r, me_id), ""),
137
+ ("扑救", lambda r, i: str(r["saves"]), "sde-num"),
138
+ ("出场", lambda r, i: f'{r["attended"]}/{r["total"]}', "sde-num"),
139
+ ],
140
+ me_id,
141
+ )
142
+
143
+
144
  def _board_mvp(rows: list[dict], me_id: Optional[int]) -> ui.Tag:
145
  return _rank_table(
146
  rows,
src/view_me.py CHANGED
@@ -54,15 +54,17 @@ def _my_panel() -> ui.Tag:
54
  def my_totals_view(rank: Optional[dict[str, Any]]) -> ui.Tag:
55
  if not rank:
56
  return ui.div()
57
- cards = ui.div(
58
  theme.stat(rank["goals"], "我的进球", f'榜单第 {rank["goal_rank"]}/{rank["n_players"]}'),
59
  theme.stat(
60
  rank["assists"], "我的助攻", f'榜单第 {rank["assist_rank"]}/{rank["n_players"]}', "blue"
61
  ),
62
  theme.stat(rank["ga"], "进球+助攻", accent="cream"),
63
  theme.stat(f'{rank["attended"]}/{rank["total"]}', "出场", accent="green"),
64
- class_="sde-stats cols-4",
65
- )
 
 
66
  return theme.card("我的数据总览", cards, icon="📊")
67
 
68
 
@@ -125,10 +127,10 @@ def my_trend_view(matchlog: list[dict[str, Any]]) -> ui.Tag:
125
  return theme.card("我的进球/助攻趋势", trend_svg(matchlog), icon="📈", sub="按时间正序")
126
 
127
 
128
- def my_form_view(matchlog: list[dict[str, Any]]) -> ui.Tag:
129
  """逐场登记:每场一张卡片,出勤/进球/助攻控件 flex 换行,手机端不溢出。
130
 
131
- 输入框 id(att_/g_/a_)保持不变,server 端保存逻辑无需改动。
132
  """
133
  if not matchlog:
134
  return ui.div("还没有比赛,等领队录入比分后即可登记。", class_="sde-empty")
@@ -154,6 +156,15 @@ def my_form_view(matchlog: list[dict[str, Any]]) -> ui.Tag:
154
  ui.input_numeric(f"a_{mid}", None, int(m["assists"]), min=0, max=99, width="80px"),
155
  class_="sde-ctl",
156
  ),
 
 
 
 
 
 
 
 
 
157
  class_="sde-ctl-row",
158
  ),
159
  class_="sde-mc sde-mc-form",
 
54
  def my_totals_view(rank: Optional[dict[str, Any]]) -> ui.Tag:
55
  if not rank:
56
  return ui.div()
57
+ items = [
58
  theme.stat(rank["goals"], "我的进球", f'榜单第 {rank["goal_rank"]}/{rank["n_players"]}'),
59
  theme.stat(
60
  rank["assists"], "我的助攻", f'榜单第 {rank["assist_rank"]}/{rank["n_players"]}', "blue"
61
  ),
62
  theme.stat(rank["ga"], "进球+助攻", accent="cream"),
63
  theme.stat(f'{rank["attended"]}/{rank["total"]}', "出场", accent="green"),
64
+ ]
65
+ if rank.get("is_goalkeeper"):
66
+ items.append(theme.stat(rank.get("saves", 0), "我的扑救", "门将", accent="blue"))
67
+ cards = ui.div(*items, class_="sde-stats cols-4")
68
  return theme.card("我的数据总览", cards, icon="📊")
69
 
70
 
 
127
  return theme.card("我的进球/助攻趋势", trend_svg(matchlog), icon="📈", sub="按时间正序")
128
 
129
 
130
+ def my_form_view(matchlog: list[dict[str, Any]], is_gk: bool = False) -> ui.Tag:
131
  """逐场登记:每场一张卡片,出勤/进球/助攻控件 flex 换行,手机端不溢出。
132
 
133
+ 输入框 id(att_/g_/a_)保持不变;门将额外多一个扑救栏(sv_)。
134
  """
135
  if not matchlog:
136
  return ui.div("还没有比赛,等领队录入比分后即可登记。", class_="sde-empty")
 
156
  ui.input_numeric(f"a_{mid}", None, int(m["assists"]), min=0, max=99, width="80px"),
157
  class_="sde-ctl",
158
  ),
159
+ (
160
+ ui.div(
161
+ ui.span("扑救", class_="sde-ctl-l"),
162
+ ui.input_numeric(f"sv_{mid}", None, int(m["saves"]), min=0, max=99, width="80px"),
163
+ class_="sde-ctl",
164
+ )
165
+ if is_gk
166
+ else None
167
+ ),
168
  class_="sde-ctl-row",
169
  ),
170
  class_="sde-mc sde-mc-form",
src/views.py CHANGED
@@ -9,7 +9,11 @@
9
  """
10
  from __future__ import annotations
11
 
12
- from .view_admin import admin_match_editor, admin_players_view
 
 
 
 
13
  from .view_auth import app_shell, login_view
14
  from .view_home import home_view
15
  from .view_me import (
@@ -31,4 +35,5 @@ __all__ = [
31
  "my_mvp_form_view",
32
  "admin_match_editor",
33
  "admin_players_view",
 
34
  ]
 
9
  """
10
  from __future__ import annotations
11
 
12
+ from .view_admin import (
13
+ admin_edit_player_view,
14
+ admin_match_editor,
15
+ admin_players_view,
16
+ )
17
  from .view_auth import app_shell, login_view
18
  from .view_home import home_view
19
  from .view_me import (
 
35
  "my_mvp_form_view",
36
  "admin_match_editor",
37
  "admin_players_view",
38
+ "admin_edit_player_view",
39
  ]