"use server"; import { createAdminClient } from "@/lib/supabase/server"; import { auth } from "@clerk/nextjs/server"; import type { PayrollSettings } from "@/lib/payroll-settings-types"; async function getOrganisationId(): Promise { const { userId } = await auth(); if (!userId) throw new Error("Unauthenticated"); const supabase = await createAdminClient(); const { data: member, error } = await supabase .from("organisation_members") .select("organisation_id") .eq("user_id", userId) .single(); if (error || !member) throw new Error("No organisation found"); return member.organisation_id; } /** * Fetch the payroll settings for the current user's organisation. */ export async function fetchPayrollSettings(): Promise { const orgId = await getOrganisationId(); const supabase = await createAdminClient(); const { data, error } = await supabase .from("payroll_settings") .select("*") .eq("organisation_id", orgId) .single(); if (error && error.code !== "PGRST116") throw error; // PGRST116 = not found return data as PayrollSettings | null; } /** * Save payroll settings for the current organisation. * Creates if not exists, updates if exists. */ export async function savePayrollSettings( input: Omit ): Promise<{ success: boolean; error?: string }> { const orgId = await getOrganisationId(); const supabase = await createAdminClient(); // Check if settings already exist const { data: existing } = await supabase .from("payroll_settings") .select("id") .eq("organisation_id", orgId) .single(); const payload = { organisation_id: orgId, country_code: input.country_code, country_name: input.country_name, currency: input.currency, is_natively_supported: input.is_natively_supported, state_code: input.state_code, state_name: input.state_name, state_tax_rate: input.state_tax_rate, is_singapore_citizen_or_pr: input.is_singapore_citizen_or_pr, flat_income_tax_rate: input.flat_income_tax_rate, employer_pension_rate: input.employer_pension_rate, employer_tax_rate: input.employer_tax_rate, tax_free_allowance: input.tax_free_allowance, }; if (existing) { const { error } = await supabase .from("payroll_settings") .update(payload) .eq("id", existing.id); if (error) return { success: false, error: error.message }; } else { const { error } = await supabase .from("payroll_settings") .insert(payload); if (error) return { success: false, error: error.message }; } return { success: true }; }