Spaces:
Running on Zero

shamiur commited on
Commit
214d20b
·
1 Parent(s): 783f268

Part 211: Full team management (add/delete/role/activity)

Browse files
src/sunnyware/main.py CHANGED
@@ -30,6 +30,7 @@ from .routes import approvals as approvals_routes
30
  from .routes import sso as sso_routes
31
  from .routes import authkit as authkit_routes
32
  from .routes import workos_admin as workos_admin_routes
 
33
  from .routes import agent as agent_routes
34
  from .routes import eval as eval_routes
35
  from .routes import mcp as mcp_routes
@@ -132,6 +133,7 @@ app.include_router(hitl_routes.router)
132
  app.include_router(sso_routes.router)
133
  app.include_router(authkit_routes.router)
134
  app.include_router(workos_admin_routes.router)
 
135
  app.include_router(agent_routes.router)
136
  app.include_router(tools_routes.router)
137
  app.include_router(sessions_routes.router)
 
30
  from .routes import sso as sso_routes
31
  from .routes import authkit as authkit_routes
32
  from .routes import workos_admin as workos_admin_routes
33
+ from .routes import team as team_routes
34
  from .routes import agent as agent_routes
35
  from .routes import eval as eval_routes
36
  from .routes import mcp as mcp_routes
 
133
  app.include_router(sso_routes.router)
134
  app.include_router(authkit_routes.router)
135
  app.include_router(workos_admin_routes.router)
136
+ app.include_router(team_routes.router)
137
  app.include_router(agent_routes.router)
138
  app.include_router(tools_routes.router)
139
  app.include_router(sessions_routes.router)
src/sunnyware/routes/auth.py CHANGED
@@ -55,4 +55,29 @@ async def auth_login(req: Request):
55
  return JSONResponse({"error": "Valid email required"}, status_code=400)
56
 
57
  token = _generate_jwt(email)
 
 
 
 
 
 
 
 
