forked from fahrPool/fahrPool
40 lines
1.8 KiB
TypeScript
40 lines
1.8 KiB
TypeScript
import type { SupabaseClient } from "@supabase/supabase-js";
|
|
import { zaehleRollen, type RollenAnzahl } from "./rollen";
|
|
|
|
export type FirmaUebersicht = { id: string; name: string; aktiv: boolean; rollen: RollenAnzahl };
|
|
export type FirmenAdmin = { id: string; name: string; username: string; email: string | null };
|
|
|
|
type FirmaZeile = { id: string; name: string; aktiv: boolean; profiles: { role: string | null }[] | null };
|
|
|
|
function zuUebersicht(f: FirmaZeile): FirmaUebersicht {
|
|
return { id: f.id, name: f.name, aktiv: f.aktiv, rollen: zaehleRollen(f.profiles) };
|
|
}
|
|
|
|
// Nur mit dem Service-Client aufrufen.
|
|
export async function listFirmen(admin: SupabaseClient): Promise<FirmaUebersicht[]> {
|
|
const { data, error } = await admin.from("firmen").select("id, name, aktiv, profiles(role)").order("name");
|
|
if (error) throw new Error(`Firmen laden fehlgeschlagen: ${error.message}`);
|
|
return ((data ?? []) as FirmaZeile[]).map(zuUebersicht);
|
|
}
|
|
|
|
export async function ladeFirmaFuerPlattform(admin: SupabaseClient, firmaId: string): Promise<FirmaUebersicht | null> {
|
|
const { data } = await admin.from("firmen").select("id, name, aktiv, profiles(role)").eq("id", firmaId).maybeSingle();
|
|
return data ? zuUebersicht(data as FirmaZeile) : null;
|
|
}
|
|
|
|
export async function listFirmenAdmins(admin: SupabaseClient, firmaId: string): Promise<FirmenAdmin[]> {
|
|
const { data, error } = await admin
|
|
.from("profiles")
|
|
.select("id, name, username")
|
|
.eq("firma_id", firmaId)
|
|
.eq("role", "admin")
|
|
.order("name");
|
|
if (error) throw new Error(`Admins laden fehlgeschlagen: ${error.message}`);
|
|
return Promise.all(
|
|
(data ?? []).map(async (p) => {
|
|
const { data: auth } = await admin.auth.admin.getUserById(p.id as string);
|
|
return { id: p.id as string, name: p.name as string, username: p.username as string, email: auth.user?.email ?? null };
|
|
})
|
|
);
|
|
}
|