|
- "use client";
-
- import { clientAuthFetch } from "@/app/utils/clientAuthFetch";
- import { NEXT_PUBLIC_API_URL } from "@/config/api";
-
- const base = NEXT_PUBLIC_API_URL;
-
- export type ItemDefaultShelfLifeRow = {
- id: number;
- itemCode: string;
- itemName?: string | null;
- defaultDays?: number | null;
- minus18Days?: number | null;
- useMinus18: boolean;
- openedDays?: number | null;
- storageC?: string | null;
- remarks?: string | null;
- effectiveDays?: number | null;
- };
-
- export type ItemDefaultShelfLifeInput = {
- itemCode: string;
- defaultDays?: number | null;
- minus18Days?: number | null;
- useMinus18: boolean;
- openedDays?: number | null;
- storageC?: string | null;
- remarks?: string | null;
- };
-
- async function parseJson<T>(res: Response): Promise<T> {
- if (!res.ok) {
- throw new Error(await readError(res));
- }
- return res.json() as Promise<T>;
- }
-
- async function readError(res: Response): Promise<string> {
- const text = await res.text().catch(() => "");
- if (!text) return `HTTP ${res.status}`;
- try {
- const json = JSON.parse(text) as { message?: string; error?: string };
- return json.message || json.error || text;
- } catch {
- return text;
- }
- }
-
- export async function fetchItemDefaultShelfLives(
- q?: string,
- ): Promise<ItemDefaultShelfLifeRow[]> {
- const url = new URL(`${base}/itemDefaultShelfLives`);
- if (q?.trim()) url.searchParams.set("q", q.trim());
- const res = await clientAuthFetch(url.toString(), { method: "GET" });
- return parseJson<ItemDefaultShelfLifeRow[]>(res);
- }
-
- export async function createItemDefaultShelfLife(
- data: ItemDefaultShelfLifeInput,
- ): Promise<ItemDefaultShelfLifeRow> {
- const res = await clientAuthFetch(`${base}/itemDefaultShelfLives`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(data),
- });
- return parseJson<ItemDefaultShelfLifeRow>(res);
- }
-
- export async function updateItemDefaultShelfLife(
- id: number,
- data: ItemDefaultShelfLifeInput,
- ): Promise<ItemDefaultShelfLifeRow> {
- const res = await clientAuthFetch(`${base}/itemDefaultShelfLives/${id}`, {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(data),
- });
- return parseJson<ItemDefaultShelfLifeRow>(res);
- }
-
- export async function deleteItemDefaultShelfLife(
- id: number,
- ): Promise<ItemDefaultShelfLifeRow[]> {
- const res = await clientAuthFetch(`${base}/itemDefaultShelfLives/${id}`, {
- method: "DELETE",
- });
- return parseJson<ItemDefaultShelfLifeRow[]>(res);
- }
|