11import { db } from '@sim/db'
22import { gmailMailbox , user } from '@sim/db/schema'
33import { createLogger } from '@sim/logger'
4- import { and , eq , ne , sql } from 'drizzle-orm'
4+ import { and , eq , lt , or , sql } from 'drizzle-orm'
55import { isBillingEnabled } from '@/lib/core/config/env-flags'
66import type { DbOrTx } from '@/lib/db/types'
77
@@ -18,12 +18,14 @@ import type { DbOrTx } from '@/lib/db/types'
1818const logger = createLogger ( 'GmailAlias' )
1919
2020/**
21- * Whether another account, banned or not, already holds the Gmail inbox this
22- * user's address delivers to. Pass the caller's transaction as `executor` to
23- * read on it; the read then runs in a savepoint, so a failed lookup never
24- * aborts that transaction. Fails open: a lookup error returns `false` and is
25- * logged, because refusing a legitimate person's allowance is worse than one
26- * missed match.
21+ * Whether an earlier account, banned or not, already holds the Gmail inbox this
22+ * user's address delivers to. Only an account created before this one counts
23+ * (the id breaks a creation-time tie), so the inbox's first account keeps the
24+ * allowance however late its own stats row is created. Pass the caller's
25+ * transaction as `executor` to read on it; the read then runs in a savepoint,
26+ * so a failed lookup never aborts that transaction. Fails open: a lookup error
27+ * returns `false` and is logged, because refusing a legitimate person's
28+ * allowance is worse than one missed match.
2729 */
2830export async function userHasGmailAliasAccount (
2931 userId : string ,
@@ -32,15 +34,23 @@ export async function userHasGmailAliasAccount(
3234 if ( ! isBillingEnabled ) return false
3335 const read = async ( reader : DbOrTx ) => {
3436 const [ self ] = await reader
35- . select ( { mailbox : gmailMailbox ( user . email ) } )
37+ . select ( { mailbox : gmailMailbox ( user . email ) , createdAt : user . createdAt } )
3638 . from ( user )
3739 . where ( eq ( user . id , userId ) )
3840 . limit ( 1 )
3941 if ( ! self ?. mailbox ) return false
4042 const [ other ] = await reader
4143 . select ( { id : user . id } )
4244 . from ( user )
43- . where ( and ( sql `${ gmailMailbox ( user . email ) } = ${ self . mailbox } ` , ne ( user . id , userId ) ) )
45+ . where (
46+ and (
47+ sql `${ gmailMailbox ( user . email ) } = ${ self . mailbox } ` ,
48+ or (
49+ lt ( user . createdAt , self . createdAt ) ,
50+ and ( eq ( user . createdAt , self . createdAt ) , lt ( user . id , userId ) )
51+ )
52+ )
53+ )
4454 . limit ( 1 )
4555 return Boolean ( other )
4656 }
0 commit comments