Files
sarlink-portal/actions/user-actions.ts
i701 dc3b5f9bf9
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 6m54s
feat(user-verification): implement user verification functionality and update dialog UI
2025-07-16 02:03:03 +05:00

163 lines
4.4 KiB
TypeScript

"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/auth";
import type { RejectUserFormState } from "@/components/user/user-reject-dialog";
import type { ApiError } from "@/lib/backend-types";
import type { User } from "@/lib/types/user";
import { handleApiResponse } from "@/utils/tryCatch";
type VerifyUserResponse = {
"ok": boolean,
"mismatch_fields": string[] | null,
"error": string | null,
"detail": string | null
} | {
"message": boolean,
};
export async function verifyUser(userId: string) {
const session = await getServerSession(authOptions);
if (!session?.apiToken) {
return { ok: false, error: 'Not authenticated' } as const;
}
try {
const r = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/verify/`,
{
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Token ${session.apiToken}`,
},
},
);
const body = (await r.json().catch(() => ({}))) as VerifyUserResponse &
{ message?: string; detail?: string };
if (!r.ok) {
const msg = body?.message || body?.detail || 'User verification failed';
return { ok: false, error: msg, mismatch_fields: body?.mismatch_fields || null } as const;
}
return { ok: true, data: body } as const;
} catch (err) {
return { ok: false, error: (err as Error).message } as const;
}
}
export async function getProfile() {
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/profile/`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
},
);
return handleApiResponse<User>(response, "getProfile");
}
export async function rejectUser(
_prevState: RejectUserFormState,
formData: FormData
): Promise<RejectUserFormState> {
const userId = formData.get("userId") as string;
const rejection_details = formData.get("rejection_details") as string;
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/reject/`,
{
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
body: JSON.stringify({ rejection_details: rejection_details }),
},
);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || errorData.detail || "Failed to reject user");
}
// Handle 204 No Content response (successful deletion)
if (response.status === 204) {
revalidatePath("/users");
redirect("/users");
}
revalidatePath("/users");
const error = await response.json()
return {
message: (error as ApiError).message || (error as ApiError).detail || "An unexpected error occurred.",
fieldErrors: {},
payload: formData
};
}
export type UpdateUserFormState = {
message: string;
fieldErrors?: {
id_card?: string[];
first_name?: string[];
last_name?: string[];
dob?: string[];
mobile?: string[];
address?: string[];
};
payload?: FormData;
};
export async function updateUser(
_prevState: UpdateUserFormState,
formData: FormData
): Promise<UpdateUserFormState> {
const userId = formData.get("userId") as string;
const data: Record<string, string | number | boolean> = {};
for (const [key, value] of formData.entries()) {
if (value !== undefined && value !== "") {
data[key] = typeof value === "number" ? value : String(value);
}
}
console.log("data in update user action", data)
const session = await getServerSession(authOptions);
const response = await fetch(
`${process.env.SARLINK_API_BASE_URL}/api/auth/users/${userId}/update/`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Token ${session?.apiToken}`,
},
body: JSON.stringify(data),
},
);
console.log("response in update user action", response)
if (!response.ok) {
const errorData = await response.json();
return {
message: errorData.message || errorData.detail || "An error occurred while updating the user.",
fieldErrors: errorData.field_errors || {},
payload: formData,
}
}
const updatedUser = await response.json() as User;
revalidatePath("/users/[userId]/update", "page");
revalidatePath("/users/[userId]/verify", "page");
return {
...updatedUser,
message: "User updated successfully",
};
}