58
  return {"ok": True, "token": token, "email": email, "owner_key": f"user:{email}"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  return JSONResponse({"error": "Valid email required"}, status_code=400)
56
 
57
  token = _generate_jwt(email)
58
+
59
+ # Part 211: track login in team activity
60
+ try:
61
+ from .. import team_store as _team
62
+ _team.track_login(email)
63
+ except Exception:
64
+ pass
65
+
66
  return {"ok": True, "token": token, "email": email, "owner_key": f"user:{email}"}
67
+
68
+
69
+ @router.post("/api/auth/logout")
70
+ async def auth_logout(req: Request):
71
+ """Part 211: track logout activity (best-effort)."""
72
+ try:
73
+ body = await req.json()
74
+ except Exception:
75
+ body = {}
76
+ email = (body.get("email") or "").strip().lower()
77
+ if email:
78
+ try:
79
+ from .. import team_store as _team
80
+ _team.track_logout(email)
81
+ except Exception:
82
+ pass
83
+ return {"ok": True}
src/sunnyware/routes/authkit.py CHANGED
@@ -31,6 +31,13 @@ async def auth_callback(code: str = ""):
31
 
32
  email = result["email"]
33
 
 
 
 
 
 
 
 
34
  # 1. Ensure SaaS Org exists for this user (free tier default)
35
  from .. import saas_store as s
36
  org = s.get_org_by_email(email)
 
31
 
32
  email = result["email"]
33
 
34
+ # Part 211: track login in team activity
35
+ try:
36
+ from .. import team_store as _team
37
+ _team.track_login(email)
38
+ except Exception:
39
+ pass
40
+
41
  # 1. Ensure SaaS Org exists for this user (free tier default)
42
  from .. import saas_store as s
43
  org = s.get_org_by_email(email)
src/sunnyware/routes/team.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: 2026 Shamiur Rashid Sunny
2
+ # SPDX-License-Identifier: AGPL-3.0-only
3
+ """Part 211: Team management routes."""
4
+
5
+ from fastapi import APIRouter, Request
6
+ from fastapi.responses import JSONResponse
7
+ from .. import team_store as _team
8
+
9
+ router = APIRouter(tags=["team"])
10
+
11
+
12
+ def _admin_only(req: Request):
13
+ from .. import auth as _auth
14
+ key = req.headers.get("x-api-key") or ""
15
+ if not key:
16
+ authz = req.headers.get("authorization") or ""
17
+ if authz.lower().startswith("bearer "):
18
+ key = authz[7:].strip()
19
+ if not _auth.auth_enabled():
20
+ return None
21
+ if not key or not _auth.is_valid_key(key):
22
+ return JSONResponse({"error": "auth_required"}, status_code=401)
23
+ role = _auth.role_for_key(key)
24
+ if not _auth.has_role(role, "admin"):
25
+ return JSONResponse({"error": "forbidden"}, status_code=403)
26
+ return None
27
+
28
+
29
+ @router.get("/api/team/members")
30
+ async def list_members(req: Request):
31
+ d = _admin_only(req)
32
+ if d: return d
33
+ return {"count": len(_team.list_members()), "members": _team.list_members()}
34
+
35
+
36
+ @router.post("/api/team/members")
37
+ async def add_member(req: Request):
38
+ d = _admin_only(req)
39
+ if d: return d
40
+ body = await req.json()
41
+ email = (body.get("email") or "").strip().lower()
42
+ name = (body.get("name") or "").strip()
43
+ role = (body.get("role") or "Viewer").strip()
44
+ if not email or "@" not in email:
45
+ return JSONResponse({"error": "Valid email required"}, status_code=400)
46
+ if _team.get_member_by_email(email):
47
+ return JSONResponse({"error": "Member with this email already exists"}, status_code=400)
48
+ member = _team.add_member(email, name, role, added_by="admin")
49
+ return {"ok": True, "member": member}
50
+
51
+
52
+ @router.patch("/api/team/members/{member_id}")
53
+ async def update_member(member_id: str, req: Request):
54
+ d = _admin_only(req)
55
+ if d: return d
56
+ body = await req.json()
57
+ patch = {}
58
+ if "role" in body: patch["role"] = body["role"]
59
+ if "name" in body: patch["name"] = body["name"]
60
+ if "status" in body: patch["status"] = body["status"]
61
+ updated = _team.update_member(member_id, patch)
62
+ if not updated:
63
+ return JSONResponse({"error": "Member not found"}, status_code=404)
64
+ return {"ok": True, "member": updated}
65
+
66
+
67
+ @router.delete("/api/team/members/{member_id}")
68
+ async def delete_member(member_id: str, req: Request):
69
+ d = _admin_only(req)
70
+ if d: return d
71
+ ok = _team.delete_member(member_id)
72
+ return {"ok": ok}
73
+
74
+
75
+ @router.get("/api/team/activity")
76
+ async def list_activity(req: Request, limit: int = 200, user: str = "", action: str = ""):
77
+ d = _admin_only(req)
78
+ if d: return d
79
+ items = _team.list_activity(limit=limit, user=user, action_filter=action)
80
+ return {"count": len(items), "activity": items}
81
+
82
+
83
+ @router.delete("/api/team/activity")
84
+ async def clear_activity(req: Request):
85
+ d = _admin_only(req)
86
+ if d: return d
87
+ ok = _team.clear_activity()
88
+ return {"ok": ok}
src/sunnyware/team_store.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: 2026 Shamiur Rashid Sunny
2
+ # SPDX-License-Identifier: AGPL-3.0-only
3
+ """Part 211: Team members + activity log store."""
4
+
5
+ import json
6
+ import os
7
+ import secrets
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Optional
11
+
12
+
13
+ def _base() -> Path:
14
+ data = Path("/data")
15
+ if data.exists() and os.access(str(data), os.W_OK):
16
+ return data
17
+ return Path("data")
18
+
19
+
20
+ def _path(name: str) -> Path:
21
+ return _base() / name
22
+
23
+
24
+ def _load(name: str, default: dict) -> dict:
25
+ p = _path(name)
26
+ if not p.exists():
27
+ return dict(default)
28
+ try:
29
+ return json.loads(p.read_text(encoding="utf-8"))
30
+ except Exception:
31
+ return dict(default)
32
+
33
+
34
+ def _save(name: str, data: dict) -> bool:
35
+ p = _path(name)
36
+ try:
37
+ p.parent.mkdir(parents=True, exist_ok=True)
38
+ tmp = p.with_suffix(".tmp")
39
+ tmp.write_text(json.dumps(data, indent=2, sort_keys=True), encoding="utf-8")
40
+ tmp.replace(p)
41
+ return True
42
+ except Exception:
43
+ return False
44
+
45
+
46
+ # ═══════════════════════════════════════════════════════════
47
+ # MEMBERS
48
+ # ═══════════════════════════════════════════════════════════
49
+ def list_members() -> list:
50
+ members = _load("team_members.json", {})
51
+ return sorted(members.values(), key=lambda m: m.get("added_at", 0), reverse=True)
52
+
53
+
54
+ def get_member(member_id: str) -> Optional[dict]:
55
+ return _load("team_members.json", {}).get(member_id)
56
+
57
+
58
+ def get_member_by_email(email: str) -> Optional[dict]:
59
+ email = (email or "").lower().strip()
60
+ if not email:
61
+ return None
62
+ for m in _load("team_members.json", {}).values():
63
+ if (m.get("email") or "").lower() == email:
64
+ return m
65
+ return None
66
+
67
+
68
+ def add_member(email: str, name: str, role: str, added_by: str = "") -> dict:
69
+ members = _load("team_members.json", {})
70
+ mid = "m_" + secrets.token_hex(6)
71
+ member = {
72
+ "id": mid,
73
+ "email": email.lower().strip(),
74
+ "name": name or email.split("@")[0],
75
+ "role": role or "Viewer",
76
+ "status": "active",
77
+ "added_at": time.time(),
78
+ "added_by": added_by,
79
+ "last_login": None,
80
+ "last_logout": None,
81
+ }
82
+ members[mid] = member
83
+ _save("team_members.json", members)
84
+ log_activity(email, "member_added", f"Role: {role}, Added by: {added_by}")
85
+ return member
86
+
87
+
88
+ def update_member(member_id: str, patch: dict) -> Optional[dict]:
89
+ members = _load("team_members.json", {})
90
+ if member_id not in members:
91
+ return None
92
+ old_role = members[member_id].get("role")
93
+ members[member_id].update(patch)
94
+ _save("team_members.json", members)
95
+ if "role" in patch and patch["role"] != old_role:
96
+ log_activity(members[member_id].get("email", ""), "role_changed", f"{old_role} -> {patch['role']}")
97
+ return members[member_id]
98
+
99
+
100
+ def delete_member(member_id: str) -> bool:
101
+ members = _load("team_members.json", {})
102
+ if member_id not in members:
103
+ return False
104
+ email = members[member_id].get("email", "")
105
+ del members[member_id]
106
+ _save("team_members.json", members)
107
+ log_activity(email, "member_deleted", "")
108
+ return True
109
+
110
+
111
+ # ═══════════════════════════════════════════════════════════
112
+ # ACTIVITY
113
+ # ═══════════════════════════════════════════════════════════
114
+ def log_activity(user: str, action: str, details: str = "") -> dict:
115
+ activity = _load("team_activity.json", {})
116
+ aid = "a_" + secrets.token_hex(6)
117
+ entry = {
118
+ "id": aid,
119
+ "user": (user or "system").lower().strip(),
120
+ "action": action,
121
+ "details": details,
122
+ "ts": time.time(),
123
+ }
124
+ activity[aid] = entry
125
+ # Keep last 1000
126
+ if len(activity) > 1000:
127
+ items = sorted(activity.items(), key=lambda kv: kv[1].get("ts", 0))
128
+ for k, _ in items[:-1000]:
129
+ del activity[k]
130
+ _save("team_activity.json", activity)
131
+ return entry
132
+
133
+
134
+ def list_activity(limit: int = 200, user: str = "", action_filter: str = "") -> list:
135
+ activity = _load("team_activity.json", {})
136
+ items = list(activity.values())
137
+ if user:
138
+ items = [i for i in items if (i.get("user") or "").lower() == user.lower()]
139
+ if action_filter:
140
+ items = [i for i in items if i.get("action") == action_filter]
141
+ return sorted(items, key=lambda x: x.get("ts", 0), reverse=True)[:limit]
142
+
143
+
144
+ def clear_activity() -> bool:
145
+ return _save("team_activity.json", {})
146
+
147
+
148
+ # ═════════════════════════════���═════════════════════════════
149
+ # AUTH HOOKS
150
+ # ═══════════════════════════════════════════════════════════
151
+ def track_login(email: str) -> None:
152
+ member = get_member_by_email(email)
153
+ if member:
154
+ update_member(member["id"], {"last_login": time.time()})
155
+ log_activity(email, "login", "")
156
+
157
+
158
+ def track_logout(email: str) -> None:
159
+ member = get_member_by_email(email)
160
+ if member:
161
+ update_member(member["id"], {"last_logout": time.time()})
162
+ log_activity(email, "logout", "")
static/admin-v2.html CHANGED
@@ -1924,49 +1924,162 @@ async function renderHealth() {
1924
 
1925
  // ==== TEAM ====
1926
  async function renderTeam() {
1927
- const audit = await api('/api/acc/audit');
1928
- const roles = {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1929
  Owner: 'Full access to everything',
1930
  Finance: 'Plans, Invoices, Accounting, Budget, Capital, Reports',
1931
  Support: 'Customers, Access, Health, view-only sessions',
1932
  Viewer: 'Read-only: Dashboard, Customers, Plans, Health, Alerts',
1933
  };
 
 
 
 
 
 
 
 
 
 
 
1934
  $('content').innerHTML = `
1935
- <h2>Team Roles</h2>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1936
  <table>
1937
  <thead><tr><th>Role</th><th>Access</th></tr></thead>
1938
  <tbody>
1939
- ${Object.entries(roles).map(([r, desc]) => `
1940
  <tr><td><strong>${esc(r)}</strong></td><td>${esc(desc)}</td></tr>
1941
  `).join('')}
1942
  </tbody>
1943
  </table>
1944
- <h2>Audit Log (${audit.audit.length})</h2>
1945
- ${audit.audit.length === 0 ? '<p style="color:var(--muted)">No audit entries yet.</p>' : `
1946
- <table class="ledger">
1947
- <thead><tr><th>Time</th><th>User</th><th>Action</th></tr></thead>
 
 
1948
  <tbody>
1949
- ${audit.audit.slice().reverse().slice(0, 100).map(a => `
1950
  <tr>
1951
- <td>${esc(a.t)}</td>
1952
- <td>${esc(a.u)}</td>
1953
- <td>${esc(a.a)}</td>
 
1954
  </tr>
1955
  `).join('')}
1956
  </tbody>
1957
  </table>
1958
- `}
1959
- <div class="card" style="margin-top:20px;">
1960
- <h3 style="margin-top:0;color:var(--accent);">Add Audit Entry</h3>
1961
- <div class="form-row">
1962
- <div><label>User</label><input id="audit-user" placeholder="admin"></div>
1963
- <div><label>Action</label><input id="audit-action" placeholder="What was done"></div>
1964
- <button onclick="logAudit()">Log</button>
1965
- </div>
1966
  </div>
 
1967
  `;
1968
  }
1969
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1970
  async function logAudit() {
1971
  const user = $('audit-user').value.trim() || 'admin';
1972
  const action = $('audit-action').value.trim();
 
1924
 
1925
  // ==== TEAM ====
1926
  async function renderTeam() {
1927
+ const [membersData, activityData] = await Promise.all([
1928
+ api('/api/team/members').catch(() => ({ members: [] })),
1929
+ api('/api/team/activity?limit=100').catch(() => ({ activity: [] }))
1930
+ ]);
1931
+ const members = membersData.members || [];
1932
+ const activity = activityData.activity || [];
1933
+
1934
+ const fmtTs = (ts) => {
1935
+ if (!ts) return '—';
1936
+ const d = new Date(ts * 1000);
1937
+ const diffMin = Math.floor((Date.now() - d) / 60000);
1938
+ if (diffMin < 1) return 'Just now';
1939
+ if (diffMin < 60) return diffMin + 'm ago';
1940
+ const diffHr = Math.floor(diffMin / 60);
1941
+ if (diffHr < 24) return diffHr + 'h ago';
1942
+ return d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
1943
+ };
1944
+
1945
+ const roleOptions = ['Owner', 'Finance', 'Support', 'Viewer'];
1946
+ const ROLE_DESC = {
1947
  Owner: 'Full access to everything',
1948
  Finance: 'Plans, Invoices, Accounting, Budget, Capital, Reports',
1949
  Support: 'Customers, Access, Health, view-only sessions',
1950
  Viewer: 'Read-only: Dashboard, Customers, Plans, Health, Alerts',
1951
  };
1952
+
1953
+ const actionBadge = (action) => {
1954
+ const colors = {
1955
+ login: '#2ecc71', logout: '#7c5cff',
1956
+ member_added: '#00d4ff', member_deleted: '#e74c3c',
1957
+ role_changed: '#f39c12',
1958
+ };
1959
+ const c = colors[action] || '#666';
1960
+ return '<span style="display:inline-block;padding:2px 8px;border-radius:99px;font-size:10px;font-weight:600;background:' + c + '22;color:' + c + ';">' + esc(action) + '</span>';
1961
+ };
1962
+
1963
  $('content').innerHTML = `
1964
+ <h2>Team Members (${members.length})</h2>
1965
+ <p style="color:var(--muted);margin-bottom:12px;">Manage who has access to this workspace.</p>
1966
+ ${members.length === 0 ? '<p style="color:var(--muted)">No team members yet. Add the first one below.</p>' : `
1967
+ <table>
1968
+ <thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Status</th><th>Last Login</th><th>Last Logout</th><th></th></tr></thead>
1969
+ <tbody>
1970
+ ${members.map(m => `
1971
+ <tr data-mid="${esc(m.id)}">
1972
+ <td><strong>${esc(m.name || '—')}</strong></td>
1973
+ <td>${esc(m.email)}</td>
1974
+ <td>
1975
+ <select onchange="changeMemberRole('${esc(m.id)}', this.value)" style="width:auto;padding:4px;font-size:12px">
1976
+ ${roleOptions.map(r => '<option value="' + r + '"' + (r === m.role ? ' selected' : '') + '>' + r + '</option>').join('')}
1977
+ </select>
1978
+ </td>
1979
+ <td><span class="tag ${m.status === 'active' ? 'ok' : ''}">${esc(m.status || 'active')}</span></td>
1980
+ <td>${fmtTs(m.last_login)}</td>
1981
+ <td>${fmtTs(m.last_logout)}</td>
1982
+ <td><button class="ghost small" onclick="deleteTeamMember('${esc(m.id)}', '${esc(m.email)}')">Delete</button></td>
1983
+ </tr>
1984
+ `).join('')}
1985
+ </tbody>
1986
+ </table>
1987
+ `}
1988
+
1989
+ <div class="card" style="margin-top:20px;">
1990
+ <h3 style="margin-top:0;color:var(--accent);">Add Team Member</h3>
1991
+ <div class="form-row">
1992
+ <div><label>Name</label><input id="tm-name" placeholder="Jane Doe"></div>
1993
+ <div><label>Email</label><input id="tm-email" type="email" placeholder="jane@company.com"></div>
1994
+ <div><label>Role</label>
1995
+ <select id="tm-role">
1996
+ ${roleOptions.map(r => '<option value="' + r + '"' + (r === 'Viewer' ? ' selected' : '') + '>' + r + '</option>').join('')}
1997
+ </select>
1998
+ </div>
1999
+ <button onclick="addTeamMember()">Add Member</button>
2000
+ </div>
2001
+ </div>
2002
+
2003
+ <h2 style="margin-top:32px;">Role Permissions</h2>
2004
  <table>
2005
  <thead><tr><th>Role</th><th>Access</th></tr></thead>
2006
  <tbody>
2007
+ ${Object.entries(ROLE_DESC).map(([r, desc]) => `
2008
  <tr><td><strong>${esc(r)}</strong></td><td>${esc(desc)}</td></tr>
2009
  `).join('')}
2010
  </tbody>
2011
  </table>
2012
+
2013
+ <h2 style="margin-top:32px;">Activity Log (${activity.length})</h2>
2014
+ <p style="color:var(--muted);margin-bottom:12px;">Logins, logouts, role changes, and member additions.</p>
2015
+ ${activity.length === 0 ? '<p style="color:var(--muted)">No activity yet.</p>' : `
2016
+ <table>
2017
+ <thead><tr><th>Time</th><th>User</th><th>Action</th><th>Details</th></tr></thead>
2018
  <tbody>
2019
+ ${activity.map(a => `
2020
  <tr>
2021
+ <td>${fmtTs(a.ts)}</td>
2022
+ <td>${esc(a.user)}</td>
2023
+ <td>${actionBadge(a.action)}</td>
2024
+ <td style="font-size:12px;color:var(--muted);">${esc(a.details || '')}</td>
2025
  </tr>
2026
  `).join('')}
2027
  </tbody>
2028
  </table>
2029
+ <div style="margin-top:12px;">
2030
+ <button class="ghost small" onclick="clearTeamActivity()">Clear Activity Log</button>
 
 
 
 
 
 
2031
  </div>
2032
+ `}
2033
  `;
2034
  }
2035
 
2036
+ async function addTeamMember() {
2037
+ const name = (document.getElementById('tm-name')?.value || '').trim();
2038
+ const email = (document.getElementById('tm-email')?.value || '').trim();
2039
+ const role = (document.getElementById('tm-role')?.value || 'Viewer').trim();
2040
+ if (!email || !email.includes('@')) return toast('Valid email required', 'error');
2041
+ try {
2042
+ await api('/api/team/members', 'POST', { name, email, role });
2043
+ toast('Member added', 'success');
2044
+ nav('team');
2045
+ } catch(e) {
2046
+ toast('Error: ' + e.message, 'error');
2047
+ }
2048
+ }
2049
+
2050
+ async function deleteTeamMember(memberId, email) {
2051
+ if (!confirm('Remove ' + email + ' from the team?')) return;
2052
+ try {
2053
+ await api('/api/team/members/' + memberId, 'DELETE');
2054
+ toast('Member removed', 'success');
2055
+ nav('team');
2056
+ } catch(e) {
2057
+ toast('Error: ' + e.message, 'error');
2058
+ }
2059
+ }
2060
+
2061
+ async function changeMemberRole(memberId, newRole) {
2062
+ try {
2063
+ await api('/api/team/members/' + memberId, 'PATCH', { role: newRole });
2064
+ toast('Role updated to ' + newRole, 'success');
2065
+ nav('team');
2066
+ } catch(e) {
2067
+ toast('Error: ' + e.message, 'error');
2068
+ nav('team');
2069
+ }
2070
+ }
2071
+
2072
+ async function clearTeamActivity() {
2073
+ if (!confirm('Clear the entire activity log? This cannot be undone.')) return;
2074
+ try {
2075
+ await api('/api/team/activity', 'DELETE');
2076
+ toast('Activity log cleared', 'success');
2077
+ nav('team');
2078
+ } catch(e) {
2079
+ toast('Error: ' + e.message, 'error');
2080
+ }
2081
+ }
2082
+
2083
  async function logAudit() {
2084
  const user = $('audit-user').value.trim() || 'admin';
2085
  const action = $('audit-action').value.trim();