Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
474 changes: 460 additions & 14 deletions app/(app)/dashboard/org-controls.tsx

Large diffs are not rendered by default.

59 changes: 57 additions & 2 deletions app/(app)/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {
OrgDashboardControls,
ProjectOrgMoveControl,
type DashboardSenderConfig,
type DashboardDataSource,
type DashboardAudienceStats,
type DashboardOrg,
type DashboardOrgTeam,
} from "./org-controls";
Expand Down Expand Up @@ -92,7 +94,16 @@ export default async function DashboardPage({
? projectsQuery.eq("organization_id", selectedOrgId).or(accessFilter)
: projectsQuery.or(accessFilter);

const [{ data: projectsRaw }, { data: audits }, counts, senderConfigs, orgTeam] = await Promise.all([
const ownerOrgId = selectedOrg?.role === "owner" ? selectedOrgId : null;
const [
{ data: projectsRaw },
{ data: audits },
counts,
senderConfigs,
dataSources,
audienceStats,
orgTeam,
] = await Promise.all([
scopedProjectsQuery,
supabase
.from("audits")
Expand All @@ -101,7 +112,9 @@ export default async function DashboardPage({
.order("created_at", { ascending: false })
.limit(10),
countByStatus(supabase, user!.id, accessFilter, selectedOrgId),
fetchSenderConfigs(supabase, selectedOrg?.role === "owner" ? selectedOrgId : null),
fetchSenderConfigs(supabase, ownerOrgId),
fetchDataSources(supabase, ownerOrgId),
fetchAudienceStats(supabase, ownerOrgId),
fetchOrgTeam(selectedOrg && isOrgWideRole(selectedOrg.role) ? selectedOrgId : null),
]);
const projects = ((projectsRaw ?? []) as unknown) as DashboardProject[];
Expand Down Expand Up @@ -141,6 +154,8 @@ export default async function DashboardPage({
orgs={orgs as DashboardOrg[]}
selectedOrgId={selectedOrgId}
senderConfigs={senderConfigs}
dataSources={dataSources}
audienceStats={audienceStats}
orgTeam={orgTeam}
/>
)}
Expand Down Expand Up @@ -519,3 +534,43 @@ async function fetchSenderConfigs(
}
return ((data ?? []) as unknown) as DashboardSenderConfig[];
}

async function fetchDataSources(
supabase: Awaited<ReturnType<typeof createClient>>,
organizationId: string | null,
): Promise<DashboardDataSource[]> {
if (!organizationId) return [];
const { data, error } = await supabase
.from("organization_data_sources")
.select("id,label,kind,enabled,last_synced_at,last_sync_count,last_sync_error")
.eq("organization_id", organizationId)
.order("created_at", { ascending: false });
if (error) {
if (missingOrgSchema(error)) return [];
throw error;
}
return ((data ?? []) as unknown) as DashboardDataSource[];
}

async function fetchAudienceStats(
supabase: Awaited<ReturnType<typeof createClient>>,
organizationId: string | null,
): Promise<DashboardAudienceStats> {
if (!organizationId) return { total: 0, unsubscribed: 0 };
const [{ count: total, error: totalErr }, { count: unsub, error: unsubErr }] =
await Promise.all([
supabase
.from("organization_audience_contacts")
.select("id", { count: "exact", head: true })
.eq("organization_id", organizationId),
supabase
.from("organization_audience_contacts")
.select("id", { count: "exact", head: true })
.eq("organization_id", organizationId)
.not("unsubscribed_at", "is", null),
]);
if (totalErr || unsubErr) {
if (missingOrgSchema(totalErr ?? unsubErr)) return { total: 0, unsubscribed: 0 };
}
return { total: total ?? 0, unsubscribed: unsub ?? 0 };
}
42 changes: 37 additions & 5 deletions app/actions/org-members.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,20 @@ async function requireOrgOwner(orgId: string) {
return { ok: true as const, user, org, supabase, svc };
}

export type OrgInviteRole = "member" | "viewer";

export async function inviteOrgMember(
orgId: string,
email: string,
role: OrgInviteRole = "member",
): Promise<{ ok: boolean; error?: string }> {
const normalized = email.trim().toLowerCase();
if (!normalized.includes("@")) {
return { ok: false, error: "Invalid email address." };
}
if (role !== "member" && role !== "viewer") {
return { ok: false, error: "Invalid role." };
}

const ctx = await requireOrgOwner(orgId);
if (!ctx.ok) return { ok: false, error: ctx.error };
Expand Down Expand Up @@ -73,7 +79,7 @@ export async function inviteOrgMember(
if ((existingMember as { role: OrgRole }).role === "project_member") {
const { error } = await svc
.from("organization_members")
.update({ role: "member" })
.update({ role })
.eq("id", (existingMember as { id: string }).id);
if (error) return { ok: false, error: error.message };
revalidatePath("/dashboard");
Expand All @@ -92,7 +98,7 @@ export async function inviteOrgMember(

const { data: invitation, error: insertErr } = await svc
.from("organization_invitations")
.insert({ organization_id: orgId, email: normalized, invited_by: user.id })
.insert({ organization_id: orgId, email: normalized, invited_by: user.id, role })
.select("token")
.single();

Expand Down Expand Up @@ -169,13 +175,13 @@ export async function removeOrgMember(
.update({ role: "project_member" })
.eq("organization_id", orgId)
.eq("user_id", userId)
.eq("role", "member")
.in("role", ["member", "viewer"])
: await ctx.svc
.from("organization_members")
.delete()
.eq("organization_id", orgId)
.eq("user_id", userId)
.eq("role", "member");
.in("role", ["member", "viewer"]);

if (error) return { ok: false, error: error.message };

Expand All @@ -191,6 +197,31 @@ export async function removeOrgMember(
return { ok: true };
}

// Change an existing org member between full member and read-only viewer.
// Owner-only. Never touches 'owner' or 'project_member' rows.
export async function setOrgMemberRole(
orgId: string,
userId: string,
role: OrgInviteRole,
): Promise<{ ok: boolean; error?: string }> {
if (role !== "member" && role !== "viewer") {
return { ok: false, error: "Invalid role." };
}
const ctx = await requireOrgOwner(orgId);
if (!ctx.ok) return { ok: false, error: ctx.error };

const { error } = await ctx.svc
.from("organization_members")
.update({ role })
.eq("organization_id", orgId)
.eq("user_id", userId)
.in("role", ["member", "viewer"]);
if (error) return { ok: false, error: error.message };

revalidatePath("/dashboard");
return { ok: true };
}

export type OrgTeamMember = {
id: string;
user_id: string;
Expand All @@ -202,6 +233,7 @@ export type OrgTeamMember = {
export type OrgPendingInvitation = {
id: string;
email: string;
role: OrgInviteRole;
expires_at: string;
created_at: string;
};
Expand Down Expand Up @@ -264,7 +296,7 @@ export async function listOrgTeam(orgId: string): Promise<
const { data: invitationsRaw } = isOwner
? await svc
.from("organization_invitations")
.select("id, email, expires_at, created_at")
.select("id, email, role, expires_at, created_at")
.eq("organization_id", orgId)
.is("accepted_at", null)
.order("created_at", { ascending: false })
Expand Down
Loading
Loading