84 lines
1.9 KiB
TypeScript
84 lines
1.9 KiB
TypeScript
"use server";
|
|
import { cookies } from "next/headers";
|
|
|
|
import {
|
|
AUTH_COOKIE_NAME,
|
|
BE_BASE_URL,
|
|
REVALIDATE_SECONDS,
|
|
HEALTH_CACHE_TAG,
|
|
} from "./constants";
|
|
|
|
export interface IHealthData {
|
|
success?: boolean;
|
|
message?: string;
|
|
total?: number;
|
|
successful?: number;
|
|
acceptance_rate?: number;
|
|
amount?: number;
|
|
atv?: number;
|
|
stats?: Array<{
|
|
label: string;
|
|
value: string | number;
|
|
change: string;
|
|
}>;
|
|
}
|
|
|
|
export interface IFetchHealthDataParams {
|
|
dateStart?: string;
|
|
dateEnd?: string;
|
|
}
|
|
|
|
export async function fetchHealthDataService({
|
|
dateStart,
|
|
dateEnd,
|
|
}: IFetchHealthDataParams = {}): Promise<IHealthData> {
|
|
const cookieStore = await cookies();
|
|
const token = cookieStore.get(AUTH_COOKIE_NAME)?.value;
|
|
|
|
if (!token) {
|
|
throw new Error("Missing auth token");
|
|
}
|
|
|
|
const queryParts: string[] = [];
|
|
|
|
// Add date filter if provided
|
|
if (dateStart && dateEnd) {
|
|
queryParts.push(
|
|
`Modified=BETWEEN/${encodeURIComponent(dateStart)}/${encodeURIComponent(dateEnd)}`
|
|
);
|
|
} else if (dateStart) {
|
|
queryParts.push(`Modified=>/${encodeURIComponent(dateStart)}`);
|
|
} else if (dateEnd) {
|
|
queryParts.push(`Modified=</${encodeURIComponent(dateEnd)}`);
|
|
}
|
|
|
|
const queryString = queryParts.join("&");
|
|
const backendUrl = `${BE_BASE_URL}/api/v1/transactions/health${
|
|
queryString ? `?${queryString}` : ""
|
|
}`;
|
|
|
|
const response = await fetch(backendUrl, {
|
|
method: "GET",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${token}`,
|
|
},
|
|
next: {
|
|
revalidate: REVALIDATE_SECONDS,
|
|
tags: [HEALTH_CACHE_TAG],
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response
|
|
.json()
|
|
.catch(() => ({ message: "Failed to fetch health data" }));
|
|
throw new Error(errorData?.message || "Failed to fetch health data");
|
|
}
|
|
|
|
const data = (await response.json()) as IHealthData;
|
|
|
|
console.log("[data]", data.stats);
|
|
return data;
|
|
}
|