"use client"; import { clientAuthFetch } from "@/app/utils/clientAuthFetch"; import { NEXT_PUBLIC_API_URL } from "@/config/api"; import { STOCK_TAKE_QTY_GAP_WARN_PERCENT } from "./stockTakeQtyGapWarning"; export const STOCK_TAKE_QTY_GAP_WARN_SETTING = "STOCK_TAKE.qtyGapWarnPercent"; export const STOCK_TAKE_QTY_GAP_SETTING_EVENT = "stock-take-qty-gap-warn-percent"; type SettingsRow = { name: string; value: string }; let cached: number | null = null; export function parseQtyGapWarnPercent(raw: string | null | undefined): number { const text = String(raw ?? "").trim(); if (!text) return STOCK_TAKE_QTY_GAP_WARN_PERCENT; const n = Number(text); if (!Number.isFinite(n) || n < 0 || n > 1000) return STOCK_TAKE_QTY_GAP_WARN_PERCENT; return Math.round(n); } export async function fetchStockTakeQtyGapWarnPercent(): Promise { if (cached != null) return cached; const base = (NEXT_PUBLIC_API_URL ?? "").replace(/\/$/, ""); const res = await clientAuthFetch(`${base}/settings`, { method: "GET" }); if (!res.ok) return STOCK_TAKE_QTY_GAP_WARN_PERCENT; const rows = (await res.json()) as SettingsRow[]; const value = rows.find((row) => row.name === STOCK_TAKE_QTY_GAP_WARN_SETTING)?.value; cached = parseQtyGapWarnPercent(value); return cached; } export async function saveStockTakeQtyGapWarnPercent(percent: number): Promise { const base = (NEXT_PUBLIC_API_URL ?? "").replace(/\/$/, ""); const res = await clientAuthFetch( `${base}/settings/${encodeURIComponent(STOCK_TAKE_QTY_GAP_WARN_SETTING)}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ value: String(percent) }), }, ); if (!res.ok) { const text = await res.text().catch(() => ""); throw new Error(text || `Failed to save setting: ${res.status}`); } cached = percent; window.dispatchEvent(new CustomEvent(STOCK_TAKE_QTY_GAP_SETTING_EVENT, { detail: percent })); }