"use server"; import { revalidatePath } from "next/cache"; import { sanitizeIlikeTerm } from "@/lib/supabase/query"; import { createClient } from "@/lib/supabase/server"; type ActionResult = { success: boolean; error?: string }; const POSITION_PATHS = ["/positions", "/orgchart", "/"]; async function callRpc( fn: "create_position" | "delete_position" | "staff_position_internally", payload: Record, revalidate: string[] ): Promise { const supabase = await createClient(); const { error } = await supabase.rpc(fn, { payload }); if (error) return { success: false, error: error.message }; for (const path of revalidate) revalidatePath(path); return { success: true }; } export async function createPosition(payload: { title: string; superior_employee_id: string; is_lead: boolean; team_id?: string; valid_from: string; }): Promise { return callRpc("create_position", payload, POSITION_PATHS); } export async function deletePosition(positionId: string): Promise { return callRpc("delete_position", { position_id: positionId }, POSITION_PATHS); } export async function staffPositionInternally(payload: { position_id: string; employee_id: string; }): Promise { return callRpc("staff_position_internally", payload, [...POSITION_PATHS, "/employees", `/employees/${payload.employee_id}`]); } export type SuperiorSearchResult = { id: string; first_name: string; last_name: string; job_title: string; division_id: string }; // For "Position ausschreiben": superior lookup, filtered to team-leads when // the new position is an IC role, or to division-heads/CEO when the new // position is itself a team lead (ยง2). export async function searchSuperiors(query: string, forLeadPosition: boolean): Promise { const supabase = await createClient(); let q = supabase .from("employees") .select("id, first_name, last_name, job_title, division_id") .eq("status", "Aktiv") .limit(20); q = forLeadPosition ? q.lte("org_level", 1) : q.eq("is_lead", true).eq("org_level", 2); if (query.trim()) { const term = sanitizeIlikeTerm(query.trim()); q = q.or(`first_name.ilike.%${term}%,last_name.ilike.%${term}%,job_title.ilike.%${term}%`); } const { data } = await q; return data ?? []; }