@@ -309,6 +309,9 @@ impl GlobalDB {
309309
310310 /// Batch add members by email. Returns count of newly added members.
311311 ///
312+ /// If an email matches an existing global user, the member is linked to
313+ /// that user immediately so they gain access without needing to re-auth.
314+ ///
312315 /// # Errors
313316 /// Returns an error on database failure.
314317 pub async fn batch_add_members (
@@ -324,17 +327,47 @@ impl GlobalDB {
324327 continue ;
325328 }
326329
327- // Check if this email matches an existing global user
328- // (we don't have email in global_user, so just store the email for now)
329- let result = sqlx:: query (
330- r"INSERT INTO cohort_member (cohort_id, email, initial_balance) VALUES (?, ?, ?) ON CONFLICT DO NOTHING" ,
330+ let global_user_id = sqlx:: query_scalar :: < _ , i64 > (
331+ r"SELECT id FROM global_user WHERE email = ?" ,
331332 )
332- . bind ( cohort_id)
333333 . bind ( & email)
334- . bind ( initial_balance)
335- . execute ( & self . pool )
334+ . fetch_optional ( & self . pool )
336335 . await ?;
337336
337+ let result = if let Some ( gid) = global_user_id {
338+ // Promote any pre-authorized pending row to point at the user.
339+ let linked = sqlx:: query (
340+ r"UPDATE cohort_member SET global_user_id = ? WHERE cohort_id = ? AND email = ? AND global_user_id IS NULL" ,
341+ )
342+ . bind ( gid)
343+ . bind ( cohort_id)
344+ . bind ( & email)
345+ . execute ( & self . pool )
346+ . await ?;
347+
348+ if linked. rows_affected ( ) > 0 {
349+ linked
350+ } else {
351+ sqlx:: query (
352+ r"INSERT INTO cohort_member (cohort_id, global_user_id, initial_balance) VALUES (?, ?, ?) ON CONFLICT DO NOTHING" ,
353+ )
354+ . bind ( cohort_id)
355+ . bind ( gid)
356+ . bind ( initial_balance)
357+ . execute ( & self . pool )
358+ . await ?
359+ }
360+ } else {
361+ sqlx:: query (
362+ r"INSERT INTO cohort_member (cohort_id, email, initial_balance) VALUES (?, ?, ?) ON CONFLICT DO NOTHING" ,
363+ )
364+ . bind ( cohort_id)
365+ . bind ( & email)
366+ . bind ( initial_balance)
367+ . execute ( & self . pool )
368+ . await ?
369+ } ;
370+
338371 if result. rows_affected ( ) > 0 {
339372 added += 1 ;
340373 }
0 commit comments