Coverage for api/invite_requests.py: 63.25%

188 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 20:17 +0000

1""" 

2Invite Request API endpoints for Missing Table 

3 

4Handles public invite request submissions and admin management. 

5""" 

6 

7import os 

8import sys 

9from datetime import datetime 

10 

11import structlog 

12from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request 

13from pydantic import BaseModel, EmailStr, Field 

14 

15from supabase import create_client 

16 

17logger = structlog.get_logger(__name__) 

18 

19sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 

20 

21from auth import get_current_user_required 

22from dao.match_dao import SupabaseConnection as DbConnectionHolder 

23from notifications.invite_request_alerts import notify_new_invite_request 

24from rate_limiter import RATE_LIMITS, rate_limit 

25from services.email_service import EmailService 

26 

27# Initialize database connection with service role for admin operations 

28supabase_url = os.getenv("SUPABASE_URL", "") 

29service_key = os.getenv("SUPABASE_SERVICE_KEY") 

30 

31# Create service role client for operations that bypass RLS 

32if service_key: 32 ↛ 36line 32 didn't jump to line 36 because the condition on line 32 was always true

33 service_client = create_client(supabase_url, service_key) 

34else: 

35 # Fallback to regular connection if service key not available 

36 db_conn_holder_obj = DbConnectionHolder() 

37 service_client = db_conn_holder_obj.client 

38 

39router = APIRouter(prefix="/api/invite-requests", tags=["invite-requests"]) 

40 

41# Embedded through invite_requests.invitation_id (SB-1312) 

42LINKED_INVITATION_COLUMNS = "id, invite_code, invite_type, status, testflight_status, testflight_error" 

43 

44 

45# Pydantic models 

46class InviteRequestCreate(BaseModel): 

47 """Model for creating a new invite request""" 

48 

49 email: EmailStr = Field(..., description="Email address of the requester") 

50 name: str = Field(..., min_length=1, max_length=255, description="Name of the requester") 

51 team: str | None = Field(None, max_length=255, description="Team or club affiliation") 

52 reason: str | None = Field(None, description="Reason for wanting to join") 

53 wants_ios_beta: bool = Field(False, description="Requester wants the iPhone beta") 

54 website: str | None = Field(None, description="Honeypot field - should be empty") 

55 

56 

57class LinkedInvitation(BaseModel): 

58 """The invitation an admin created from a request (SB-1312)""" 

59 

60 id: str 

61 invite_code: str 

62 invite_type: str 

63 status: str 

64 testflight_status: str | None = None 

65 testflight_error: str | None = None 

66 

67 

68class InviteRequestResponse(BaseModel): 

69 """Model for invite request response""" 

70 

71 id: str 

72 email: str 

73 name: str 

74 team: str | None 

75 reason: str | None 

76 wants_ios_beta: bool = False 

77 status: str 

78 created_at: datetime 

79 updated_at: datetime 

80 reviewed_by: str | None 

81 reviewed_at: datetime | None 

82 admin_notes: str | None 

83 invitation_id: str | None = None 

84 invitation: LinkedInvitation | None = None 

85 

86 

87class InviteRequestStatusUpdate(BaseModel): 

88 """Model for updating invite request status. 

89 

90 No "approved": a request is approved only by creating its invitation 

91 (SB-1392), so an approved request always has one. 

92 """ 

93 

94 status: str = Field(..., pattern="^(pending|rejected|existing_user)$") 

95 admin_notes: str | None = Field(None, description="Admin notes about the decision") 

96 

97 

98class TestRejectionEmail(BaseModel): 

99 """Request body for sending a test rejection email to an arbitrary address.""" 

100 

101 to_email: EmailStr = Field(..., description="Recipient address") 

102 name: str = Field("Test User", min_length=1, max_length=255) 

103 

104 

105class InviteRequestStats(BaseModel): 

106 """Statistics about invite requests""" 

107 

