Complete rewrite of all of the hooks and actions for statuses as well as for the Tech Table. Need to rewrite history component & then I will be happy & ready to continue

This commit is contained in:
2025-06-13 04:26:52 -05:00
parent 653fe64bbf
commit c96bdab91b
9 changed files with 718 additions and 928 deletions

View File

@ -1,21 +1,18 @@
'use server'
import 'server-only';
import {
createServerClient,
type Profile,
type Result,
type Status,
} from '@/utils/supabase';
'use server';
import { createServerClient } from '@/utils/supabase';
import type { Profile, Result, Status } from '@/utils/supabase';
import { getUser, getProfile } from '@/lib/hooks'
type UserWithStatus = {
user: Profile;
status: string;
created_at: string;
updated_by: Profile;
updated_by?: Profile;
};
type PaginatedHistory = UserWithStatus[] & {
type PaginatedHistory = {
profile?: Profile;
statuses: Status[];
meta: {
current_page: number;
per_page: number;
@ -24,15 +21,14 @@ type PaginatedHistory = UserWithStatus[] & {
};
};
export const getUsersWithStatuses = async () => {
export const getRecentUsersWithStatuses = async (): Promise<
Result<UserWithStatus[]>
> => {
try {
const supabase = await createServerClient();
const oneDayAgo = new Date(Date.now() - 1000 * 60 * 60 * 24);
// Get only users with recent statuses (Past 7 days)
const oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
const { data: recentStatuses, error } = await supabase
const { data, error } = await supabase
.from('statuses')
.select(`
user:profiles!user_id(*),
@ -40,14 +36,245 @@ export const getUsersWithStatuses = async () => {
created_at,
updated_by:profiles!updated_by_id(*)
`)
.gte('created_at', oneWeekAgo.toISOString())
.order('created_at', { ascending: false });
.gte('created_at', oneDayAgo.toISOString())
.order('created_at', { ascending: false }) as { data: UserWithStatus[], error: unknown };
if (error) throw error;
if (!recentStatuses.length) return { success: true, data: []};
if (error) throw error as Error;
if (!data?.length) return { success: true, data: [] };
return { success: true, data: recentStatuses };
// 3⃣ client-side dedupe: keep the first status you see per user
const seen = new Set<string>();
const filtered = data.filter((row) => {
if (seen.has(row.user.id)) return false;
seen.add(row.user.id);
return true;
});
return { success: true, data: filtered };
} catch (error) {
return { success: false, error: `Error: ${error as string}` };
return { success: false, error: `Error: ${error as Error}` };
}
};
export const broadcastStatusUpdates = async (
userStatuses: UserWithStatus[],
): Promise<Result<void>> => {
try {
const supabase = await createServerClient();
for (const userStatus of userStatuses) {
const broadcast = await supabase.channel('status_updates').send({
type: 'broadcast',
event: 'status_updated',
payload: {
user_status: userStatus,
timestamp: new Date().toISOString(),
}
});
if (broadcast === 'error' || broadcast === 'timed out')
throw new Error('Failed to broadcast status update. Timed out or errored.');
}
return { success: true, data: undefined };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
};
}
};
export const updateStatuses = async (
userIds: string[],
status: string,
): Promise<Result<void>> => {
try {
const supabase = await createServerClient();
const userResponse = await getUser();
if (!userResponse.success) throw new Error('Not authenticated!');
const profileResponse = await getProfile();
if (!profileResponse.success) throw new Error(profileResponse.error);
const user = userResponse.data;
const userProfile = profileResponse.data;
const inserts = userIds.map(usersId => ({
user_id: usersId,
status,
updated_by_id: user.id,
}));
const { data: insertedStatuses, error: insertedStatusesError } = await supabase
.from('statuses')
.insert(inserts)
.select();
if (insertedStatusesError) throw insertedStatusesError as Error;
if (insertedStatuses) {
const broadcastArray = new Array<UserWithStatus>(insertedStatuses.length);
for (const insertedStatus of insertedStatuses) {
const { data: profile, error: profileError } = await supabase
.from('profiles')
.select('*')
.eq('id', insertedStatus.user_id)
.single();
if (profileError) throw profileError as Error;
if (profile) {
broadcastArray.push({
user: profile,
status: insertedStatus.status,
created_at: insertedStatus.created_at,
updated_by: userProfile,
});
}
}
await broadcastStatusUpdates(broadcastArray);
}
return { success: true, data: undefined };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
};
}
};
export const updateUserStatus = async (status: string): Promise<Result<void>> => {
try {
const supabase = await createServerClient();
const userResponse = await getUser();
if (!userResponse.success) throw new Error(`Not authenticated! ${userResponse.error}`);
const profileResponse = await getProfile();
if (!profileResponse.success) throw new Error(`Could not get profile! ${profileResponse.error}`);
const user = userResponse.data;
const userProfile = profileResponse.data;
const { data: insertedStatus, error: insertedStatusError } = await supabase
.from('statuses')
.insert({
user_id: user.id,
status,
updated_by_id: user.id,
})
.select()
.single();
if (insertedStatusError) throw insertedStatusError as Error;
const userStatus: UserWithStatus = {
user: userProfile,
status: insertedStatus.status,
created_at: insertedStatus.created_at,
};
await broadcastStatusUpdates([userStatus]);
return { success: true, data: undefined };
} catch (error) {
return {
success: false,
error: `Error updating user's status: ${error as Error}`,
}
}
};
export const getUserHistory = async (
userId: string,
page = 1,
perPage = 50,
): Promise<Result<PaginatedHistory>> => {
try {
const supabase = await createServerClient();
const userResponse = await getUser();
if (!userResponse.success) throw new Error(`Not authenticated! ${userResponse.error}`);
const offset = (page - 1) * perPage;
const { count } = await supabase
.from('statuses')
.select('*', { count: 'exact', head: true })
.eq('user_id', userId);
const { data: statuses, error: statusesError } = await supabase
.from('statuses')
.select('*')
.eq('user_id', userId)
.order('created_at', { ascending: false })
.range(offset, offset + perPage - 1) as {data: Status[], error: unknown};
if (statusesError) throw statusesError as Error;
const { data: profile, error: profileError } = await supabase
.from('profiles')
.select('*')
.eq('id', userId)
.single() as { data: Profile, error: unknown };
if (profileError) throw profileError as Error;
if (!profile) throw new Error('User profile not found!');
const totalCount = count ?? 0;
const totalPages = Math.ceil(totalCount / perPage);
return {
success: true,
data: {
profile,
statuses,
meta: {
current_page: page,
per_page: perPage,
total_pages: totalPages,
total_count: totalCount,
},
},
};
} catch (error) {
return {
success: false,
error: `Error getting user's history: ${error as Error}`,
};
}
};
export const getAllHistory = async (
page = 1,
perPage = 50,
): Promise<Result<PaginatedHistory>> => {
try {
const supabase = await createServerClient();
const userResponse = await getUser();
if (!userResponse.success) throw new Error(`Not authenticated! ${userResponse.error}`);
const offset = (page - 1) * perPage;
const { count } = await supabase
.from('statuses')
.select('*', { count: 'exact', head: true });
const { data: statuses, error: statusesError } = await supabase
.from('statuses')
.select('*')
.order('created_at', { ascending: false })
.range(offset, offset + perPage - 1) as {data: Status[], error: unknown};
if (statusesError) throw statusesError as Error;
const totalCount = count ?? 0;
const totalPages = Math.ceil(totalCount / perPage);
return {
success: true,
data: {
statuses,
meta: {
current_page: page,
per_page: perPage,
total_pages: totalPages,
total_count: totalCount,
},
},
};
} catch (error) {
return {
success: false,
error: `Error getting all history: ${error as Error}`,
};
}
};