import type { SupabaseClient } from "@supabase/supabase-js"; import { breadcrumbLabel, loadOrgMaps } from "./org"; import type { Database } from "./supabase/types"; export type OpenPositionResolved = { id: string; position_number: string; title: string; team_id: string; division_id: string; is_lead: boolean; reports_to_employee_id: string | null; created_at: string; managerName: string | null; orgLabel: string; }; // Shared by the Hire Wizard (position lookup) and the Positions & Bereiche page. export async function loadOpenPositions(supabase: SupabaseClient): Promise { const orgMaps = await loadOrgMaps(supabase); const { data: positions } = await supabase .from("positions") .select("id, position_number, title, team_id, division_id, is_lead, reports_to_employee_id, created_at") .eq("status", "open") .order("created_at", { ascending: false }); const managerIds = Array.from( new Set((positions ?? []).map((p) => p.reports_to_employee_id).filter((id): id is string => Boolean(id))) ); const { data: managers } = managerIds.length ? await supabase.from("employees_directory").select("id, first_name, last_name").in("id", managerIds) : { data: [] as { id: string; first_name: string; last_name: string }[] }; const managerNameById = new Map((managers ?? []).map((m) => [m.id, `${m.first_name} ${m.last_name}`])); return (positions ?? []).map((p) => ({ ...p, managerName: p.reports_to_employee_id ? (managerNameById.get(p.reports_to_employee_id) ?? null) : null, orgLabel: breadcrumbLabel(orgMaps, p.division_id, p.team_id), })); }