108 total: int 

109 pending: int 

110 approved: int 

111 rejected: int 

112 existing_user: int = 0 

113 

114 

115# Public endpoint - no auth required 

116@router.post("", status_code=201) 

117@rate_limit(RATE_LIMITS["invite_request"]) 

118async def create_invite_request(request: Request, payload: InviteRequestCreate, background_tasks: BackgroundTasks): 

119 """ 

120 Submit a new invite request (public endpoint). 

121 

122 Anyone can submit an invite request without authentication. 

123 Duplicate email submissions are allowed (users can re-submit). 

124 """ 

125 try: 

126 # Honeypot check - if filled, it's a bot 

127 if payload.website: 

128 # Return fake success to not alert the bot 

129 return { 

130 "success": True, 

131 "message": "Thank you for your interest! We'll review your request and reach out soon.", 

132 } 

133 

134 # Check for existing pending request with same email 

135 existing = ( 

136 service_client.table("invite_requests") 

137 .select("id, status") 

138 .eq("email", payload.email) 

139 .eq("status", "pending") 

140 .execute() 

141 ) 

142 

143 if existing.data: 

144 # Return success anyway - we don't want to reveal if email exists 

145 return { 

146 "success": True, 

147 "message": "Thank you for your interest! We'll review your request and reach out soon.", 

148 } 

149 

150 # Insert new invite request 

151 result = ( 

152 service_client.table("invite_requests") 

153 .insert( 

154 { 

155 "email": payload.email, 

156 "name": payload.name, 

157 "team": payload.team, 

158 "reason": payload.reason, 

159 "wants_ios_beta": payload.wants_ios_beta, 

160 "status": "pending", 

161 } 

162 ) 

163 .execute() 

164 ) 

165 

166 if result.data: 166 ↛ 179line 166 didn't jump to line 179 because the condition on line 166 was always true

167 # Ping admins after the response is sent; never fails the request. 

168 background_tasks.add_task( 

169 notify_new_invite_request, 

170 payload.name, 

171 payload.team, 

172 payload.wants_ios_beta, 

173 ) 

174 return { 

175 "success": True, 

176 "message": "Thank you for your interest! We'll review your request and reach out soon.", 

177 } 

178 else: 

179 raise HTTPException(status_code=500, detail="Failed to submit invite request") 

180 

181 except HTTPException: 

182 raise 

183 except Exception: 

184 logger.exception("Error creating invite request") 

185 raise HTTPException(status_code=500, detail="An error occurred while submitting your request") from None 

186 

187 

188# Admin endpoints 

189@router.get("", response_model=list[InviteRequestResponse]) 

190async def list_invite_requests( 

191 current_user=Depends(get_current_user_required), 

192 status: str | None = Query(None, pattern="^(pending|approved|rejected|existing_user)$"), 

193 ios_beta: bool | None = Query(None, description="Filter by the iPhone-beta opt-in"), 

194 limit: int = Query(50, ge=1, le=100), 

195 offset: int = Query(0, ge=0), 

196): 

197 """ 

198 List all invite requests (admin only). 

199 

200 Supports filtering by status, iPhone-beta opt-in, and pagination. 

201 """ 

202 if current_user.get("role") not in ["admin", "club_manager"]: 202 ↛ 203line 202 didn't jump to line 203 because the condition on line 202 was never true

203 raise HTTPException(status_code=403, detail="Only admins can view invite requests") 

204 

205 try: 

206 query = ( 

207 service_client.table("invite_requests") 

208 .select(f"*, invitation:invitations({LINKED_INVITATION_COLUMNS})") 

209 .order("created_at", desc=True) 

210 .range(offset, offset + limit - 1) 

211 ) 

212 

213 if status: 213 ↛ 214line 213 didn't jump to line 214 because the condition on line 213 was never true

214 query = query.eq("status", status) 

215 

