import { apiRequestData } from "./http"; export type BudgetControlRuleEntityType = "all" | "reimbursement" | "purchase_request" | "travel_request"; export type BudgetControlMode = "warn" | "block" | "manual_review"; export type BudgetControlRule = { id: string; name: string; entityType: BudgetControlRuleEntityType; departmentId: string | null; legalEntityId: string | null; costCenterId: string | null; expenseTypeId: string | null; controlMode: BudgetControlMode; priority: number; enabled: boolean; notes: string | null; archivedAt: string | null; createdAt: string | null; updatedAt: string | null; }; export type BudgetControlRuleListResponse = { items: BudgetControlRule[]; }; function toQueryString(query: Record) { const params = new URLSearchParams(); for (const [key, value] of Object.entries(query)) { if (value == null || value === "") { continue; } params.set(key, typeof value === "boolean" ? String(value) : value); } const encoded = params.toString(); return encoded ? `?${encoded}` : ""; } export async function fetchBudgetControlRules(query: { entityType?: BudgetControlRuleEntityType; enabled?: boolean; } = {}) { return apiRequestData( `/api/budget-control-rules${toQueryString(query as Record)}`, ); } export async function createBudgetControlRule(payload: { name: string; entityType: BudgetControlRuleEntityType; departmentId?: string | null; legalEntityId?: string | null; expenseTypeId?: string | null; controlMode: BudgetControlMode; priority?: number; enabled?: boolean; notes?: string | null; }) { return apiRequestData<{ item: BudgetControlRule }>("/api/budget-control-rules", { method: "POST", body: JSON.stringify(payload), }); } export async function patchBudgetControlRule( ruleId: string, payload: Partial<{ name: string; entityType: BudgetControlRuleEntityType; departmentId: string | null; legalEntityId: string | null; expenseTypeId: string | null; controlMode: BudgetControlMode; priority: number; enabled: boolean; notes: string | null; }>, ) { return apiRequestData<{ item: BudgetControlRule }>(`/api/budget-control-rules/${ruleId}`, { method: "PATCH", body: JSON.stringify(payload), }); } export async function archiveBudgetControlRule(ruleId: string) { return apiRequestData<{ item: BudgetControlRule }>(`/api/budget-control-rules/${ruleId}/archive`, { method: "POST", body: JSON.stringify({}), }); }