@@ -22,10 +22,39 @@ export async function createProject(project: Omit<Project, 'id' | 'created_at' |
2222export async function getProjects ( userId : string ) {
2323 guard ( )
2424 const supabase = createClient ( )
25- const { data, error } = await supabase
25+ const { data : ownedProjects , error : ownedError } = await supabase
2626 . from ( 'projects' ) . select ( '*' ) . eq ( 'user_id' , userId ) . order ( 'created_at' , { ascending : false } )
27- if ( error ) throw error
28- return data || [ ]
27+
28+ if ( ownedError ) throw ownedError
29+
30+ const { data : collaboratorRows , error : collaboratorError } = await supabase
31+ . from ( 'project_collaborators' )
32+ . select ( 'project_id' )
33+ . eq ( 'user_id' , userId )
34+
35+ if ( collaboratorError ) throw collaboratorError
36+
37+ const ownedIds = new Set ( ( ownedProjects || [ ] ) . map ( ( project ) => project . id ) )
38+ const collaboratorProjectIds = Array . from (
39+ new Set ( ( collaboratorRows || [ ] ) . map ( ( row ) => row . project_id ) . filter ( Boolean ) )
40+ ) . filter ( ( projectId ) => ! ownedIds . has ( projectId ) )
41+
42+ if ( collaboratorProjectIds . length === 0 ) {
43+ return ownedProjects || [ ]
44+ }
45+
46+ const { data : collaboratorProjects , error : collaboratorProjectsError } = await supabase
47+ . from ( 'projects' )
48+ . select ( '*' )
49+ . in ( 'id' , collaboratorProjectIds )
50+
51+ if ( collaboratorProjectsError ) throw collaboratorProjectsError
52+
53+ return [ ...( ownedProjects || [ ] ) , ...( collaboratorProjects || [ ] ) ] . sort ( ( a , b ) => {
54+ const aTime = new Date ( a . updated_at || a . created_at || 0 ) . getTime ( )
55+ const bTime = new Date ( b . updated_at || b . created_at || 0 ) . getTime ( )
56+ return bTime - aTime
57+ } )
2958}
3059
3160export async function updateProject ( id : string , updates : Partial < Project > ) {
@@ -91,12 +120,16 @@ export async function searchUsers(query: string) {
91120}
92121
93122export async function getProfileByEmail ( email : string ) {
123+ guard ( )
124+ const normalizedEmail = email . trim ( ) . toLowerCase ( )
125+ if ( ! normalizedEmail ) return null
126+
94127 const supabase = createClient ( )
95128 const { data, error } = await supabase
96129 . from ( 'profiles' )
97130 . select ( '*' )
98- . eq ( 'email' , email )
99- . single ( )
131+ . ilike ( 'email' , normalizedEmail )
132+ . maybeSingle ( )
100133 if ( error && error . code !== 'PGRST116' ) throw error
101134 return data || null
102135}
0 commit comments