216 if ios_beta is not None: 216 ↛ 217line 216 didn't jump to line 217 because the condition on line 216 was never true

217 query = query.eq("wants_ios_beta", ios_beta) 

218 

219 result = query.execute() 

220 

221 return result.data or [] 

222 

223 except Exception: 

224 logger.exception("Error listing invite requests") 

225 raise HTTPException(status_code=500, detail="Failed to retrieve invite requests") from None 

226 

227 

228@router.get("/stats", response_model=InviteRequestStats) 

229async def get_invite_request_stats(current_user=Depends(get_current_user_required)): 

230 """ 

231 Get statistics about invite requests (admin only). 

232 """ 

233 if current_user.get("role") not in ["admin", "club_manager"]: 

234 raise HTTPException(status_code=403, detail="Only admins can view invite request stats") 

235 

236 try: 

237 # Get counts by status 

238 all_requests = service_client.table("invite_requests").select("status").execute() 

239 

240 stats = {"total": 0, "pending": 0, "approved": 0, "rejected": 0, "existing_user": 0} 

241 

242 if all_requests.data: 

243 stats["total"] = len(all_requests.data) 

244 for req in all_requests.data: 

245 status = req.get("status", "pending") 

246 if status in stats: 

247 stats[status] += 1 

248 

249 return stats 

250 

251 except Exception: 

252 logger.exception("Error getting invite request stats") 

253 raise HTTPException(status_code=500, detail="Failed to retrieve statistics") from None 

254 

255 

256@router.get("/{request_id}", response_model=InviteRequestResponse) 

257async def get_invite_request(request_id: str, current_user=Depends(get_current_user_required)): 

258 """ 

259 Get a specific invite request by ID (admin only). 

260 """ 

261 if current_user.get("role") not in ["admin", "club_manager"]: 

262 raise HTTPException(status_code=403, detail="Only admins can view invite requests") 

263 

264 try: 

265 result = service_client.table("invite_requests").select("*").eq("id", request_id).execute() 

266 

267 if not result.data: 

268 raise HTTPException(status_code=404, detail="Invite request not found") 

269 

270 return result.data[0] 

271 

272 except HTTPException: 

273 raise 

274 except Exception: 

275 logger.exception("Error getting invite request") 

276 raise HTTPException(status_code=500, detail="Failed to retrieve invite request") from None 

277 

278 

279@router.post("/test-rejection-email") 

280async def send_test_rejection_email( 

281 payload: TestRejectionEmail, 

282 current_user=Depends(get_current_user_required), 

283): 

284 """ 

285 Send the rejection email to an arbitrary address so admins can preview 

286 the template before a real Reject (SB-1407), without a throwaway 

287 invite_requests row. 

288 

289 Admin only. 

290 """ 

291 if current_user.get("role") not in ["admin", "club_manager"]: 

292 raise HTTPException(status_code=403, detail="Only admins can send test emails") 

293 

294 try: 

295 email_service = EmailService() 

296 except Exception: 

297 logger.exception("EmailService init failed for test-rejection-email") 

298 raise HTTPException(status_code=503, detail="Email service is unavailable") from None 

299 

300 sent = email_service.send_invite_request_rejection(to_email=payload.to_email, name=payload.name) 

301 if not sent: 

302 raise HTTPException(status_code=502, detail="Email send failed") 

303 

304 return {"success": True, "message": f"Test rejection email sent to {payload.to_email}"} 

305 

306 

307@router.put("/{request_id}/status") 

308async def update_invite_request_status( 

309 request_id: str, 

310 status_update: InviteRequestStatusUpdate, 

311 current_user=Depends(get_current_user_required), 

312): 

313 """ 

314 Reject an invite request, close it as from an existing user, or reset 

315 one to pending (admin only). Only a rejection emails the requester; 

316 existing_user closes it silently (SB-1408). 

317 

318 Approving is done by creating the invitation from the request 

319 (POST /api/invites/admin/... with invite_request_id), never here. 

320 """ 

