Files
prowler/ui/actions/users/tenants.ts
Alan Buscaglia 4d5676f00e feat: upgrade to React 19, Next.js 15, React Compiler, HeroUI and Tailwind 4 (#8748)
Co-authored-by: Alan Buscaglia <alanbuscaglia@MacBook-Pro.local>
Co-authored-by: alejandrobailo <alejandrobailo94@gmail.com>
Co-authored-by: César Arroba <cesar@prowler.com>
Co-authored-by: Alejandro Bailo <59607668+alejandrobailo@users.noreply.github.com>
2025-09-30 09:59:51 +02:00

85 lines
2.1 KiB
TypeScript

"use server";
import { z } from "zod";
import { apiBaseUrl, getAuthHeaders } from "@/lib/helper";
import { handleApiError, handleApiResponse } from "@/lib/server-actions-helper";
export const getAllTenants = async () => {
const headers = await getAuthHeaders({ contentType: false });
const url = new URL(`${apiBaseUrl}/tenants`);
try {
const response = await fetch(url.toString(), {
method: "GET",
headers,
});
if (!response.ok) {
throw new Error(`Failed to fetch tenants data: ${response.statusText}`);
}
return handleApiResponse(response);
} catch (error) {
console.error("Error fetching tenants:", error);
return undefined;
}
};
const editTenantFormSchema = z
.object({
tenantId: z.string(),
name: z.string().trim().min(1, { message: "Name is required" }),
currentName: z.string(),
})
.refine((data) => data.name !== data.currentName, {
message: "Name must be different from the current name",
path: ["name"],
});
export async function updateTenantName(_prevState: any, formData: FormData) {
const headers = await getAuthHeaders({ contentType: true });
const formDataObject = Object.fromEntries(formData);
const validatedData = editTenantFormSchema.safeParse(formDataObject);
if (!validatedData.success) {
const formFieldErrors = validatedData.error.flatten().fieldErrors;
return {
errors: {
name: formFieldErrors?.name?.[0],
},
};
}
const { tenantId, name } = validatedData.data;
const payload = {
data: {
type: "tenants",
id: tenantId,
attributes: {
name: name.trim(),
},
},
};
try {
const url = new URL(`${apiBaseUrl}/tenants/${tenantId}`);
const response = await fetch(url.toString(), {
method: "PATCH",
headers,
body: JSON.stringify(payload),
});
if (!response.ok) {
throw new Error(`Failed to update tenant name: ${response.statusText}`);
}
await handleApiResponse(response, "/profile", false);
return { success: "Tenant name updated successfully!" };
} catch (error) {
return handleApiError(error);
}
}