321 if current_user.get("role") not in ["admin", "club_manager"]: 321 ↛ 322line 321 didn't jump to line 322 because the condition on line 321 was never true

322 raise HTTPException(status_code=403, detail="Only admins can update invite requests") 

323 

324 try: 

325 # Get current request 

326 existing = service_client.table("invite_requests").select("*").eq("id", request_id).execute() 

327 

328 if not existing.data: 328 ↛ 329line 328 didn't jump to line 329 because the condition on line 328 was never true

329 raise HTTPException(status_code=404, detail="Invite request not found") 

330 

331 previous = existing.data[0] 

332 # A linked request's invitation exists; resetting would strand it and 

333 # the request could never be linked again (SB-1392). 

334 if previous.get("invitation_id"): 

335 raise HTTPException( 

336 status_code=409, detail="Invite request already has an invitation; cancel the invitation instead" 

337 ) 

338 

339 # Get user ID 

340 user_id = current_user.get("id") or current_user.get("user_id") or current_user.get("sub") 

341 

342 # Update the request 

343 update_data = { 

344 "status": status_update.status, 

345 "reviewed_by": user_id, 

346 "reviewed_at": datetime.utcnow().isoformat(), 

347 } 

348 

349 if status_update.admin_notes: 349 ↛ 350line 349 didn't jump to line 350 because the condition on line 349 was never true

350 update_data["admin_notes"] = status_update.admin_notes 

351 

352 result = service_client.table("invite_requests").update(update_data).eq("id", request_id).execute() 

353 

354 if not result.data: 354 ↛ 355line 354 didn't jump to line 355 because the condition on line 354 was never true

355 raise HTTPException(status_code=500, detail="Failed to update invite request") 

356 

357 updated_request = result.data[0] 

358 

359 # On rejection, tell the requester (SB-1392) - once, not again when 

360 # an already-rejected request is rejected. Email failures are logged 

361 # but never fail the API call. 

362 email_sent = False 

363 if status_update.status == "rejected" and previous.get("status") != "rejected": 

364 try: 

365 email_service = EmailService() 

366 email_sent = email_service.send_invite_request_rejection( 

367 to_email=updated_request["email"], 

368 name=updated_request["name"], 

369 ) 

370 except Exception: 

371 logger.exception( 

372 "Failed to send invite-request rejection email", 

373 extra={"request_id": request_id}, 

374 ) 

375 

376 return { 

377 "success": True, 

378 "message": f"Invite request {status_update.status}", 

379 "request": updated_request, 

380 "email_sent": email_sent, 

381 } 

382 

383 except HTTPException: 

384 raise 

385 except Exception: 

386 logger.exception("Error updating invite request") 

387 raise HTTPException(status_code=500, detail="Failed to update invite request") from None 

388 

389 

390@router.delete("/{request_id}") 

391async def delete_invite_request(request_id: str, current_user=Depends(get_current_user_required)): 

392 """ 

393 Delete an invite request (admin only). 

394 

395 Use with caution - this permanently removes the request. 

396 """ 

397 if current_user.get("role") not in ["admin", "club_manager"]: 

398 raise HTTPException(status_code=403, detail="Only admins can delete invite requests") 

399 

400 try: 

401 # Check if request exists 

402 existing = service_client.table("invite_requests").select("id").eq("id", request_id).execute() 

403 

404 if not existing.data: 

405 raise HTTPException(status_code=404, detail="Invite request not found") 

406 

407 # Delete the request 

408 service_client.table("invite_requests").delete().eq("id", request_id).execute() 

409 

410 return {"success": True, "message": "Invite request deleted successfully"} 

411 

412 except HTTPException: 

413 raise 

414 except Exception: 

415 logger.exception("Error deleting invite request") 

416 raise HTTPException(status_code=500, detail="Failed to delete invite request") from None