diff --git a/package.json b/package.json index 3a630eb6..20f4f65d 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,7 @@ "private": true, "scripts": { "dev": "next dev", + "warmup": "node scripts/warmup-menu.mjs", "build": "next build", "start": "set NODE_OPTIONS=--inspect --max-old-space-size=6144&& next start", "lint": "next lint", diff --git a/scripts/warmup-menu.mjs b/scripts/warmup-menu.mjs new file mode 100644 index 00000000..03910fa1 --- /dev/null +++ b/scripts/warmup-menu.mjs @@ -0,0 +1,88 @@ +const BASE = process.env.WARMUP_BASE || "http://localhost:3000"; +const COOKIE = process.env.WARMUP_COOKIE || ""; + +const PATHS = [ + "/dashboard", + "/po", + "/pickOrder", + "/inventory", + "/itemTracing", + "/stocktakemanagement", + "/stockIssue", + "/putAway", + "/finishedGood/management", + "/stockRecord", + "/doworkbench", + "/do", + "/ps", + "/jo", + "/jodetail", + "/productionProcess", + "/bag", + "/bagPrint", + "/laserPrint", + "/report", + "/m18Syn", + "/chart/purchase", + "/chart/joborder", + "/chart/joborder/board", + "/chart/delivery", + "/chart/warehouse", + "/chart/forecast", + "/settings/user", + "/settings/clientMonitor", + "/settings/items", + "/settings/itemDefaultShelfLife", + "/settings/equipment", + "/settings/warehouse", + "/settings/printer", + "/settings/itemPrice", + "/settings/qcItem", + "/settings/qcCategory", + "/settings/qcItemAll", + "/settings/shop/board", + "/settings/deliveryOrderFloor", + "/settings/rss", + "/settings/bomWeighting", + "/settings/masterDataIssues", + "/settings/qrCodeHandle", + "/settings/m18ImportTesting", + "/settings/importExcel", + "/settings/importBom", +]; + +async function waitReady() { + const deadline = Date.now() + 120_000; + while (Date.now() < deadline) { + try { + const res = await fetch(`${BASE}/login`); + if (res.status < 500) return; + } catch { + // server still starting + } + await new Promise((r) => setTimeout(r, 1000)); + } + throw new Error(`dev server not ready at ${BASE}`); +} + +console.log(`Waiting for ${BASE}/login (Next compiles this on first hit; the site will look stuck until it finishes)…`); +await waitReady(); +console.log(`Dev server answered. Warming ${PATHS.length} menu pages at ${BASE}`); +if (!COOKIE) { + console.log( + "No WARMUP_COOKIE — private pages (/dashboard, /ps, /report, /settings, …) will redirect and stay uncompiled.", + ); +} + +for (const path of PATHS) { + process.stdout.write(`compiling ${path} … `); + const t0 = Date.now(); + const res = await fetch(`${BASE}${path}`, { + redirect: "manual", + headers: COOKIE ? { cookie: COOKIE } : {}, + }); + const redirected = res.status >= 300 && res.status < 400; + console.log( + `${res.status} ${Date.now() - t0}ms${redirected ? " (redirect, page not compiled)" : ""}`, + ); +} diff --git a/src/app/(main)/axios/AxiosProvider.tsx b/src/app/(main)/axios/AxiosProvider.tsx index e2f5f2f2..26bd3808 100644 --- a/src/app/(main)/axios/AxiosProvider.tsx +++ b/src/app/(main)/axios/AxiosProvider.tsx @@ -2,12 +2,26 @@ "use client"; -import React, { createContext, useContext, useEffect, useState, useCallback } from "react"; +import React, { + createContext, + useContext, + useEffect, + useState, + useCallback, + useRef, +} from "react"; import { getSession } from "next-auth/react"; import { SessionWithTokens } from "@/config/authConfig"; import { + ACCESS_TOKEN_KEY, + ACCESS_TOKEN_REFRESH_SKEW_SECONDS, + clearBackendTokens, + ensureFreshAccessToken, + getBackendJwtSecondsRemaining, isBackendJwtExpired, LOGIN_SESSION_EXPIRED_HREF, + persistBackendTokens, + readStoredRefreshToken, } from "@/app/utils/authToken"; import axiosInstance, { SetupAxiosInterceptors } from "./axiosInstance"; @@ -19,14 +33,48 @@ const TokenContext = createContext<{ setAccessToken: () => {}, }); -export const AxiosProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { +/** + * Merge next-auth tokens into localStorage without clobbering a newer + * localStorage access token (e.g. after a client-side refresh). + */ +function syncSessionTokensToStorage(session: SessionWithTokens | null): void { + if (!session) return; + + let localAccess = ""; + try { + localAccess = localStorage.getItem(ACCESS_TOKEN_KEY)?.trim() ?? ""; + } catch { + localAccess = ""; + } + const localRefresh = readStoredRefreshToken(); + const sessionAccess = session.accessToken?.trim() || ""; + const sessionRefresh = session.refreshToken?.trim() || ""; + + // local missing, or local expired while session already has a fresher JWT + if ( + sessionAccess && + (!localAccess || isBackendJwtExpired(localAccess)) + ) { + persistBackendTokens(sessionAccess, sessionRefresh || localRefresh); + return; + } + + // Keep existing access token; only backfill missing refresh token + if (localAccess && sessionRefresh && !localRefresh) { + persistBackendTokens(localAccess, sessionRefresh); + } +} + +export const AxiosProvider: React.FC<{ children: React.ReactNode }> = ({ + children, +}) => { const [accessToken, setAccessToken] = useState(null); const [isHydrated, setIsHydrated] = useState(false); + const refreshTimerRef = useRef | null>(null); - // Hydrate token only on client useEffect(() => { try { - const token = localStorage.getItem("accessToken"); + const token = localStorage.getItem(ACCESS_TOKEN_KEY); if (token) setAccessToken(token); } catch (e) { console.warn("localStorage unavailable", e); @@ -35,10 +83,34 @@ export const AxiosProvider: React.FC<{ children: React.ReactNode }> = ({ childre } }, []); + const scheduleProactiveRefresh = useCallback((token: string) => { + if (refreshTimerRef.current) { + clearTimeout(refreshTimerRef.current); + refreshTimerRef.current = null; + } + const remaining = getBackendJwtSecondsRemaining(token); + if (remaining === null) return; + + // Refresh a few minutes before expiry (clamp delay to a safe range for setTimeout) + const delayMs = Math.min( + Math.max(30_000, (remaining - ACCESS_TOKEN_REFRESH_SKEW_SECONDS) * 1000), + 2_147_483_647 + ); + refreshTimerRef.current = setTimeout(async () => { + const session = (await getSession()) as SessionWithTokens | null; + const next = await ensureFreshAccessToken( + readStoredRefreshToken() || session?.refreshToken + ); + if (next) { + setAccessToken(next); + scheduleProactiveRefresh(next); + } + }, delayMs); + }, []); + /** - * Detect expired/missing backend JWT before user actions (e.g. /report search). - * Sync accessToken from next-auth session into localStorage if missing, then - * redirect to login when the Bearer token is absent or past `exp`. + * Keep backend JWT fresh. Only force login redirect when we have neither a + * usable access token nor a successful refresh (avoid false logout on blips). */ useEffect(() => { if (!isHydrated || typeof window === "undefined") return; @@ -46,37 +118,47 @@ export const AxiosProvider: React.FC<{ children: React.ReactNode }> = ({ childre let cancelled = false; (async () => { try { - let token = localStorage.getItem("accessToken")?.trim() ?? ""; + const session = (await getSession()) as SessionWithTokens | null; + if (cancelled) return; - if (!token) { - const session = (await getSession()) as SessionWithTokens | null; - if (cancelled) return; - if (session?.accessToken) { - token = session.accessToken; - localStorage.setItem("accessToken", token); - setAccessToken(token); - } - } + syncSessionTokensToStorage(session); + + const token = await ensureFreshAccessToken( + readStoredRefreshToken() || session?.refreshToken + ); + if (cancelled) return; if (!token) { + // Soft-fail if next-auth still has a session — avoid kicking users on + // transient refresh failures when an access token simply isn't readable yet. + if (session?.accessToken && !session.error) { + setAccessToken(session.accessToken); + persistBackendTokens(session.accessToken, session.refreshToken); + scheduleProactiveRefresh(session.accessToken); + return; + } + clearBackendTokens(); window.location.href = LOGIN_SESSION_EXPIRED_HREF; return; } - if (isBackendJwtExpired(token)) { - window.location.href = LOGIN_SESSION_EXPIRED_HREF; - } + setAccessToken(token); + scheduleProactiveRefresh(token); } catch (e) { + // Do not redirect on unexpected errors (network / getSession failures) console.warn("Auth token check failed", e); } })(); return () => { cancelled = true; + if (refreshTimerRef.current) { + clearTimeout(refreshTimerRef.current); + refreshTimerRef.current = null; + } }; - }, [isHydrated]); + }, [isHydrated, scheduleProactiveRefresh]); - // Apply token + interceptors useEffect(() => { if (accessToken) { axiosInstance.defaults.headers.Authorization = `Bearer ${accessToken}`; @@ -86,24 +168,26 @@ export const AxiosProvider: React.FC<{ children: React.ReactNode }> = ({ childre } }, [accessToken]); - const handleSetAccessToken = useCallback((token: string | null) => { - setAccessToken(token); - try { - if (token) { - localStorage.setItem("accessToken", token); - } else { - localStorage.removeItem("accessToken"); + const handleSetAccessToken = useCallback( + (token: string | null) => { + setAccessToken(token); + try { + if (token) { + localStorage.setItem(ACCESS_TOKEN_KEY, token); + scheduleProactiveRefresh(token); + } else { + clearBackendTokens(); + } + } catch { + // ignore (e.g. private mode) } - } catch (e) { - // ignore (e.g. private mode) - } - }, []); + }, + [scheduleProactiveRefresh] + ); - // Critical fix: never return null → always return children wrapped in fragment return ( - {/* Render children immediately – they will just not have the token for 1-2ms */} {children} @@ -111,4 +195,4 @@ export const AxiosProvider: React.FC<{ children: React.ReactNode }> = ({ childre }; export const useAxios = () => useContext(AxiosContext); -export const useToken = () => useContext(TokenContext); \ No newline at end of file +export const useToken = () => useContext(TokenContext); diff --git a/src/app/(main)/axios/axiosInstance.ts b/src/app/(main)/axios/axiosInstance.ts index 1d24e5d9..2641a062 100644 --- a/src/app/(main)/axios/axiosInstance.ts +++ b/src/app/(main)/axios/axiosInstance.ts @@ -1,52 +1,76 @@ -import axios from "axios"; +import axios, { AxiosError, InternalAxiosRequestConfig } from "axios"; +import { + LOGIN_SESSION_EXPIRED_HREF, + readStoredRefreshToken, + refreshBackendAccessToken, +} from "@/app/utils/authToken"; const axiosInstance = axios.create({ - baseURL: process.env.API_URL, + baseURL: process.env.API_URL || process.env.NEXT_PUBLIC_API_URL, }); -// Clear existing interceptors to prevent multiple registrations -const clearInterceptors = () => { - const requestInterceptor = axiosInstance.interceptors.request.use(); - const responseInterceptor = axiosInstance.interceptors.response.use(); +type RetriableConfig = InternalAxiosRequestConfig & { _retry?: boolean }; - if (requestInterceptor) { - axiosInstance.interceptors.request.eject(requestInterceptor); - } +let requestInterceptorId: number | null = null; +let responseInterceptorId: number | null = null; - if (responseInterceptor) { - axiosInstance.interceptors.response.eject(responseInterceptor); +const clearInterceptors = () => { + if (requestInterceptorId !== null) { + axiosInstance.interceptors.request.eject(requestInterceptorId); + requestInterceptorId = null; + } + if (responseInterceptorId !== null) { + axiosInstance.interceptors.response.eject(responseInterceptorId); + responseInterceptorId = null; } }; -export const SetupAxiosInterceptors = (inputToken: string | null) => { - console.log("[debug] set up interceptors", inputToken); - - // Clear existing interceptors +/** + * Always prefer localStorage accessToken (may have been refreshed) over any + * closed-over token passed into SetupAxiosInterceptors. + */ +export const SetupAxiosInterceptors = (_inputToken: string | null) => { clearInterceptors(); - // Request interceptor - axiosInstance.interceptors.request.use( + requestInterceptorId = axiosInstance.interceptors.request.use( (config) => { - // Use the token passed in or retrieve from localStorage - const token = inputToken ?? localStorage.getItem("accessToken"); - if (token) { - config.headers.Authorization = `Bearer ${token}`; + try { + const token = + (typeof window !== "undefined" + ? localStorage.getItem("accessToken") + : null) ?? _inputToken; + if (token) { + config.headers.Authorization = `Bearer ${token}`; + } + } catch { + if (_inputToken) { + config.headers.Authorization = `Bearer ${_inputToken}`; + } } return config; }, - (error) => { - return Promise.reject(error); - }, + (error) => Promise.reject(error), ); - console.log("[debug] set up interceptors2", inputToken); + responseInterceptorId = axiosInstance.interceptors.response.use( + (response) => response, + async (error: AxiosError) => { + const status = error.response?.status; + const original = error.config as RetriableConfig | undefined; + + // Only 401 = unauthenticated. Do not treat 403 (forbidden) as session expiry. + if (status === 401 && original && !original._retry && typeof window !== "undefined") { + original._retry = true; + const refreshed = await refreshBackendAccessToken(readStoredRefreshToken()); + if (refreshed) { + original.headers = original.headers ?? {}; + original.headers.Authorization = `Bearer ${refreshed}`; + axiosInstance.defaults.headers.Authorization = `Bearer ${refreshed}`; + return axiosInstance(original); + } + window.location.href = LOGIN_SESSION_EXPIRED_HREF; + } - // Response interceptor - axiosInstance.interceptors.response.use( - (response) => { - return response; - }, - (error) => { console.error("API Error:", error.response?.data || error); return Promise.reject(error); }, diff --git a/src/app/(main)/chart/delivery/page.tsx b/src/app/(main)/chart/delivery/page.tsx index bbbf3bb8..4cc04524 100644 --- a/src/app/(main)/chart/delivery/page.tsx +++ b/src/app/(main)/chart/delivery/page.tsx @@ -1,6 +1,8 @@ "use client"; import React, { useCallback, useMemo, useState } from "react"; +import { useSession } from "next-auth/react"; +import { AUTH, hasAbility } from "@/authorities"; import { Box, Typography, @@ -68,6 +70,9 @@ const defaultCriteria: Criteria = { /** FP-MTMS Version Checklist | Functions Ref. No. 61 | v1.0.0 | 2026-08-10 */ export default function DeliveryChartPage() { + const { data: session } = useSession(); + const abilities = session?.abilities ?? session?.user?.abilities ?? []; + const canSeeStaffPerformance = hasAbility(abilities, AUTH.PERFORMANCE); const [criteria, setCriteria] = useState(defaultCriteria); const [topItemsSelected, setTopItemsSelected] = useState([]); const [topItemOptions, setTopItemOptions] = useState([]); @@ -132,6 +137,10 @@ export default function DeliveryChartPage() { }, [criteria.topItems, topItemsSelected, setChartLoading]); React.useEffect(() => { + if (!canSeeStaffPerformance) { + setChartData((prev) => ({ ...prev, staffPerf: [] })); + return; + } const s = criteria.staffPerf.startDate; const e = criteria.staffPerf.endDate; if (!s || !e) { @@ -161,13 +170,17 @@ export default function DeliveryChartPage() { ) .catch((err) => setError(err instanceof Error ? err.message : "Request failed")) .finally(() => setChartLoading("staffPerf", false)); - }, [criteria.staffPerf, staffSelected, setChartLoading]); + }, [canSeeStaffPerformance, criteria.staffPerf, staffSelected, setChartLoading]); React.useEffect(() => { + if (!canSeeStaffPerformance) { + setStaffOptions([]); + return; + } fetchStaffDeliveryPerformanceHandlers() .then(setStaffOptions) .catch(() => setStaffOptions([])); - }, []); + }, [canSeeStaffPerformance]); React.useEffect(() => { const { startDate: s, endDate: e } = toDateRange(criteria.topItems.rangeDays); fetchTopDeliveryItemsItemOptions(s, e).then(setTopItemOptions).catch(() => setTopItemOptions([])); @@ -317,6 +330,7 @@ export default function DeliveryChartPage() { )} + {canSeeStaffPerformance && ( )} + )} ); } diff --git a/src/app/(main)/m18Syn/page.tsx b/src/app/(main)/m18Syn/page.tsx index 8a84520d..4c7f6b74 100644 --- a/src/app/(main)/m18Syn/page.tsx +++ b/src/app/(main)/m18Syn/page.tsx @@ -39,6 +39,7 @@ export default function M18SynPage() { type ParsedSyncResult = | { kind: "exists"; message: string } + | { kind: "skipped_not_pending"; message: string } | { kind: "not_found"; message: string } | { kind: "success"; message: string; totalSuccess: number } | { kind: "fail"; message: string; totalFail: number } @@ -60,15 +61,45 @@ export default function M18SynPage() { return { kind: "exists", message: `${docName}已存在系統` }; } - // "not found in M18" (sync-by-code returns processed=1, fail=1) + // Local PO/DO exists but status is not pending — sync intentionally skipped + if (query.includes("skipped (not pending")) { + const statusMatch = query.match(/status=([^\s;|]+)/); + const statusRaw = (statusMatch?.[1] ?? "").toLowerCase(); + const statusLabel = (() => { + if (statusRaw === "receiving") { + // DO uses receiving = 已放單; PO uses receiving = 收貨中 + return docName === "送貨訂單" ? "已放單" : "收貨中"; + } + if (statusRaw === "completed") return "已完成"; + if (statusRaw === "pending") return "待處理"; + return statusRaw || "非待處理"; + })(); + return { + kind: "skipped_not_pending", + message: `無法同步:此${docName}目前為「${statusLabel}」,不能再從 M18 覆寫(僅「待處理」可同步)。`, + }; + } + + // "not found in M18" (sync-by-code returns processed=1, fail=1) — may be wrong tab (PO vs DO) if ( - docName === "送貨訂單" && totalProcessed === 1 && totalSuccess === 0 && totalFail === 1 && query.includes("code=equal=") ) { - return { kind: "not_found", message: `在M18找不到${docName}` }; + if (docName === "採購單") { + return { + kind: "not_found", + message: "在M18找不到採購單", + }; + } + if (docName === "送貨訂單") { + return { + kind: "not_found", + message: + "在M18找不到送貨訂單。若此單為物料採購單,請改到「採購單」分頁同步。", + }; + } } if (totalSuccess > 0 && totalFail === 0) { @@ -108,7 +139,8 @@ export default function M18SynPage() { const handleSyncM18PoByCode = async () => { if (m18PoInFlightRef.current) return; - if (!m18PoCode.trim()) { + const code = m18PoCode.trim(); + if (!code) { alert("Please enter PO code."); return; } @@ -116,15 +148,58 @@ export default function M18SynPage() { setIsSyncingM18Po(true); setM18PoSyncResult(""); try { - const response = await clientAuthFetch( - `${NEXT_PUBLIC_API_URL}/m18/test/po-by-code?code=${encodeURIComponent(m18PoCode.trim())}`, + const poResponse = await clientAuthFetch( + `${NEXT_PUBLIC_API_URL}/m18/test/po-by-code?code=${encodeURIComponent(code)}`, { method: "GET" }, ); - if (response.status === 401 || response.status === 403) return; - const text = await response.text(); - setM18PoSyncResult(formatSyncResultText("採購單", text)); - if (!response.ok) { - alert(`Sync failed: ${response.status}`); + if (poResponse.status === 401 || poResponse.status === 403) return; + const poText = await poResponse.text(); + const poParsed = parseSyncResult("採購單", poText); + + if (poParsed.kind !== "not_found") { + setM18PoSyncResult(poParsed.message); + if (!poResponse.ok) { + alert(`Sync failed: ${poResponse.status}`); + } + return; + } + + // PO not found under material-PO scope — auto-try DO (shop PO) with same code + setM18PoSyncResult("採購單找不到,改嘗試同步送貨訂單…"); + const doResponse = await clientAuthFetch( + `${NEXT_PUBLIC_API_URL}/m18/test/do-by-code?code=${encodeURIComponent(code)}`, + { method: "GET" }, + ); + if (doResponse.status === 401 || doResponse.status === 403) return; + const doText = await doResponse.text(); + const doParsed = parseSyncResult("送貨訂單", doText); + + if (doParsed.kind === "success") { + setM18PoSyncResult( + [ + `採購單找不到(code=${code})`, + `已自動改以送貨訂單同步:成功`, + ].join("\n"), + ); + } else if (doParsed.kind === "not_found") { + setM18PoSyncResult( + [ + `採購單找不到(code=${code})`, + `已自動改試送貨訂單:亦找不到`, + "請確認單號是否正確。", + ].join("\n"), + ); + } else { + setM18PoSyncResult( + [ + `採購單找不到(code=${code})`, + `已自動改試送貨訂單:${doParsed.message}`, + ].join("\n"), + ); + } + + if (!doResponse.ok) { + alert(`DO fallback sync failed: ${doResponse.status}`); } } catch (e) { console.error("M18 PO Sync By Code Error:", e); @@ -158,6 +233,7 @@ export default function M18SynPage() { const outputs: string[] = []; const okCodes: string[] = []; const notFoundCodes: string[] = []; + const skippedReleasedCodes: string[] = []; const otherFailCodes: string[] = []; for (const code of codes) { const response = await clientAuthFetch( @@ -169,6 +245,7 @@ export default function M18SynPage() { const parsed = parseSyncResult("送貨訂單", text || ""); if (parsed.kind === "success") okCodes.push(code); else if (parsed.kind === "not_found") notFoundCodes.push(code); + else if (parsed.kind === "skipped_not_pending") skippedReleasedCodes.push(code); else otherFailCodes.push(code); const perCodeMsg = @@ -180,7 +257,13 @@ export default function M18SynPage() { outputs.push(""); outputs.push(`共${okCodes.length}張送貨訂單成功`); - if (notFoundCodes.length > 0) outputs.push(`共${notFoundCodes.length}張在M18找不到訂單 (${notFoundCodes.join(", ")})`); + if (notFoundCodes.length > 0) { + outputs.push(`共${notFoundCodes.length}張在M18找不到送貨訂單 (${notFoundCodes.join(", ")})`); + outputs.push("提示:若為物料採購單,請改到「採購單」分頁同步。"); + } + if (skippedReleasedCodes.length > 0) { + outputs.push(`共${skippedReleasedCodes.length}張已放單/已完成,無法再同步 (${skippedReleasedCodes.join(", ")})`); + } if (otherFailCodes.length > 0) outputs.push(`共${otherFailCodes.length}張同步失敗 (${otherFailCodes.join(", ")})`); setM18DoSyncResult(outputs.join("\n")); @@ -217,6 +300,7 @@ export default function M18SynPage() { const okCodes: string[] = []; const existsCodes: string[] = []; const notFoundCodes: string[] = []; + const skippedReleasedCodes: string[] = []; const otherFailCodes: string[] = []; for (const code of codes) { const response = await clientAuthFetch( @@ -229,6 +313,7 @@ export default function M18SynPage() { if (parsed.kind === "success") okCodes.push(code); else if (parsed.kind === "exists") existsCodes.push(code); else if (parsed.kind === "not_found") notFoundCodes.push(code); + else if (parsed.kind === "skipped_not_pending") skippedReleasedCodes.push(code); else otherFailCodes.push(code); const perCodeMsg = @@ -242,8 +327,14 @@ export default function M18SynPage() { // Summary outputs.push(""); outputs.push(`共${okCodes.length}張送貨訂單成功`); - if (notFoundCodes.length > 0) outputs.push(`共${notFoundCodes.length}張在M18找不到訂單 (${notFoundCodes.join(", ")})`); + if (notFoundCodes.length > 0) { + outputs.push(`共${notFoundCodes.length}張在M18找不到送貨訂單 (${notFoundCodes.join(", ")})`); + outputs.push("提示:若為物料採購單,請改到「採購單」分頁同步。"); + } if (existsCodes.length > 0) outputs.push(`共${existsCodes.length}張訂單已存在系統 (${existsCodes.join(", ")})`); + if (skippedReleasedCodes.length > 0) { + outputs.push(`共${skippedReleasedCodes.length}張已放單/已完成,無法再同步 (${skippedReleasedCodes.join(", ")})`); + } if (otherFailCodes.length > 0) outputs.push(`共${otherFailCodes.length}張同步失敗 (${otherFailCodes.join(", ")})`); setM18DoExtraSyncResult(outputs.join("\n")); @@ -301,6 +392,7 @@ export default function M18SynPage() { Requires 行政 (ADMIN) or M18同步 (M18_SYNC). Sync Purchase Order, Delivery Order, or product/material from M18 using document or item code. + 「採購單」找不到時會自動改試「送貨訂單」;「送貨訂單」找不到時請改到「採購單」分頁。 setTabValue(v)} aria-label="M18 sync by code" centered variant="fullWidth"> diff --git a/src/app/(main)/report/AsyncItemCodeAutocomplete.tsx b/src/app/(main)/report/AsyncItemCodeAutocomplete.tsx index 3e1681a1..9bcb214e 100644 --- a/src/app/(main)/report/AsyncItemCodeAutocomplete.tsx +++ b/src/app/(main)/report/AsyncItemCodeAutocomplete.tsx @@ -1,14 +1,17 @@ "use client"; -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { Autocomplete, Chip, CircularProgress, TextField } from "@mui/material"; import { useTranslation } from "react-i18next"; import { searchItemCodes, type ItemCodeSearchHit } from "./itemCodeSearchApi"; +import { parseItemCodeTokens } from "./parseItemCodeTokens"; type Props = { label: string; value: string[]; onChange: (codes: string[]) => void; + /** Live text in the box, including text that has not been picked from the list. */ + onInputValueChange?: (value: string) => void; placeholder?: string; disabled?: boolean; minChars?: number; @@ -17,11 +20,12 @@ type Props = { const hitLabel = (hit: ItemCodeSearchHit) => hit.name ? `${hit.code} ${hit.name}` : hit.code; -/** FP-MTMS Version Checklist | Functions Ref. No. 81 | v1.0.0 | 2026-09-10 */ +/** FP-MTMS Version Checklist | Functions Ref. No. 81 | v1.0.1 | 2026-09-28 */ const AsyncItemCodeAutocomplete: React.FC = ({ label, value, onChange, + onInputValueChange, placeholder, disabled = false, minChars = 2, @@ -73,21 +77,47 @@ const AsyncItemCodeAutocomplete: React.FC = ({ }; }, [trimmedInput, minChars]); + const selectedCodes = useMemo( + () => new Set(value.map((code) => code.toUpperCase())), + [value], + ); + const options = useMemo(() => { const seen = new Set(); const codes: string[] = []; suggestions.forEach((hit) => { - if (seen.has(hit.code)) return; - seen.add(hit.code); + const key = hit.code.toUpperCase(); + if (seen.has(key) || selectedCodes.has(key)) return; + seen.add(key); codes.push(hit.code); }); - value.forEach((code) => { - if (seen.has(code)) return; - seen.add(code); - codes.push(code); - }); return codes; - }, [suggestions, value]); + }, [suggestions, selectedCodes]); + + useEffect(() => { + const trimmed = inputValue.trim(); + if (!trimmed) return; + const hit = suggestions.find((item) => item.code.toUpperCase() === trimmed.toUpperCase()); + if (hit) onInputValueChange?.(hit.code); + }, [suggestions, inputValue, onInputValueChange]); + + const inputValueRef = useRef(inputValue); + inputValueRef.current = inputValue; + const previousValueRef = useRef(value); + useEffect(() => { + const previous = previousValueRef.current; + previousValueRef.current = value; + const tokens = parseItemCodeTokens(inputValueRef.current); + if (tokens.length === 0) return; + const previousKeys = new Set(previous.map((code) => code.toUpperCase())); + const nextKeys = new Set(value.map((code) => code.toUpperCase())); + const justCommitted = tokens.every( + (token) => nextKeys.has(token.toUpperCase()) && !previousKeys.has(token.toUpperCase()), + ); + if (!justCommitted) return; + setInputValue(""); + onInputValueChange?.(""); + }, [value, onInputValueChange]); const noOptionsText = needsMoreChars ? t("typeToSearchItemCode", { min: minChars }) @@ -112,9 +142,11 @@ const AsyncItemCodeAutocomplete: React.FC = ({ filterOptions={(opts) => trimmedInput.length < minChars ? [] - : opts.filter((code) => !value.includes(code)) + : opts.filter((code) => !selectedCodes.has(code.toUpperCase())) + } + isOptionEqualToValue={(option, selected) => + option.toUpperCase() === selected.toUpperCase() } - isOptionEqualToValue={(option, selected) => option === selected} autoHighlight noOptionsText={noOptionsText} sx={{ @@ -162,9 +194,13 @@ const AsyncItemCodeAutocomplete: React.FC = ({ onInputChange={(_, next, reason) => { if (reason === "reset") { setInputValue(""); + onInputValueChange?.(""); return; } setInputValue(next); + const trimmed = next.trim(); + const hit = suggestions.find((item) => item.code.toUpperCase() === trimmed.toUpperCase()); + onInputValueChange?.(hit?.code ?? next); }} onChange={(_, newValue) => { const codes = (Array.isArray(newValue) ? newValue : []) diff --git a/src/app/(main)/report/ReportSelectionDashboard.tsx b/src/app/(main)/report/ReportSelectionDashboard.tsx index b5eb3802..48ea716f 100644 --- a/src/app/(main)/report/ReportSelectionDashboard.tsx +++ b/src/app/(main)/report/ReportSelectionDashboard.tsx @@ -23,6 +23,7 @@ import { useReportLabels } from "./reportI18n"; const REPORT_ICON_MAP: Record = { "rep-011": Inventory2OutlinedIcon, + "rep-020": Inventory2OutlinedIcon, "rep-007": MonetizationOnOutlinedIcon, "rep-012": LayersOutlinedIcon, "rep-021": Inventory2OutlinedIcon, diff --git a/src/app/(main)/report/SemiFGProductionAnalysisReport.tsx b/src/app/(main)/report/SemiFGProductionAnalysisReport.tsx index f676ba66..af09bff2 100644 --- a/src/app/(main)/report/SemiFGProductionAnalysisReport.tsx +++ b/src/app/(main)/report/SemiFGProductionAnalysisReport.tsx @@ -1,6 +1,6 @@ "use client"; -import React, { useState, useEffect } from 'react'; +import React, { useEffect, useRef, useState } from 'react'; import { useTranslation } from "react-i18next"; import { Dialog, @@ -19,17 +19,21 @@ import { Typography, } from '@mui/material'; import DownloadIcon from '@mui/icons-material/Download'; +import dayjs from 'dayjs'; import { - fetchSemiFGItemCodes, fetchSemiFGItemCodesWithCategory, generateSemiFGProductionAnalysisReport, generateSemiFGProductionAnalysisReportExcel, + generateSemiFGProductionAnalysisReportExcelDaily, ItemCodeWithCategory, } from './semiFGProductionAnalysisApi'; import { parseItemCodeTokens } from './parseItemCodeTokens'; +type ExportFormat = 'pdf' | 'excel' | 'excel-daily'; + interface SemiFGProductionAnalysisReportProps { criteria: Record; + prepareCriteria?: () => Record; requiredFieldLabels: string[]; loading: boolean; setLoading: (loading: boolean) => void; @@ -39,6 +43,7 @@ interface SemiFGProductionAnalysisReportProps { export default function SemiFGProductionAnalysisReport({ criteria, + prepareCriteria, requiredFieldLabels, loading, setLoading, @@ -49,7 +54,8 @@ export default function SemiFGProductionAnalysisReport({ const [showConfirmDialog, setShowConfirmDialog] = useState(false); const [selectedItemCodesInfo, setSelectedItemCodesInfo] = useState([]); const [itemCodesWithCategory, setItemCodesWithCategory] = useState>({}); - const [exportFormat, setExportFormat] = useState<'pdf' | 'excel'>('pdf'); + const [exportFormat, setExportFormat] = useState('pdf'); + const inFlightRef = useRef(false); // Fetch item codes with category when stockCategory changes useEffect(() => { @@ -69,19 +75,39 @@ export default function SemiFGProductionAnalysisReport({ } }, [criteria.stockCategory]); - const handleExportClick = async (format: 'pdf' | 'excel') => { + const dailyRangeError = (activeCriteria: Record): string | null => { + const start = (activeCriteria.lastOutDateStart || '').trim(); + const end = (activeCriteria.lastOutDateEnd || '').trim(); + if (!start || !end) return t('semiFgDailyRangeRequired'); + const startDate = dayjs(start); + const endDate = dayjs(end); + if (!startDate.isValid() || !endDate.isValid()) return t('semiFgDailyRangeRequired'); + if (endDate.isBefore(startDate, 'day')) return t('semiFgDailyRangeInvalid'); + if (endDate.diff(startDate, 'day') + 1 > 366) return t('semiFgDailyRangeTooLong'); + return null; + }; + + const handleExportClick = async (format: ExportFormat) => { + if (inFlightRef.current) return; + const activeCriteria = prepareCriteria?.() ?? criteria; setExportFormat(format); - // Validate required fields if (requiredFieldLabels.length > 0) { alert(t('missingRequired', { fields: requiredFieldLabels.join('\n- ') })); return; } + if (format === 'excel-daily') { + const rangeError = dailyRangeError(activeCriteria); + if (rangeError) { + alert(rangeError); + return; + } + } const selectedCodes = parseItemCodeTokens( - [criteria.itemCode, criteria.itemCodePaste].filter(Boolean).join(' '), + [activeCriteria.itemCode, activeCriteria.itemCodePaste].filter(Boolean).join(' '), ); if (selectedCodes.length === 0) { - await executeExport(format); + await executeExport(format, activeCriteria); return; } @@ -97,24 +123,47 @@ export default function SemiFGProductionAnalysisReport({ setShowConfirmDialog(true); }; - const executeExport = async (format: 'pdf' | 'excel' = exportFormat) => { + const executeExport = async ( + format: ExportFormat = exportFormat, + activeCriteria: Record = prepareCriteria?.() ?? criteria, + ) => { + if (inFlightRef.current) return; + inFlightRef.current = true; setLoading(true); try { - if (format === 'excel') { - await generateSemiFGProductionAnalysisReportExcel(criteria, reportTitle); + if (format === 'excel-daily') { + await generateSemiFGProductionAnalysisReportExcelDaily(activeCriteria, reportTitle); + onExportSuccess?.('excel'); + } else if (format === 'excel') { + await generateSemiFGProductionAnalysisReportExcel(activeCriteria, reportTitle); + onExportSuccess?.('excel'); } else { - await generateSemiFGProductionAnalysisReport(criteria, reportTitle); + await generateSemiFGProductionAnalysisReport(activeCriteria, reportTitle); + onExportSuccess?.('pdf'); } - onExportSuccess?.(format); setShowConfirmDialog(false); } catch (error) { console.error('Failed to generate report:', error); - alert(t('generateError')); + const message = error instanceof Error ? error.message.trim() : ''; + alert(message && !message.startsWith('HTTP error') ? message : t('generateError')); } finally { setLoading(false); + inFlightRef.current = false; } }; + const confirmLabel = loading + ? exportFormat === 'excel-daily' + ? t('semiFgGeneratingDailyExcel') + : exportFormat === 'excel' + ? t('generatingExcel') + : t('generatingPdf') + : exportFormat === 'excel-daily' + ? t('semiFgConfirmDailyExcel') + : exportFormat === 'excel' + ? t('confirmDownloadExcel') + : t('confirmDownloadPdf'); + return ( <>
@@ -126,7 +175,7 @@ export default function SemiFGProductionAnalysisReport({ disabled={loading} sx={{ px: 4 }} > - {loading ? t('generatingPdf') : t('downloadPdf')} + {loading && exportFormat === 'pdf' ? t('generatingPdf') : t('downloadPdf')} +
@@ -196,13 +258,7 @@ export default function SemiFGProductionAnalysisReport({ disabled={loading} startIcon={} > - {loading - ? exportFormat === 'excel' - ? t('generatingExcel') - : t('generatingPdf') - : exportFormat === 'excel' - ? t('confirmDownloadExcel') - : t('confirmDownloadPdf')} + {confirmLabel} diff --git a/src/app/(main)/report/page.tsx b/src/app/(main)/report/page.tsx index 89f442e8..06d4006d 100644 --- a/src/app/(main)/report/page.tsx +++ b/src/app/(main)/report/page.tsx @@ -26,7 +26,7 @@ import { import DownloadIcon from '@mui/icons-material/Download'; import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined'; import { REPORTS } from '@/config/reportConfig'; -import { mergePastedItemCodes, buildItemCodePasteRequestBody } from './parseItemCodeTokens'; +import { mergePastedItemCodes, buildItemCodePasteRequestBody, parseItemCodeTokens } from './parseItemCodeTokens'; import { NEXT_PUBLIC_API_URL } from '@/config/api'; import { clientAuthFetch } from '@/app/utils/clientAuthFetch'; import SemiFGProductionAnalysisReport from './SemiFGProductionAnalysisReport'; @@ -57,6 +57,21 @@ interface ItemCodeWithName { name: string; } +/** Months from the earliest ledger month through the current month. Value stays YYYY-MM-01. */ +function ledgerMonthOptions(isZh: boolean, earliest: string) { + const start = dayjs().startOf('month'); + let end = dayjs(earliest).startOf('month'); + if (!end.isValid() || end.isAfter(start)) end = start; + const count = start.diff(end, 'month') + 1; + return Array.from({ length: count }, (_, i) => { + const d = start.subtract(i, 'month'); + return { + value: d.format(OUTPUT_DATE_FORMAT), + label: isZh ? `${d.year()}年${d.month() + 1}月` : d.format('MMMM YYYY'), + }; + }); +} + const FIELD_ERROR_SX = { '& .MuiOutlinedInput-root.Mui-error': { '& .MuiOutlinedInput-notchedOutline': { @@ -86,8 +101,8 @@ const ITEM_CODE_PASTE_POST_REPORTS = new Set([ /** FP-MTMS Version Checklist | Functions Ref. No. 39 | v1.0.3 | 2026-09-10 */ /** FP-MTMS Version Checklist | Functions Ref. No. 60 | v1.0.1 | 2026-08-11 */ -/** FP-MTMS Version Checklist | Functions Ref. No. 69 | v1.0.2 | 2026-09-10 */ -/** FP-MTMS Version Checklist | Functions Ref. No. 82 | v1.0.0 | 2026-09-10 */ +/** FP-MTMS Version Checklist | Functions Ref. No. 69 | v1.0.3 | 2026-09-28 */ +/** FP-MTMS Version Checklist | Functions Ref. No. 82 | v1.0.1 | 2026-09-28 */ export default function ReportPage() { const { data: session } = useSession() as { data: SessionWithTokens | null }; const { t, i18n, reportTitle, fieldLabel, fieldHint, optionLabel } = useReportLabels(); @@ -97,7 +112,39 @@ export default function ReportPage() { session?.abilities?.includes(AUTH.ADMIN) ?? false; const [selectedReportId, setSelectedReportId] = useState(''); + const [ledgerEarliest, setLedgerEarliest] = useState<{ reportId: string; earliest: string } | null>(null); const [criteria, setCriteria] = useState>({}); + const criteriaRef = useRef>({}); + const pendingItemCodeInputRef = useRef>({}); + const updateCriteria = ( + updater: Record | ((prev: Record) => Record), + ) => { + const next = typeof updater === 'function' ? updater(criteriaRef.current) : updater; + criteriaRef.current = next; + setCriteria(next); + }; + /** Typed item codes are not in criteria until a dropdown option is chosen. Merge them in before the request. */ + const flushPendingItemCodeInputs = (): Record => { + const pendingEntries = Object.entries(pendingItemCodeInputRef.current).filter(([, raw]) => raw.trim()); + if (pendingEntries.length === 0) return criteriaRef.current; + + const next = { ...criteriaRef.current }; + let changed = false; + for (const [field, raw] of pendingEntries) { + pendingItemCodeInputRef.current[field] = ''; + const merged = parseItemCodeTokens([next[field], raw].filter(Boolean).join(' ')); + const joined = merged.join(','); + if (joined && joined !== (next[field] || '')) { + next[field] = joined; + changed = true; + } + } + if (changed) { + criteriaRef.current = next; + setCriteria(next); + } + return criteriaRef.current; + }; const [loading, setLoading] = useState(false); const excelInFlightRef = useRef(false); const [dynamicOptions, setDynamicOptions] = useState>({}); @@ -124,14 +171,15 @@ export default function ReportPage() { if (reportId === selectedReportId) return; setSelectedReportId(reportId); setFieldErrors({}); + pendingItemCodeInputRef.current = {}; if (reportId === 'rep-010') { - setCriteria({ qcType: 'all', qcItemScope: 'all' }); + updateCriteria({ qcType: 'all', qcItemScope: 'all' }); } else if (reportId === 'rep-004') { - setCriteria({ storeId: 'All', poPrefix: 'All' }); + updateCriteria({ storeId: 'All', poPrefix: 'All' }); } else if (reportId === 'rep-021') { - setCriteria({ storeId: 'All', stockTakeSectionDescription: 'All', lotOrigin: 'All' }); + updateCriteria({ storeId: 'All', stockTakeSectionDescription: 'All', lotOrigin: 'All' }); } else { - setCriteria({}); + updateCriteria({}); } }; @@ -143,7 +191,7 @@ export default function ReportPage() { delete next[name]; return next; }); - setCriteria((prev) => { + updateCriteria((prev) => { const next = { ...prev, [name]: stringValue }; if (currentReport?.id === 'rep-021' && name === 'warehouse') { const m = stringValue.trim().match(/^w(\d)/i); @@ -237,6 +285,32 @@ export default function ReportPage() { } }; + // Earliest stock_ledger month for the period-start list. Newest month is always the current month. + useEffect(() => { + const endpoint = currentReport?.fields.find( + (field) => field.type === 'month' && field.earliestMonthEndpoint, + )?.earliestMonthEndpoint; + if (!currentReport || !endpoint) return; + const reportId = currentReport.id; + let cancelled = false; + (async () => { + try { + const response = await clientAuthFetch(endpoint); + if (!response.ok) return; + const data = await response.json(); + const earliest = typeof data?.earliest === 'string' ? data.earliest : ''; + if (!cancelled && earliest) { + setLedgerEarliest({ reportId, earliest }); + } + } catch (error) { + console.error('Failed to load ledger months', error); + } + })(); + return () => { + cancelled = true; + }; + }, [currentReport]); + // Load initial options when report is selected useEffect(() => { if (currentReport) { @@ -252,7 +326,7 @@ export default function ReportPage() { // Default "All" (no filter) for stock take variance report conditions. if (selectedReportId === 'rep-012') { - setCriteria({ + updateCriteria({ store_id: 'All', status: 'All', type: 'All', @@ -264,7 +338,7 @@ export default function ReportPage() { useEffect(() => { if (selectedReportId !== 'rep-012' || !rep012MultiRound) return; if (criteria.status === 'completed') return; - setCriteria((prev) => ({ ...prev, status: 'completed' })); + updateCriteria((prev) => ({ ...prev, status: 'completed' })); }, [selectedReportId, rep012MultiRound, criteria.status]); // React 18 Strict Mode (dev) mounts → unmounts → remounts, so effects with [] run twice. @@ -329,19 +403,20 @@ export default function ReportPage() { /** rep-012:單輪送 status;多輪送 stockTakeRoundId 清單且 status=completed */ const buildRep012QueryString = (): string => { + const active = criteriaRef.current; const p = new URLSearchParams(); p.set('stockTakeRoundId', rep012RoundIds.join(',')); - const code = criteria.itemCode?.trim(); + const code = active.itemCode?.trim(); if (code) p.set('itemCode', code); - const store = criteria.store_id?.trim(); + const store = active.store_id?.trim(); if (store && store !== 'All') p.set('store_id', store); if (rep012MultiRound) { p.set('status', 'completed'); } else { - const status = criteria.status?.trim(); + const status = active.status?.trim(); if (status && status !== 'All') p.set('status', status); } - const lotType = criteria.type?.trim(); + const lotType = active.type?.trim(); if (lotType && lotType !== 'All') p.set('type', lotType); return p.toString(); }; @@ -349,15 +424,16 @@ export default function ReportPage() { /** FP-MTMS Version Checklist | Functions Ref. No. 64 | v1.0.0 | 2026-08-11 */ /** rep-010:qcItemScope → includeMeasurable / includeOther;qcType=all 不傳篩選 */ const buildRep010QueryString = (): string => { + const active = criteriaRef.current; const p = new URLSearchParams(); - Object.entries(criteria).forEach(([key, value]) => { + Object.entries(active).forEach(([key, value]) => { if (key === 'qcItemScope') return; if (key === 'qcType' && String(value).trim().toLowerCase() === 'all') return; if (value != null && String(value).trim() !== '') { p.set(key, String(value)); } }); - const scope = (criteria.qcItemScope || 'all').trim().toLowerCase(); + const scope = (active.qcItemScope || 'all').trim().toLowerCase(); if (scope === 'measurable') { p.set('includeMeasurable', 'true'); p.set('includeOther', 'false'); @@ -380,7 +456,7 @@ export default function ReportPage() { if (!currentReport) return ''; if (currentReport.id === 'rep-012') return buildRep012QueryString(); if (currentReport.id === 'rep-010') return buildRep010QueryString(); - const merged = mergePastedItemCodes(criteria, itemCodeFieldName()); + const merged = mergePastedItemCodes(criteriaRef.current, itemCodeFieldName()); const p = new URLSearchParams(merged); if (currentReport.id === 'rep-016') { const day = (merged.dateStart || '').trim(); @@ -393,6 +469,7 @@ export default function ReportPage() { }; const handlePrint = async () => { + flushPendingItemCodeInputs(); if (!currentReport) return; if (!validateRequiredFields()) return; @@ -409,6 +486,7 @@ export default function ReportPage() { }; const handleExcelPrint = async () => { + flushPendingItemCodeInputs(); if (!currentReport) return; if (!validateRequiredFields()) return; await executeExcelReport(); @@ -420,17 +498,18 @@ export default function ReportPage() { excelInFlightRef.current = true; setLoading(true); try { + const activeCriteria = criteriaRef.current; if (currentReport.id === 'rep-014') { await generateGrnReportExcel( - criteria, + activeCriteria, reportTitle(currentReport), includeGrnFinancialColumns, t, ); } else if (currentReport.id === 'rep-015') { - await generateBomShopSyncReportExcel(criteria, reportTitle(currentReport), t); + await generateBomShopSyncReportExcel(activeCriteria, reportTitle(currentReport), t); } else if (currentReport.id === 'rep-017') { - await generateShopOrderReplenishmentReportExcel(criteria, reportTitle(currentReport), t); + await generateShopOrderReplenishmentReportExcel(activeCriteria, reportTitle(currentReport), t); } else { // Backend returns actual .xlsx bytes for this Excel endpoint. const usesItemCodePastePost = isItemCodePastePostReport(); @@ -445,7 +524,7 @@ export default function ReportPage() { Accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'Content-Type': 'application/json', }, - body: JSON.stringify(buildItemCodePasteRequestBody(criteria, itemCodeFieldName())), + body: JSON.stringify(buildItemCodePasteRequestBody(criteriaRef.current, itemCodeFieldName())), } : { method: 'GET', @@ -514,7 +593,7 @@ export default function ReportPage() { Accept: 'application/pdf', 'Content-Type': 'application/json', }, - body: JSON.stringify(buildItemCodePasteRequestBody(criteria, itemCodeFieldName())), + body: JSON.stringify(buildItemCodePasteRequestBody(criteriaRef.current, itemCodeFieldName())), } : { method: 'GET', @@ -624,6 +703,50 @@ export default function ReportPage() { field.name === 'status' && rep012MultiRound; + if (field.type === 'month') { + const earliestForReport = + ledgerEarliest?.reportId === currentReport.id ? ledgerEarliest.earliest : ''; + const monthOptions = earliestForReport + ? ledgerMonthOptions(isZh, earliestForReport) + : []; + return ( + + handleFieldChange(field.name, e.target.value)} + sx={{ + ...FIELD_ERROR_SX, + ...(currentReport.id === 'rep-005' ? { + '& .MuiOutlinedInput-root': { + minHeight: '64px', + fontSize: '1rem' + }, + '& .MuiInputLabel-root': { + fontSize: '1rem' + } + } : {}), + }} + > + + {isZh ? '請選擇月份' : 'Select month'} + + {monthOptions.map((opt) => ( + + {opt.label} + + ))} + + + ); + } + if (field.type === 'date') { const parsed = currentValue ? dayjs(currentValue) : null; const dateError = fieldErrors[field.name]; @@ -692,7 +815,13 @@ export default function ReportPage() { label={translatedLabel} placeholder={field.placeholder || "e.g. FA0591"} value={selectedCodes} - onChange={(codes) => handleFieldChange(field.name, codes)} + onInputValueChange={(text) => { + pendingItemCodeInputRef.current[field.name] = text; + }} + onChange={(codes) => { + pendingItemCodeInputRef.current[field.name] = ""; + handleFieldChange(field.name, codes); + }} minChars={field.asyncSearchMinChars ?? 2} disabled={disabledByCheckedCheckbox || disabledRep012Status || !!field.disabled} /> @@ -711,8 +840,19 @@ export default function ReportPage() { opt.value)} value={autocompleteValue} + isOptionEqualToValue={(option, selected) => + String(option).toUpperCase() === String(selected).toUpperCase() + } + onInputChange={(_, input, reason) => { + if (reason === "reset" || reason === "clear") { + pendingItemCodeInputRef.current[field.name] = ""; + return; + } + pendingItemCodeInputRef.current[field.name] = input; + }} onChange={(event, newValue, reason) => { if (field.multiple) { // Handle multiple selection - newValue is an array @@ -895,6 +1035,7 @@ export default function ReportPage() { {currentReport.id === 'rep-005' ? ( f.required && !criteria[f.name]).map(f => fieldLabel(currentReport.id, f))} loading={loading} setLoading={setLoading} diff --git a/src/app/(main)/report/reportCategories.ts b/src/app/(main)/report/reportCategories.ts index 2b2f7aa7..f8c88e6a 100644 --- a/src/app/(main)/report/reportCategories.ts +++ b/src/app/(main)/report/reportCategories.ts @@ -17,7 +17,7 @@ export const REPORT_CATEGORIES: ReportCategoryConfig[] = [ headerBg: "#b8e0b8", bodyBg: "#eef8ee", accent: "#2e7d32", - reportIds: ["rep-011", "rep-007", "rep-012", "rep-021", "rep-010"], + reportIds: ["rep-011", "rep-020", "rep-007", "rep-012", "rep-021", "rep-010"], }, { id: "inbound-outbound", diff --git a/src/app/(main)/report/semiFGProductionAnalysisApi.ts b/src/app/(main)/report/semiFGProductionAnalysisApi.ts index e77636e5..0f7f845a 100644 --- a/src/app/(main)/report/semiFGProductionAnalysisApi.ts +++ b/src/app/(main)/report/semiFGProductionAnalysisApi.ts @@ -146,3 +146,53 @@ export const generateSemiFGProductionAnalysisReportExcel = async ( link.remove(); window.URL.revokeObjectURL(downloadUrl); }; + +/** + * Excel with one column per day in the selected production date range. + */ +export const generateSemiFGProductionAnalysisReportExcelDaily = async ( + criteria: Record, + reportTitle: string = '成品/半成品生產分析報告' +): Promise => { + const url = `${NEXT_PUBLIC_API_URL}/report/print-semi-fg-production-analysis-excel-daily`; + + const response = await clientAuthFetch(url, { + method: 'POST', + headers: { + Accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'Content-Type': 'application/json', + }, + body: JSON.stringify(buildItemCodePasteRequestBody(criteria, 'itemCode')), + }); + + if (response.status === 401 || response.status === 403) throw new Error('Unauthorized'); + if (!response.ok) throw new Error(await readReportErrorMessage(response)); + + const blob = await response.blob(); + const downloadUrl = window.URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = downloadUrl; + + const contentDisposition = response.headers.get('Content-Disposition'); + let fileName = `${reportTitle}_每日.xlsx`; + if (contentDisposition?.includes('filename=')) { + fileName = contentDisposition.split('filename=')[1].split(';')[0].replace(/"/g, ''); + } + + link.setAttribute('download', fileName); + document.body.appendChild(link); + link.click(); + link.remove(); + window.URL.revokeObjectURL(downloadUrl); +}; + +async function readReportErrorMessage(response: Response): Promise { + const text = await response.text(); + try { + const parsed = JSON.parse(text) as { message?: string }; + if (parsed.message) return parsed.message; + } catch { + // Response body is not JSON. + } + return text.trim(); +} diff --git a/src/app/(main)/settings/shop/layout.tsx b/src/app/(main)/settings/shop/layout.tsx new file mode 100644 index 00000000..357f7952 --- /dev/null +++ b/src/app/(main)/settings/shop/layout.tsx @@ -0,0 +1,27 @@ +import { I18nProvider } from "@/i18n"; +import { authOptions } from "@/config/authConfig"; +import { AUTH, hasAbility } from "@/authorities"; +import { getServerSession } from "next-auth"; +import { redirect } from "next/navigation"; + +/** Route board and shop/truck lane pages: ADMIN or 車線 (TRUCK_LANE). */ +export default async function ShopSettingsLayout({ + children, +}: { + children: React.ReactNode; +}) { + const session = await getServerSession(authOptions); + const abilities = session?.user?.abilities ?? []; + const canAccess = + hasAbility(abilities, AUTH.TRUCK_LANE) || hasAbility(abilities, AUTH.ADMIN); + + if (!canAccess) { + redirect("/dashboard"); + } + + return ( + + {children} + + ); +} diff --git a/src/app/(main)/settings/stockLedgerFix/page.tsx b/src/app/(main)/settings/stockLedgerFix/page.tsx new file mode 100644 index 00000000..d477b351 --- /dev/null +++ b/src/app/(main)/settings/stockLedgerFix/page.tsx @@ -0,0 +1,24 @@ +import { Metadata } from "next"; +import PageTitleBar from "@/components/PageTitleBar"; +import StockLedgerFixPageClient from "@/components/StockLedgerFix/StockLedgerFixPageClient"; +import { getServerI18n, I18nProvider } from "@/i18n"; + +export async function generateMetadata(): Promise { + const { t } = await getServerI18n("stockLedgerFix"); + return { title: t("pageTitle") }; +} + +const StockLedgerFixPage: React.FC = async () => { + const { t } = await getServerI18n("stockLedgerFix"); + + return ( + <> + + + + + + ); +}; + +export default StockLedgerFixPage; diff --git a/src/app/api/doworkbench/actions.ts b/src/app/api/doworkbench/actions.ts index 65af3d6e..60a0040d 100644 --- a/src/app/api/doworkbench/actions.ts +++ b/src/app/api/doworkbench/actions.ts @@ -216,7 +216,6 @@ export async function fetchWorkbenchStoreLaneSummary( return serverFetchJson(url, { method: "GET", cache: "no-store", - next: { revalidate: 0 }, }); } @@ -235,7 +234,6 @@ export async function fetchWorkbenchEtraLaneSummary( const data = await serverFetchJson(url, { method: "GET", cache: "no-store", - next: { revalidate: 0 }, }); return Array.isArray(data) ? data : []; } diff --git a/src/app/api/inventory/actions.ts b/src/app/api/inventory/actions.ts index d481eef9..196ba7f6 100644 --- a/src/app/api/inventory/actions.ts +++ b/src/app/api/inventory/actions.ts @@ -28,8 +28,12 @@ export interface LotLineInfo { export interface SearchInventoryLotLine extends Pageable { itemId: number; + uomId?: number; /** Non-expired lots with in > out; includes available and unavailable. */ stockIssueBadItem?: boolean; + storeId?: string; + warehouse?: string; + area?: string; } export interface SearchStockIssueBadItemLotLine extends Pageable { @@ -44,6 +48,9 @@ export interface SearchInventory extends Pageable { name: string; type: string; lotNo?: string; + storeId?: string; + warehouse?: string; + area?: string; } export interface InventoryResultByPage { @@ -161,6 +168,8 @@ async function fetchInventoriesImpl(data: SearchInventory) { ); } +export const fetchInventories = cache(fetchInventoriesImpl); + async function fetchInventoriesLatestImpl(data: SearchInventory) { const queryStr = convertObjToURLSearchParams(data); return serverFetchJson( @@ -169,12 +178,7 @@ async function fetchInventoriesLatestImpl(data: SearchInventory) { ); } -export const fetchInventories = cache(fetchInventoriesImpl); - -/** - * FP-MTMS Version Checklist | Functions Ref. No. 18 | v1.0.5 | 2026-09-21 - * Inventory search page: latest inventory row per item (no baseUnit/uomId filter). - */ +/** Location Search: lot-line grouped by item + stock UoM, with optional location filters. */ export const fetchInventoriesLatest = cache(fetchInventoriesLatestImpl); /** Bypass React cache() after mutations so lists show fresh qty. */ @@ -182,7 +186,7 @@ export async function fetchInventoriesFresh(data: SearchInventory) { return fetchInventoriesImpl(data); } -/** Bypass React cache() for inventory search page latest-inventory search. */ +/** Bypass React cache() for Location Search (searchLatest). */ export async function fetchInventoriesLatestFresh(data: SearchInventory) { return fetchInventoriesLatestImpl(data); } @@ -195,6 +199,7 @@ async function fetchInventoryLotLinesImpl(data: SearchInventoryLotLine) { ); } +/** FP-MTMS Version Checklist | Functions Ref. No. 18 | v1.0.4 | 2026-09-10 */ export const fetchInventoryLotLines = cache(fetchInventoryLotLinesImpl); /** Bypass React cache() after mutations so lists show fresh qty. */ diff --git a/src/app/api/inventory/index.ts b/src/app/api/inventory/index.ts index 869bed2e..74a7bb52 100644 --- a/src/app/api/inventory/index.ts +++ b/src/app/api/inventory/index.ts @@ -14,6 +14,10 @@ export interface InventoryResult { onHoldQty: number; unavailableQty: number; availableQty: number; + /** Item Search / getRecordByPage (inventory bucket). */ + stockUomId?: number | null; + /** Location Search / searchLatest (lot-line grouped row). Same UOM id space as stockUomId. */ + uomId?: number; uomCode: string; uomUdfudesc: string; uomShortDesc: string; diff --git a/src/app/api/inventory/inventoryBucket.ts b/src/app/api/inventory/inventoryBucket.ts new file mode 100644 index 00000000..52b6199c --- /dev/null +++ b/src/app/api/inventory/inventoryBucket.ts @@ -0,0 +1,82 @@ +/** Keys used to pick one inventory row when an item has multiple stock-UOM buckets. */ +export type InventoryBucketPick = { + itemId?: number | null; + itemCode?: string | null; + itemName?: string | null; + uomId?: number | null; + stockUomId?: number | null; + uom?: string | null; + shortUom?: string | null; + stockUom?: string | null; +}; + +export type InventoryBucketRow = { + itemId?: number | null; + itemCode?: string | null; + itemName?: string | null; + stockUomId?: number | null; + uomCode?: string | null; + uomUdfudesc?: string | null; + uomShortDesc?: string | null; + availableQty?: number | null; + onHandQty?: number | null; + unavailableQty?: number | null; +}; + +const norm = (s?: string | null) => (s ?? "").trim().toLowerCase(); + +/** Available = onHand − unavailable. Do not treat 0 as missing (`||` is wrong). */ +export function inventoryAvailableQty(inv: InventoryBucketRow): number { + if (inv.availableQty != null && !Number.isNaN(Number(inv.availableQty))) { + return Number(inv.availableQty); + } + return Number(inv.onHandQty ?? 0) - Number(inv.unavailableQty ?? 0); +} + +function itemMatches(inv: InventoryBucketRow, pick: InventoryBucketPick): boolean { + if (pick.itemId != null && inv.itemId != null) { + return Number(inv.itemId) === Number(pick.itemId); + } + if (pick.itemCode && inv.itemCode) { + return inv.itemCode === pick.itemCode; + } + if (pick.itemName && inv.itemName) { + return inv.itemName === pick.itemName; + } + return false; +} + +function uomMatches(inv: InventoryBucketRow, pick: InventoryBucketPick): boolean { + const pickUomId = pick.stockUomId ?? pick.uomId; + if (pickUomId != null && inv.stockUomId != null) { + return Number(inv.stockUomId) === Number(pickUomId); + } + const labels = [pick.uom, pick.shortUom, pick.stockUom].map(norm).filter(Boolean); + if (labels.length === 0) return true; + const invLabels = [inv.uomUdfudesc, inv.uomShortDesc, inv.uomCode].map(norm); + return labels.some((l) => invLabels.includes(l)); +} + +export function matchInventoryBucket( + inventories: InventoryBucketRow[], + pick: InventoryBucketPick, +): InventoryBucketRow | undefined { + const itemHits = inventories.filter((inv) => itemMatches(inv, pick)); + if (itemHits.length === 0) return undefined; + const hasUomPick = + pick.stockUomId != null || + pick.uomId != null || + [pick.uom, pick.shortUom, pick.stockUom].some((s) => Boolean(norm(s))); + if (hasUomPick) { + return itemHits.find((inv) => uomMatches(inv, pick)); + } + return itemHits[0]; +} + +export function getStockAvailableFromInventories( + inventories: InventoryBucketRow[], + pick: InventoryBucketPick, +): number { + const inv = matchInventoryBucket(inventories, pick); + return inv ? inventoryAvailableQty(inv) : 0; +} diff --git a/src/app/api/itemTracing/schema.ts b/src/app/api/itemTracing/schema.ts index edf0774b..3bbb3fd4 100644 --- a/src/app/api/itemTracing/schema.ts +++ b/src/app/api/itemTracing/schema.ts @@ -85,7 +85,7 @@ const ItemLotTraceMaterialInputSchema: z.ZodType> = z.la consoCode: z.string(), pickedAt: nullableStr, stockInOrigin: ItemLotTraceOriginSchema.nullable().optional(), - purchaseEvents: z.array(z.record(z.unknown())).optional(), + purchaseEvents: z.array(z.record(z.string(), z.unknown())).optional(), qcResults: z.array(ItemLotTraceQcResultSchema), putawayEvents: z.array(ItemLotTracePutawayEventSchema).optional(), nestedJoPrelude: ItemLotTraceJoPreludeSchema.nullable().optional(), @@ -107,7 +107,7 @@ const ItemLotTraceJoPreludeSchema: z.ZodType> = z.lazy(( status: z.string(), }) .passthrough(), - pickOrders: z.array(z.record(z.unknown())), + pickOrders: z.array(z.record(z.string(), z.unknown())), materialInputs: z.array(ItemLotTraceMaterialInputSchema), }) .passthrough(), @@ -158,28 +158,28 @@ export const ItemLotTraceResponseSchema = z primaryStockInLineId: nullableNum, }) .passthrough(), - warehouseLines: z.array(z.record(z.unknown())), + warehouseLines: z.array(z.record(z.string(), z.unknown())), origins: z.array(ItemLotTraceOriginSchema), - purchaseEvents: z.array(z.record(z.unknown())).optional(), + purchaseEvents: z.array(z.record(z.string(), z.unknown())).optional(), qcResults: z.array(ItemLotTraceQcResultSchema), putawayEvents: z.array(ItemLotTracePutawayEventSchema), - movements: z.array(z.record(z.unknown())), - outboundUsage: z.array(z.record(z.unknown())), - stockTakeEvents: z.array(z.record(z.unknown())), - adjustments: z.array(z.record(z.unknown())), - transfers: z.array(z.record(z.unknown())), - bomTrace: z.record(z.unknown()), + movements: z.array(z.record(z.string(), z.unknown())), + outboundUsage: z.array(z.record(z.string(), z.unknown())), + stockTakeEvents: z.array(z.record(z.string(), z.unknown())), + adjustments: z.array(z.record(z.string(), z.unknown())), + transfers: z.array(z.record(z.string(), z.unknown())), + bomTrace: z.record(z.string(), z.unknown()), joPrelude: ItemLotTraceJoPreludeSchema.nullable(), productionSteps: z.array(ItemLotTraceProductionStepSchema), - byproductLots: z.array(z.record(z.unknown())), - openMovements: z.array(z.record(z.unknown())), - failEvents: z.array(z.record(z.unknown())), - doDeliveries: z.array(z.record(z.unknown())), - replenishmentEvents: z.array(z.record(z.unknown())).optional(), - returnEvents: z.array(z.record(z.unknown())), - lotRelations: z.array(z.record(z.unknown())), - alternateLocations: z.array(z.record(z.unknown())), - locationBlocks: z.array(z.record(z.unknown())).optional(), + byproductLots: z.array(z.record(z.string(), z.unknown())), + openMovements: z.array(z.record(z.string(), z.unknown())), + failEvents: z.array(z.record(z.string(), z.unknown())), + doDeliveries: z.array(z.record(z.string(), z.unknown())), + replenishmentEvents: z.array(z.record(z.string(), z.unknown())).optional(), + returnEvents: z.array(z.record(z.string(), z.unknown())), + lotRelations: z.array(z.record(z.string(), z.unknown())), + alternateLocations: z.array(z.record(z.string(), z.unknown())), + locationBlocks: z.array(z.record(z.string(), z.unknown())).optional(), traceGraph: ItemLotTraceGraphSchema, }) .passthrough(); diff --git a/src/app/api/jo/actions.ts b/src/app/api/jo/actions.ts index 75efe315..8153f8cd 100644 --- a/src/app/api/jo/actions.ts +++ b/src/app/api/jo/actions.ts @@ -533,6 +533,7 @@ export interface JobOrderLineInfo { stockUom: string, stockBaseUom: string, + stockUomId?: number | null, availableStatus: string, bomProcessId: number, @@ -905,7 +906,7 @@ export const fetchAllJoborderProductProcessInfo = cache(async (type?: string | n ); }); -/** FP-MTMS Version Checklist | Functions Ref. No. 40 | v1.0.7 | 2026-08-06 */ +/** FP-MTMS Version Checklist | Functions Ref. No. 40 | v1.0.11 | 2026-10-29 */ export const fetchJoborderProductProcessesPage = cache(async (params: { /** Job order / process date(YYYY-MM-DD) */ date?: string | null; diff --git a/src/app/api/jo/index.ts b/src/app/api/jo/index.ts index ed8b99f4..67bd46e7 100644 --- a/src/app/api/jo/index.ts +++ b/src/app/api/jo/index.ts @@ -67,6 +67,8 @@ export interface JoDetail { export interface JoDetailPickLine { id: number; + itemId?: number; + uomId?: number; code: string; name: string; type: string; diff --git a/src/app/api/pickOrder/actions.ts b/src/app/api/pickOrder/actions.ts index f21a60b4..25409697 100644 --- a/src/app/api/pickOrder/actions.ts +++ b/src/app/api/pickOrder/actions.ts @@ -632,7 +632,6 @@ export async function fetchStoreLaneSummary(storeId: string, requiredDate?: stri const response = await serverFetchJson(url, { method: "GET", cache: "no-store", - next: { revalidate: 0 }, }); console.timeEnd(label); return response; @@ -856,7 +855,6 @@ export const fetchFGPickOrdersByUserIdWorkbench = async (userId: number) => { method: "GET", // Must be fresh: determines whether shell shows Floor/Lane panel or Detail. cache: "no-store", - next: { revalidate: 0 }, }, ); }; diff --git a/src/app/api/settings/item/index.ts b/src/app/api/settings/item/index.ts index e85933e0..f23c1145 100644 --- a/src/app/api/settings/item/index.ts +++ b/src/app/api/settings/item/index.ts @@ -66,6 +66,9 @@ export type ItemsResult = { latestMarketUnitPrice?: number; latestMupUpdatedDate?: string; purchaseUnit?: string; + uomId?: number; + uom?: string; + uomDesc?: string; }; export type Result = { diff --git a/src/app/api/shop/actions.ts b/src/app/api/shop/actions.ts index abea44e1..aa9bc199 100644 --- a/src/app/api/shop/actions.ts +++ b/src/app/api/shop/actions.ts @@ -924,4 +924,78 @@ export const importTruckLaneScheduleExcelAction = async ( ); } return (await response.json()) as TruckLaneScheduleResponse[]; +}; + +export interface PreviewTruckLaneRenameRequest { + truckLanceCode: string; + storeId: string; + remark?: string | null; +} + +export interface PreviewTruckLaneRenameResponse { + unfinishedCount: number; + completedCount: number; + handlerNames: string[]; + openScheduleCount: number; +} + +export interface RenameTruckLaneRequest { + truckLanceCode: string; + storeId: string; + remark?: string | null; + newTruckLanceCode: string; + departureTimeChanged: boolean; + newDepartureTime?: string | null; +} + +export interface RenameTruckLaneResponse { + truckLanceCode: string; + ticketCount: number; + scheduleLineCount: number; +} + +export interface TruckLaneRenameLogResponse { + id: number; + created?: string | null; + createdBy?: string | null; + oldCode: string; + newCode: string; + storeId: string; + remark?: string | null; + oldDepartureTime?: string | null; + newDepartureTime?: string | null; + ticketCount: number; + /** `truck.id` of shops in the renamed lane, comma-separated. */ + truckIds?: string | null; +} + +export const previewTruckLaneRenameAction = async ( + data: PreviewTruckLaneRenameRequest, +) => { + return serverFetchJson( + `${BASE_API_URL}/truck/previewTruckLaneRename`, + { + method: "POST", + body: JSON.stringify(data), + headers: { "Content-Type": "application/json" }, + }, + ); +}; + +export const renameTruckLaneAction = async (data: RenameTruckLaneRequest) => { + return serverFetchJson( + `${BASE_API_URL}/truck/renameTruckLane`, + { + method: "POST", + body: JSON.stringify(data), + headers: { "Content-Type": "application/json" }, + }, + ); +}; + +export const listTruckLaneRenameLogsAction = async () => { + return serverFetchJson( + `${BASE_API_URL}/truck/truckLaneRenameLog`, + { method: "GET", headers: { "Content-Type": "application/json" } }, + ); }; \ No newline at end of file diff --git a/src/app/api/shop/client.ts b/src/app/api/shop/client.ts index 67963e27..80356270 100644 --- a/src/app/api/shop/client.ts +++ b/src/app/api/shop/client.ts @@ -66,7 +66,12 @@ import { type SaveTruckRequest, type UpdateTruckShopDetailsRequest, type CreateTruckWithoutShopRequest, - type MessageResponse + type MessageResponse, + previewTruckLaneRenameAction, + renameTruckLaneAction, + listTruckLaneRenameLogsAction, + type PreviewTruckLaneRenameRequest, + type RenameTruckLaneRequest, } from "./actions"; export const fetchAllShopsClient = async (params?: Record) => { @@ -276,6 +281,20 @@ export const parseTruckLaneScheduleExcelClient = async ( return await parseTruckLaneScheduleExcelAction(formData, defaultExecuteAt); }; +export const previewTruckLaneRenameClient = async ( + data: PreviewTruckLaneRenameRequest, +) => { + return await previewTruckLaneRenameAction(data); +}; + +export const renameTruckLaneClient = async (data: RenameTruckLaneRequest) => { + return await renameTruckLaneAction(data); +}; + +export const listTruckLaneRenameLogsClient = async () => { + return await listTruckLaneRenameLogsAction(); +}; + export const importTruckLaneScheduleExcelClient = async ( formData: FormData, defaultExecuteAt?: string | null, diff --git a/src/app/api/stockAdjustment/actions.ts b/src/app/api/stockAdjustment/actions.ts index c42e0c09..f7742248 100644 --- a/src/app/api/stockAdjustment/actions.ts +++ b/src/app/api/stockAdjustment/actions.ts @@ -16,6 +16,7 @@ export interface StockAdjustmentLineRequest { expiryDate: string; warehouseId: number; uom?: string | null; + uomId?: number | null; remarks?: string | null; } diff --git a/src/app/api/stockLedgerFix/client.ts b/src/app/api/stockLedgerFix/client.ts new file mode 100644 index 00000000..805806ec --- /dev/null +++ b/src/app/api/stockLedgerFix/client.ts @@ -0,0 +1,284 @@ +"use client"; + +import axiosInstance from "@/app/(main)/axios/axiosInstance"; +import { NEXT_PUBLIC_API_URL } from "@/config/api"; + +export type StockLedgerFixDayStatus = { + date: string; + cnt: number; + missLot: number; + missUom: number; + missInventoryId: number; + missLotQty: number; + dayTableLots: number; +}; + +export type StockLedgerFixCalendarResponse = { + from: string; + to: string; + days: StockLedgerFixDayStatus[]; +}; + +export type StockLedgerFixCheckPart = { + key: string; + label: string; + ok: number; + miss: number; + incorrect: number; + group?: string; +}; + +export type StockLedgerFixDayDetail = { + date: string; + cnt: number; + parts: StockLedgerFixCheckPart[]; +}; + +export type StockLedgerFixRunResponse = { + date: string; + filledLotLineId: number; + filledUomId: number; + filledInventoryId: number; + filledLotQty: number; + filledBalance: number; + dayRowsWritten: number; + stillMissLot: number; + stillMissUom: number; + stillMissInventoryId: number; + stillMissLotQty: number; + deletedUnlinkedLot?: number; + existingLotMatch?: number; + existingLotMismatch?: number; + deletedBlankOutLine?: number; + alignedOutLine?: number; +}; + +export type StockLedgerFixInventoryPreview = { + inventoryRows: number; + lotUomPairs: number; + missingUomPairs: number; + nullStockUomId: number; +}; + +export type StockLedgerFixInventoryResponse = { + inserted: number; + updated: number; + missingUomPairsAfter: number; + patchedStockUomId: number; + nullStockUomIdAfter: number; + orphansDeleted?: number; + outQtyNulledToZero?: number; +}; + +export type StockLedgerFixSearchInventoryHit = { + inventoryId: number; + itemId: number | null; + itemCode: string | null; + uomId: number | null; + ledgerCnt: number; +}; + +export type StockLedgerFixSearchLotHit = { + inventoryLotLineId: number; + lotNo: string | null; + itemCode: string | null; + inventoryId: number | null; + ledgerCnt: number; +}; + +export type StockLedgerFixScopeDetail = { + kind: string; + id: number; + itemCode: string | null; + lotNo: string | null; + inventoryId: number | null; + uomId: number | null; + firstDate: string | null; + lastDate: string | null; + cnt: number; + lastBalance: string | null; + lastLotQtyAfter: string | null; + parts: StockLedgerFixCheckPart[]; +}; + +export type StockLedgerFixAdjResponse = { + adjDate: string; + insertedIn: number; + insertedOut: number; + overIssuePatched: number; + filledLotQty: number; + filledBalance: number; + dayRowsWritten: number; + adjustmentRecords?: number; +}; + +export async function runStockLedgerFixAdj( + adjDate?: string, + step?: "2.7a" | "2.7b", +): Promise { + const response = await axiosInstance.post( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/adj`, + { ...(adjDate ? { adjDate } : {}), ...(step ? { step } : {}) }, + { timeout: 1200000 }, + ); + return response.data; +} + +export async function fetchStockLedgerFixCalendar( + from: string, + to: string, +): Promise { + const response = await axiosInstance.get( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/calendar`, + { params: { from, to } }, + ); + return response.data; +} + +export async function fetchStockLedgerFixDay( + date: string, +): Promise { + const response = await axiosInstance.get( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/day`, + { params: { date } }, + ); + return response.data; +} + +export async function runStockLedgerFixDay( + date: string, + steps?: string[], +): Promise { + const response = await axiosInstance.post( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/run`, + { date, ...(steps && steps.length > 0 ? { steps } : {}) }, + ); + return response.data; +} + +export async function runStockLedgerFixRange( + from: string, + to: string, + steps?: string[], +): Promise { + const response = await axiosInstance.post( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/run`, + { + mode: "range", + from, + to, + ...(steps && steps.length > 0 ? { steps } : {}), + }, + { timeout: 1200000 }, + ); + return response.data; +} + +export async function fetchStockLedgerFixInventory(): Promise { + const response = await axiosInstance.get( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/inventory`, + ); + return response.data; +} + +export async function runStockLedgerFixInventory(): Promise { + const response = await axiosInstance.post( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/inventory`, + ); + return response.data; +} + +export async function searchStockLedgerFixInventory( + q: string, +): Promise { + const response = await axiosInstance.get( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/lookup/inventory`, + { params: { q } }, + ); + return response.data; +} + +export async function searchStockLedgerFixLot( + q: string, +): Promise { + const response = await axiosInstance.get( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/lookup/lot`, + { params: { q } }, + ); + return response.data; +} + +export async function fetchStockLedgerFixInventoryScope( + id: number, +): Promise { + const response = await axiosInstance.get( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/scope/inventory`, + { params: { id } }, + ); + return response.data; +} + +export async function fetchStockLedgerFixLotScope( + id: number, +): Promise { + const response = await axiosInstance.get( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/scope/lot`, + { params: { id } }, + ); + return response.data; +} + +export async function runStockLedgerFixInventoryScope( + inventoryId: number, +): Promise { + const response = await axiosInstance.post( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/run`, + { mode: "inventory", inventoryId }, + ); + return response.data; +} + +export async function runStockLedgerFixLotScope( + lotLineId: number, +): Promise { + const response = await axiosInstance.post( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/run`, + { mode: "lot", lotLineId }, + ); + return response.data; +} + +export async function downloadStockLedgerFixSql( + from: string, + to: string, + parts?: string[], +): Promise { + const response = await axiosInstance.get( + `${NEXT_PUBLIC_API_URL}/stock-ledger-fix/export`, + { + params: { + from, + to, + ...(parts && parts.length > 0 ? { parts } : {}), + }, + paramsSerializer: { + indexes: null, + }, + responseType: "blob", + timeout: 600000, + }, + ); + const blob = new Blob([response.data], { type: "application/sql;charset=utf-8" }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + const partTag = + parts && parts.length > 0 && parts.length < 6 + ? `_${parts.join("-").replaceAll(".", "")}` + : ""; + a.download = `stock_ledger_fix_${from.replaceAll("-", "")}_${to.replaceAll("-", "")}${partTag}.sql`; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); +} diff --git a/src/app/api/stockTake/actions.ts b/src/app/api/stockTake/actions.ts index f674efe0..e588dc4c 100644 --- a/src/app/api/stockTake/actions.ts +++ b/src/app/api/stockTake/actions.ts @@ -24,6 +24,8 @@ export interface InventoryLotDetailResponse { holdQty: number; availableQty: number; uom: string; + /** Stock UoM short label (e.g. 包) for the count input. */ + uomShortDesc?: string | null; warehouseCode: string; warehouseName: string; warehouseSlot: string; @@ -51,6 +53,8 @@ export interface InventoryLotDetailResponse { stockTakeEndTime?: string | string[] | null; /** ISO string or backend LocalDateTime array */ approverTime?: string | string[] | null; + /** Times this saved first count has been changed. */ + pickerReviseCount?: number | null; } /** @@ -122,6 +126,8 @@ export interface SaveStockTakeRecordRequest { badQty: number; //stockTakerName: string; remark?: string | null; + /** Overwrite the saved first count while the section is still stock-taking. */ + reviseFirstQty?: boolean; } export interface AllPickedStockTakeListReponse { id: number; diff --git a/src/app/utils/authToken.ts b/src/app/utils/authToken.ts index 7dc3a48b..8f00cf5b 100644 --- a/src/app/utils/authToken.ts +++ b/src/app/utils/authToken.ts @@ -1,11 +1,19 @@ /** * Client-side helpers for the backend JWT stored in localStorage (`accessToken`). - * Used to detect expiry before API calls so pages like /report can redirect early. + * Used to detect expiry before API calls and to refresh via /refresh-token. */ +import { NEXT_PUBLIC_API_URL } from "@/config/api"; + /** Must match clientAuthFetch redirect target */ export const LOGIN_SESSION_EXPIRED_HREF = "/login?session=expired"; +export const ACCESS_TOKEN_KEY = "accessToken"; +export const REFRESH_TOKEN_KEY = "refreshToken"; + +/** Refresh when fewer than this many seconds remain on the access token. */ +export const ACCESS_TOKEN_REFRESH_SKEW_SECONDS = 5 * 60; + /** * Decode JWT payload (no signature verification — UX only; server still validates). */ @@ -30,12 +38,143 @@ export function decodeJwtPayload( } } +/** Seconds until JWT `exp`, or null if missing/unreadable. Negative if already expired. */ +export function getBackendJwtSecondsRemaining(token: string): number | null { + const payload = decodeJwtPayload(token); + const exp = payload?.exp; + if (typeof exp !== "number") return null; + return exp - Date.now() / 1000; +} + /** * True if `exp` claim is reached or passed. False if no `exp` (let API decide). */ export function isBackendJwtExpired(token: string): boolean { - const payload = decodeJwtPayload(token); - const exp = payload?.exp; - if (typeof exp !== "number") return false; - return Date.now() / 1000 >= exp; + const remaining = getBackendJwtSecondsRemaining(token); + if (remaining === null) return false; + return remaining <= 0; +} + +/** True when token should be refreshed soon (or is already expired). */ +export function isBackendJwtExpiringSoon( + token: string, + skewSeconds: number = ACCESS_TOKEN_REFRESH_SKEW_SECONDS +): boolean { + const remaining = getBackendJwtSecondsRemaining(token); + if (remaining === null) return false; + return remaining <= skewSeconds; +} + +export function persistBackendTokens( + accessToken: string, + refreshToken?: string | null +): void { + if (typeof window === "undefined") return; + try { + localStorage.setItem(ACCESS_TOKEN_KEY, accessToken); + if (refreshToken) { + localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken); + } + } catch { + // ignore (e.g. private mode) + } +} + +export function clearBackendTokens(): void { + if (typeof window === "undefined") return; + try { + localStorage.removeItem(ACCESS_TOKEN_KEY); + localStorage.removeItem(REFRESH_TOKEN_KEY); + } catch { + // ignore + } +} + +export function readStoredRefreshToken(): string | null { + if (typeof window === "undefined") return null; + try { + return localStorage.getItem(REFRESH_TOKEN_KEY)?.trim() || null; + } catch { + return null; + } +} + +type RefreshResponse = { + accessToken?: string; + refreshToken?: string; +}; + +let refreshInFlight: Promise | null = null; + +/** + * Call backend `/refresh-token`. Returns new access token, or null if refresh failed. + * Single-flight: concurrent callers share one request. + */ +export async function refreshBackendAccessToken( + refreshTokenOverride?: string | null +): Promise { + if (refreshInFlight) return refreshInFlight; + + refreshInFlight = (async () => { + const refreshToken = + refreshTokenOverride?.trim() || readStoredRefreshToken(); + if (!refreshToken) return null; + + const base = (NEXT_PUBLIC_API_URL ?? "").replace(/\/$/, ""); + if (!base) { + console.warn("refreshBackendAccessToken: NEXT_PUBLIC_API_URL missing"); + return null; + } + + try { + const res = await fetch(`${base}/refresh-token`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ refreshToken }), + }); + if (!res.ok) { + console.warn("refresh-token failed", res.status); + return null; + } + const data = (await res.json()) as RefreshResponse; + if (!data.accessToken) return null; + persistBackendTokens(data.accessToken, data.refreshToken ?? refreshToken); + return data.accessToken; + } catch (e) { + console.warn("refresh-token error", e); + return null; + } + })().finally(() => { + refreshInFlight = null; + }); + + return refreshInFlight; +} + +/** + * Ensure a non-expired access token is in localStorage. + * Tries refresh when missing/expired/near expiry. Returns the token to use, or null. + */ +export async function ensureFreshAccessToken( + refreshTokenFallback?: string | null +): Promise { + if (typeof window === "undefined") return null; + + let token = ""; + try { + token = localStorage.getItem(ACCESS_TOKEN_KEY)?.trim() ?? ""; + } catch { + token = ""; + } + + if (token && !isBackendJwtExpiringSoon(token)) { + return token; + } + + const refreshed = await refreshBackendAccessToken(refreshTokenFallback); + if (refreshed) return refreshed; + + // Refresh failed: if current token still valid (not yet expired), keep using it + if (token && !isBackendJwtExpired(token)) return token; + return null; } diff --git a/src/app/utils/clientAuthFetch.ts b/src/app/utils/clientAuthFetch.ts index 67ed99a9..659442ce 100644 --- a/src/app/utils/clientAuthFetch.ts +++ b/src/app/utils/clientAuthFetch.ts @@ -1,28 +1,55 @@ "use client"; -import { LOGIN_SESSION_EXPIRED_HREF } from "@/app/utils/authToken"; +import { + clearBackendTokens, + ensureFreshAccessToken, + LOGIN_SESSION_EXPIRED_HREF, + readStoredRefreshToken, + refreshBackendAccessToken, +} from "@/app/utils/authToken"; +import { getSession } from "next-auth/react"; +import { SessionWithTokens } from "@/config/authConfig"; + +async function resolveRefreshTokenFallback(): Promise { + const stored = readStoredRefreshToken(); + if (stored) return stored; + const session = (await getSession()) as SessionWithTokens | null; + return session?.refreshToken ?? null; +} /** - * Client-side fetch that adds Bearer token from localStorage and redirects - * to /login?session=expired on 401 or 403 (session timeout / unauthorized). - * Use this for all authenticated API requests so session expiry is handled consistently. + * Client-side fetch that adds Bearer token from localStorage. + * On 401, tries one refresh + retry; only then redirects to login. + * 403 (forbidden) is NOT treated as session expiry. */ export async function clientAuthFetch( input: RequestInfo | URL, init?: RequestInit ): Promise { - const token = - typeof window !== "undefined" ? localStorage.getItem("accessToken") : null; + let token = await ensureFreshAccessToken(readStoredRefreshToken()); + if (!token) { + token = await ensureFreshAccessToken(await resolveRefreshTokenFallback()); + } + const headers = new Headers(init?.headers); if (token) { headers.set("Authorization", `Bearer ${token}`); } - const response = await fetch(input, { ...init, headers }); + let response = await fetch(input, { ...init, headers }); + + if (response.status === 401) { + const refreshed = await refreshBackendAccessToken( + await resolveRefreshTokenFallback() + ); + if (refreshed) { + headers.set("Authorization", `Bearer ${refreshed}`); + response = await fetch(input, { ...init, headers }); + } - if (response.status === 401 || response.status === 403) { - if (typeof window !== "undefined") { - console.warn(`Auth error ${response.status} → redirecting to login`); + if (response.status === 401 && typeof window !== "undefined") { + console.warn("Auth error 401 → redirecting to login"); + clearBackendTokens(); window.location.href = LOGIN_SESSION_EXPIRED_HREF; } } diff --git a/src/app/utils/fetchUtil.ts b/src/app/utils/fetchUtil.ts index aa445854..22327ebc 100644 --- a/src/app/utils/fetchUtil.ts +++ b/src/app/utils/fetchUtil.ts @@ -24,6 +24,27 @@ export interface searchParamsProps { searchParams: { [key: string]: string | string[] | undefined }; } +/** Prefer API `error` / `message` so SIGNAL 400s show the Chinese reason, not a traceId. */ +function userMessageFromErrorBody(body: string, fallback: string): string { + const trimmed = body.trim(); + if (!trimmed) return fallback; + try { + const errorJson = JSON.parse(trimmed) as { + error?: unknown; + message?: unknown; + }; + if (typeof errorJson.error === "string" && errorJson.error.trim()) { + return errorJson.error.trim(); + } + if (typeof errorJson.message === "string" && errorJson.message.trim()) { + return errorJson.message.trim(); + } + } catch { + return trimmed; + } + return trimmed; +} + export async function serverFetchWithNoContent(...args: FetchParams) { const response = await serverFetch(...args); @@ -57,7 +78,7 @@ export async function serverFetchWithNoContent(...args: FetchParams) { } console.error(`Server error (${response.status}):`, errorMessage); throw new ServerFetchError( - `Server error: ${response.status} ${response.statusText}. ${errorMessage}`, + userMessageFromErrorBody(errorMessage, errorMessage), response ); } @@ -107,7 +128,10 @@ export async function serverFetchJson(...args: FetchParams) { signOutUser(); default: throw new ServerFetchError( - `Server error: ${response.status} ${response.statusText}. ${errorText}`, + userMessageFromErrorBody( + errorText, + `Server error: ${response.status} ${response.statusText}`, + ), response, ); } diff --git a/src/authorities.ts b/src/authorities.ts index ad4aeb9e..b601e86f 100644 --- a/src/authorities.ts +++ b/src/authorities.ts @@ -27,6 +27,10 @@ export const AUTH = { REPORT_MGMT: "REPORT_MGMT", /** FP-MTMS Version Checklist | Functions Ref. No. 67 | v1.0.0 | 2026-08-13 — Manual M18 sync page (/m18Syn): ADMIN or this ability */ M18_SYNC: "M18_SYNC", + /** Route board (/settings/shop/board): ADMIN or this ability (DB name: 車線) */ + TRUCK_LANE: "TRUCK_LANE", + /** 員工發貨績效 on /chart/delivery (DB name: 績效) */ + PERFORMANCE: "PERFORMANCE", } as const; /** diff --git a/src/components/AppBar/Profile.tsx b/src/components/AppBar/Profile.tsx index f5d7fdde..921d6101 100644 --- a/src/components/AppBar/Profile.tsx +++ b/src/components/AppBar/Profile.tsx @@ -10,6 +10,7 @@ import Divider from "@mui/material/Divider"; import Typography from "@mui/material/Typography"; import { useTranslation } from "react-i18next"; import { signOut } from "next-auth/react"; +import { clearBackendTokens } from "@/app/utils/authToken"; type Props = Pick; @@ -51,7 +52,13 @@ const Profile: React.FC = ({ avatarImageSrc, profileName }) => { {profileName} - signOut()} sx={{ py: 1.5, fontSize: "0.875rem" }}> + { + clearBackendTokens(); + void signOut(); + }} + sx={{ py: 1.5, fontSize: "0.875rem" }} + > {t("Sign out")} diff --git a/src/components/Breadcrumb/Breadcrumb.tsx b/src/components/Breadcrumb/Breadcrumb.tsx index a5804a95..cea41b5e 100644 --- a/src/components/Breadcrumb/Breadcrumb.tsx +++ b/src/components/Breadcrumb/Breadcrumb.tsx @@ -35,6 +35,7 @@ const pathToLabelKey: { [path: string]: string } = { "/settings/qrCodeHandle": "nav.breadcrumb.qrCodeHandle", "/settings/deliveryOrderFloor": "nav.breadcrumb.deliveryOrderFloor", "/settings/masterDataIssues": "nav.breadcrumb.masterDataIssues", + "/settings/stockLedgerFix": "nav.breadcrumb.stockLedgerFix", "/settings/rss": "nav.breadcrumb.demandForecast", "/settings/equipment": "nav.breadcrumb.equipment", "/settings/equipment/MaintenanceEdit": "nav.breadcrumb.equipmentMaintenanceEdit", diff --git a/src/components/DashboardPage/truckSchedule/TruckScheduleDashboard.tsx b/src/components/DashboardPage/truckSchedule/TruckScheduleDashboard.tsx index 5c12aad5..55d7f5bb 100644 --- a/src/components/DashboardPage/truckSchedule/TruckScheduleDashboard.tsx +++ b/src/components/DashboardPage/truckSchedule/TruckScheduleDashboard.tsx @@ -203,13 +203,13 @@ const TruckScheduleDashboard: React.FC = () => { return '-'; }; - // Compare a timestamp against the selected date (today/tomorrow/...) and return a short label. - // Used to avoid confusion when picking crosses midnight. + // Compare a timestamp against calendar today. Same-day picks show no chip; + // only midnight-crossing (yesterday / tomorrow / N days) gets a label. + // Does not filter rows — trucklane tickets for the selected delivery date still show. const relativeDayLabel = useCallback( - (dateTimeData: string | number[] | null, dateOption: string): string | null => { + (dateTimeData: string | number[] | null): string | null => { if (!dateTimeData) return null; - const dateOffset = getDateOffset(dateOption); - const baseDate = dayjs().startOf('day').add(dateOffset, 'day'); + const baseDate = dayjs().startOf('day'); let dt: dayjs.Dayjs; if (Array.isArray(dateTimeData)) { @@ -518,8 +518,8 @@ const TruckScheduleDashboard: React.FC = () => { filteredData.map((row, index) => { const timeRemaining = calculateTimeRemaining(row, selectedDate); const chipColor = getTimeChipColor(row, selectedDate); - const startRel = relativeDayLabel(row.firstTicketStartTime, selectedDate); - const endRel = relativeDayLabel(row.lastTicketEndTime, selectedDate); + const startRel = relativeDayLabel(row.firstTicketStartTime); + const endRel = relativeDayLabel(row.lastTicketEndTime); return ( = ({ defaultTabIndex = 0, printerCom const confirmResult = await Swal.fire({ title: t("Batch Print"), - text: `${t("Confirm print: (")}${releasedOrders.length}${t("piece(s))")}`, + text: t("Confirm print drafts", { count: releasedOrders.length }), icon: "question", showCancelButton: true, confirmButtonText: t("Confirm"), @@ -276,18 +276,29 @@ const DoWorkbenchTabsInner: React.FC = ({ defaultTabIndex = 0, printerCom @@ -297,7 +308,7 @@ const DoWorkbenchTabsInner: React.FC = ({ defaultTabIndex = 0, printerCom sx={{ overflow: "visible", /* 徽章在標籤右側外凸,預留空間避免與下一個 Tab 貼死 */ - pr: etraIncompleteDopoCount > 99 ? 5 : etraIncompleteDopoCount > 0 ? 4 : 2, + pr: etraIncompleteDopoCount > 99 ? 2.5 : etraIncompleteDopoCount > 0 ? 2 : 1, }} label={ = ({ defaultTabIndex = 0, printerCom 0 ? 1 : 0 }} + sx={{ + pr: etraIncompleteDopoCount > 0 ? 1 : 0, + whiteSpace: "nowrap", + lineHeight: 1.2, + textAlign: "center", + }} > {t("Etra Pick Order Detail")} @@ -341,8 +357,8 @@ const DoWorkbenchTabsInner: React.FC = ({ defaultTabIndex = 0, printerCom - - + + @@ -401,7 +417,7 @@ const DoWorkbenchTabsInner: React.FC = ({ defaultTabIndex = 0, printerCom /** * FP-MTMS Version Checklist | Functions Ref. No. 20 | v1.0.0 | 2026-07-19 - * FP-MTMS Version Checklist | Functions Ref. No. 55 | v1.0.0 | 2026-08-06 + * FP-MTMS Version Checklist | Functions Ref. No. 55 | v1.0.1 | 2026-09-22 */ const DoWorkbenchTabs: React.FC = (props) => ( = ({ const currentUserId = session?.id ? parseInt(session.id, 10) : undefined; const [loading, setLoading] = useState(false); + const [isPrinting, setIsPrinting] = useState(false); + const printInFlightRef = useRef(false); const [records, setRecords] = useState([]); const initialSearchTargetDate = useMemo( () => resolveWorkbenchRecordTargetDate(initialTargetDate), @@ -183,6 +185,65 @@ const GoodPickExecutionWorkbenchRecord: React.FC = ({ return t("All dates"); }, [searchQuery.targetDate, t]); + const rememberCartonQty = useCallback((recordId: number, cartonQty: number) => { + setRecords((prev) => + prev.map((row) => + row.doPickOrderRecordId === recordId ? { ...row, numberOfCartons: cartonQty } : row, + ), + ); + }, []); + + const submitPrint = useCallback( + async (job: () => Promise<{ success: boolean }>) => { + await new Promise((resolve) => { + void Swal.fire({ + title: t("Printing..."), + allowOutsideClick: false, + allowEscapeKey: false, + showConfirmButton: false, + didOpen: () => { + Swal.showLoading(); + resolve(); + }, + }); + }); + try { + const response = await job(); + Swal.close(); + if (response.success) { + await Swal.fire({ + position: "bottom-end", + icon: "success", + text: t("Printed Successfully."), + showConfirmButton: false, + timer: 1500, + }); + return true; + } + await Swal.fire({ + position: "bottom-end", + icon: "error", + text: t("Print failed"), + showConfirmButton: false, + timer: 2000, + }); + return false; + } catch (error) { + console.error("print error:", error); + Swal.close(); + await Swal.fire({ + position: "bottom-end", + icon: "error", + text: t("Print failed"), + showConfirmButton: false, + timer: 2000, + }); + return false; + } + }, + [t], + ); + const askNumOfCarton = useCallback(async () => { const result = await Swal.fire({ title: t("Enter the number of cartons: "), @@ -210,6 +271,7 @@ const GoodPickExecutionWorkbenchRecord: React.FC = ({ const handlePrintDN = useCallback( async (recordId: number) => { + if (printInFlightRef.current) return; if (!a4Printer) { await Swal.fire({ position: "bottom-end", @@ -220,31 +282,32 @@ const GoodPickExecutionWorkbenchRecord: React.FC = ({ }); return; } - const cartonQty = await askNumOfCarton(); - if (!cartonQty) return; - const response = await printDNWorkbench({ - deliveryOrderPickOrderId: recordId, - printerId: a4Printer.id, - printQty: 1, - isDraft: false, - numOfCarton: cartonQty, - }); - if (response.success) { - await Swal.fire({ - position: "bottom-end", - icon: "success", - text: t("Printed Successfully."), - showConfirmButton: false, - timer: 1500, - }); - await loadData(); + printInFlightRef.current = true; + setIsPrinting(true); + try { + const cartonQty = await askNumOfCarton(); + if (!cartonQty) return; + const ok = await submitPrint(() => + printDNWorkbench({ + deliveryOrderPickOrderId: recordId, + printerId: a4Printer.id, + printQty: 1, + isDraft: false, + numOfCarton: cartonQty, + }), + ); + if (ok) rememberCartonQty(recordId, cartonQty); + } finally { + setIsPrinting(false); + printInFlightRef.current = false; } }, - [a4Printer, askNumOfCarton, loadData, t], + [a4Printer, askNumOfCarton, rememberCartonQty, submitPrint, t], ); const handlePrintLabel = useCallback( async (recordId: number) => { + if (printInFlightRef.current) return; if (!labelPrinter) { await Swal.fire({ position: "bottom-end", @@ -255,30 +318,31 @@ const GoodPickExecutionWorkbenchRecord: React.FC = ({ }); return; } - const cartonQty = await askNumOfCarton(); - if (!cartonQty) return; - const response = await printDNLabelsWorkbench({ - deliveryOrderPickOrderId: recordId, - printerId: labelPrinter.id, - printQty: 1, - numOfCarton: cartonQty, - }); - if (response.success) { - await Swal.fire({ - position: "bottom-end", - icon: "success", - text: t("Printed Successfully."), - showConfirmButton: false, - timer: 1500, - }); - await loadData(); + printInFlightRef.current = true; + setIsPrinting(true); + try { + const cartonQty = await askNumOfCarton(); + if (!cartonQty) return; + const ok = await submitPrint(() => + printDNLabelsWorkbench({ + deliveryOrderPickOrderId: recordId, + printerId: labelPrinter.id, + printQty: 1, + numOfCarton: cartonQty, + }), + ); + if (ok) rememberCartonQty(recordId, cartonQty); + } finally { + setIsPrinting(false); + printInFlightRef.current = false; } }, - [askNumOfCarton, labelPrinter, loadData, t], + [askNumOfCarton, labelPrinter, rememberCartonQty, submitPrint, t], ); const handlePrintBoth = useCallback( async (recordId: number) => { + if (printInFlightRef.current) return; if (!a4Printer || !labelPrinter) { await Swal.fire({ position: "bottom-end", @@ -289,37 +353,39 @@ const GoodPickExecutionWorkbenchRecord: React.FC = ({ }); return; } - const cartonQty = await askNumOfCarton(); - if (!cartonQty) return; - const [labelRes, dnRes] = await Promise.all([ - printDNLabelsWorkbench({ - deliveryOrderPickOrderId: recordId, - printerId: labelPrinter.id, - printQty: 1, - numOfCarton: cartonQty, - }), - printDNWorkbench({ - deliveryOrderPickOrderId: recordId, - printerId: a4Printer.id, - printQty: 1, - isDraft: false, - numOfCarton: cartonQty, - }), - ]); - if (labelRes.success && dnRes.success) { - await Swal.fire({ - position: "bottom-end", - icon: "success", - text: t("Printed Successfully."), - showConfirmButton: false, - timer: 1500, + printInFlightRef.current = true; + setIsPrinting(true); + try { + const cartonQty = await askNumOfCarton(); + if (!cartonQty) return; + const ok = await submitPrint(async () => { + const [labelRes, dnRes] = await Promise.all([ + printDNLabelsWorkbench({ + deliveryOrderPickOrderId: recordId, + printerId: labelPrinter.id, + printQty: 1, + numOfCarton: cartonQty, + }), + printDNWorkbench({ + deliveryOrderPickOrderId: recordId, + printerId: a4Printer.id, + printQty: 1, + isDraft: false, + numOfCarton: cartonQty, + }), + ]); + return { success: labelRes.success && dnRes.success }; }); - await loadData(); + if (ok) rememberCartonQty(recordId, cartonQty); + } finally { + setIsPrinting(false); + printInFlightRef.current = false; } }, - [a4Printer, askNumOfCarton, labelPrinter, loadData, t], + [a4Printer, askNumOfCarton, labelPrinter, rememberCartonQty, submitPrint, t], ); const handleLabelReprint = useCallback(async (doPickOrder: CompletedDoPickOrderResponse) => { + if (printInFlightRef.current) return; if (!labelPrinter) { Swal.fire({ position: "bottom-end", @@ -331,6 +397,9 @@ const GoodPickExecutionWorkbenchRecord: React.FC = ({ return; } + printInFlightRef.current = true; + setIsPrinting(true); + try { const defaultTotalCartons = Math.max(1, doPickOrder.numberOfCartons || 1); const result = await Swal.fire({ title: t("Reprint DN Label"), @@ -390,31 +459,22 @@ const GoodPickExecutionWorkbenchRecord: React.FC = ({ return; } - try { - const response = await printDNLabelsReprintWorkbench({ - deliveryOrderPickOrderId: doPickOrder.doPickOrderRecordId, - printerId: labelPrinter.id, - printQty: 1, - fromCarton: result.value.fromCarton, - toCarton: result.value.toCarton, - totalCartonsOnShipment: result.value.totalCartonsOnShipment, - }); - - if (response.success) { - Swal.fire({ - position: "bottom-end", - icon: "success", - text: t("Printed Successfully."), - showConfirmButton: false, - timer: 1500 - }); - } else { - console.error("Reprint failed:", response.message); - } - } catch (error) { - console.error("reprint error: ", error); + const ok = await submitPrint(() => + printDNLabelsReprintWorkbench({ + deliveryOrderPickOrderId: doPickOrder.doPickOrderRecordId, + printerId: labelPrinter.id, + printQty: 1, + fromCarton: result.value.fromCarton, + toCarton: result.value.toCarton, + totalCartonsOnShipment: result.value.totalCartonsOnShipment, + }), + ); + if (ok) rememberCartonQty(doPickOrder.doPickOrderRecordId, result.value.totalCartonsOnShipment); + } finally { + setIsPrinting(false); + printInFlightRef.current = false; } - }, [labelPrinter, t]); + }, [labelPrinter, rememberCartonQty, submitPrint, t]); const handleDetailClick = useCallback( async (record: CompletedDoPickOrderResponse) => { @@ -735,16 +795,16 @@ const GoodPickExecutionWorkbenchRecord: React.FC = ({ - - - - diff --git a/src/components/DoWorkbench/TruckRoutingSummaryTabWorkbench.tsx b/src/components/DoWorkbench/TruckRoutingSummaryTabWorkbench.tsx index 3325a539..c47689f1 100644 --- a/src/components/DoWorkbench/TruckRoutingSummaryTabWorkbench.tsx +++ b/src/components/DoWorkbench/TruckRoutingSummaryTabWorkbench.tsx @@ -3,6 +3,7 @@ import { useEffect, useState } from "react"; import { Box, Button, MenuItem, Stack, TextField, Typography } from "@mui/material"; import DownloadIcon from "@mui/icons-material/Download"; +import { useTranslation } from "react-i18next"; import { clientAuthFetch } from "@/app/utils/clientAuthFetch"; import { NEXT_PUBLIC_API_URL } from "@/config/api"; import { @@ -18,6 +19,7 @@ import { } from "@/lib/featureUsageLog"; const TruckRoutingSummaryTabWorkbench: React.FC = () => { + const { t } = useTranslation(); const [storeOptions, setStoreOptions] = useState([]); const [laneOptions, setLaneOptions] = useState([]); const [storeId, setStoreId] = useState(""); @@ -45,6 +47,9 @@ const TruckRoutingSummaryTabWorkbench: React.FC = () => { const canDownload = storeId && truckLanceCode && date && !loading; + const displayOptionLabel = (label: string) => + String(label).trim() === "車線-X" ? t("Truck X") : label; + const onDownload = async () => { if (!canDownload) return; try { @@ -55,7 +60,9 @@ const TruckRoutingSummaryTabWorkbench: React.FC = () => { }); if (precheck.hasUnpickedOrders) { const confirmed = window.confirm( - `此車線仍有 ${precheck.unpickedOrderCount} 張訂單未執拾。\n是否仍要列印 / 下載送貨路線摘要?` + t("Unpicked orders confirm download", { + count: precheck.unpickedOrderCount, + }), ); if (!confirmed) return; } @@ -92,7 +99,7 @@ const TruckRoutingSummaryTabWorkbench: React.FC = () => { ); } catch (error) { console.error("Failed to download Workbench Truck Routing Summary", error); - alert("下載 Workbench 送貨路線摘要失敗,請稍後再試。"); + alert(t("Failed to download Workbench truck routing summary. Please try again later.")); } finally { setLoading(false); } @@ -101,39 +108,39 @@ const TruckRoutingSummaryTabWorkbench: React.FC = () => { return ( - 送貨路線摘要 (Workbench) + {t("Truck Routing Summary (Workbench)")} onStoreChange(e.target.value)} > {storeOptions.map((opt) => ( - {opt.label} + {displayOptionLabel(opt.label)} ))} setTruckLanceCode(e.target.value)} disabled={!storeId} > {laneOptions.map((opt) => ( - {opt.label} + {displayOptionLabel(opt.label)} ))} { disabled={!canDownload} onClick={onDownload} > - {loading ? "生成中..." : "下載報告 (PDF)"} + {loading ? t("Generating...") : t("Download report (PDF)")} ); diff --git a/src/components/DoWorkbench/WorkbenchGoodPickExecutionDetail.tsx b/src/components/DoWorkbench/WorkbenchGoodPickExecutionDetail.tsx index c892984c..d3c2aecd 100644 --- a/src/components/DoWorkbench/WorkbenchGoodPickExecutionDetail.tsx +++ b/src/components/DoWorkbench/WorkbenchGoodPickExecutionDetail.tsx @@ -421,22 +421,30 @@ function isWorkbenchSourceLotExpired(lot: any): boolean { return false; } -function getWorkbenchSourceLotStatusSummary(lot: any): { +type PickOrderT = (key: string, options?: Record) => string; + +function getWorkbenchSourceLotStatusSummary(lot: any, t: PickOrderT): { severity: "success" | "warning" | "error"; text: string; } { if (!lot) { - return { severity: "warning", text: "無法判斷此批號狀態" }; + return { severity: "warning", text: t("Cannot determine this lot status") }; } if (isWorkbenchSourceLotExpired(lot)) { - return { severity: "error", text: "此批號狀態:已過期" }; + return { severity: "error", text: t("Lot status: expired") }; } const solSt = String(lot.stockOutLineStatus || "").toLowerCase(); if (solSt === "rejected") { - return { severity: "warning", text: "此出庫行:已拒絕,請改掃其他批號" }; + return { + severity: "warning", + text: t("This pick line was rejected. Please scan another lot."), + }; } if (solSt === "completed" || solSt === "partially_completed") { - return { severity: "warning", text: "此出庫行:已完成,無需再提貨" }; + return { + severity: "warning", + text: t("This pick line is already completed. No further pick needed."), + }; } /** * 無批次列:後端仍標 insufficient_stock,語意是「尚無可出庫批號」而非「已用畢」。 @@ -449,28 +457,28 @@ function getWorkbenchSourceLotStatusSummary(lot: any): { if (isNoLotRow) { return { severity: "warning", - text: "尚未綁定批號/無可用庫存列:請掃描週邊入庫或轉倉 QR", + text: t( + "No lot bound / no available stock line. Please scan nearby inbound or transfer QR.", + ), }; } const av = String(lot.lotAvailability || "").toLowerCase(); if (av === "insufficient_stock") { - return { severity: "warning", text: "此批號狀態:已用畢(無剩餘庫存)" }; + return { severity: "warning", text: t("Lot status: depleted (no remaining stock)") }; } const avail = Number(lot.availableQty); if (lot.lotNo && Number.isFinite(avail) && avail <= 0) { - return { severity: "warning", text: "此批號狀態:已用畢(可用量為 0)" }; + return { severity: "warning", text: t("Lot status: depleted (available qty is 0)") }; } if (isInventoryLotLineUnavailable(lot)) { return { severity: "warning", - text: "此批號狀態:庫存不可用(未上架或行狀態不可用)", + text: t("Lot status: unavailable (not put away or line unavailable)"), }; } - return { severity: "success", text: "此批號狀態:可提貨" }; + return { severity: "success", text: t("Lot status: ready to pick") }; } -type PickOrderT = (key: string, options?: Record) => string; - function translateWorkbenchRejectMessage(raw: string, t: PickOrderT): string { const msg = raw.trim(); if (!msg) return msg; @@ -1334,9 +1342,9 @@ const fetchAllCombinedLotData = useCallback(async (userId?: number, pickOrderIdO severity: undefined as "success" | "warning" | "error" | undefined, }; } - const s = getWorkbenchSourceLotStatusSummary(workbenchLotLabelContextLot); + const s = getWorkbenchSourceLotStatusSummary(workbenchLotLabelContextLot, t); return { text: s.text, severity: s.severity }; - }, [workbenchLotLabelModalOpen, workbenchLotLabelContextLot]); + }, [workbenchLotLabelModalOpen, workbenchLotLabelContextLot, t]); const workbenchLotLabelSubmitQty = useMemo(() => { if (!workbenchLotLabelContextLot) return 0; @@ -1811,7 +1819,9 @@ const fetchAllCombinedLotData = useCallback(async (userId?: number, pickOrderIdO setQrScanError(true); setQrScanSuccess(false); setQrScanErrorMsg( - `此批次(${scannedLot.lotNo || scannedStockInLineId})已被拒绝,无法使用。请扫描其他批次。` + t("This lot ({{lot}}) was rejected and cannot be used. Please scan another lot.", { + lot: scannedLot.lotNo || scannedStockInLineId, + }), ); }); // Mark this SOL as processed to prevent re-processing @@ -1864,7 +1874,7 @@ const fetchAllCombinedLotData = useCallback(async (userId?: number, pickOrderIdO startTransition(() => { setQrScanError(true); setQrScanSuccess(false); - setQrScanErrorMsg("当前订单中没有此物品的批次信息"); + setQrScanErrorMsg(t("No lot information for this item in the current order")); }); return; } diff --git a/src/components/DoWorkbench/WorkbenchLotLabelPrintModal.tsx b/src/components/DoWorkbench/WorkbenchLotLabelPrintModal.tsx index 875aa7d0..d92bd9fe 100644 --- a/src/components/DoWorkbench/WorkbenchLotLabelPrintModal.tsx +++ b/src/components/DoWorkbench/WorkbenchLotLabelPrintModal.tsx @@ -38,6 +38,7 @@ import { } from "@/app/api/doworkbench/actions"; import { fetchDoFloorSettingsClient } from "@/app/api/settings/deliveryOrderFloor/client"; import { QRCodeSVG } from "qrcode.react"; +import { useTranslation } from "react-i18next"; type ScanPayload = { itemId: number; @@ -149,7 +150,7 @@ function isLabelPrinter(p: Printer): boolean { return s.includes("label") && !s.includes("a4"); } -/** FP-MTMS Version Checklist | Functions Ref. No. 30 | v1.0.1 | 2026-07-22 */ +/** FP-MTMS Version Checklist | Functions Ref. No. 30 | v1.0.2 | 2026-11-02 */ const WorkbenchLotLabelPrintModal: React.FC = ({ open, onClose, @@ -171,6 +172,7 @@ const WorkbenchLotLabelPrintModal: React.FC = onSubmitQtyChange, pickRuleScope, }) => { + const { t } = useTranslation(); const scanInputRef = useRef(null); const [scanInput, setScanInput] = useState(""); const [scanError, setScanError] = useState(null); @@ -218,8 +220,8 @@ const WorkbenchLotLabelPrintModal: React.FC = useEffect(() => { if (!open) return; resetAll(); - const t = setTimeout(() => scanInputRef.current?.focus(), 50); - return () => clearTimeout(t); + const focusTimer = setTimeout(() => scanInputRef.current?.focus(), 50); + return () => clearTimeout(focusTimer); }, [open, resetAll]); useEffect(() => { @@ -275,13 +277,13 @@ const WorkbenchLotLabelPrintModal: React.FC = setPrinters([]); setSnackbar({ open: true, - message: e instanceof Error ? e.message : "載入印表機清單失敗", + message: e instanceof Error ? e.message : t("Failed to load printer list"), severity: "error", }); } finally { setPrintersLoading(false); } - }, []); + }, [t]); useEffect(() => { if (!open) return; @@ -334,23 +336,23 @@ const WorkbenchLotLabelPrintModal: React.FC = setAnalysis(data); setSnackbar({ open: true, - message: "已載入同品可用批號清單", + message: t("Loaded available lots for this item"), severity: "success", }); } catch (e) { setAnalysis(null); - setScanError(e instanceof Error ? e.message : "分析失敗"); + setScanError(e instanceof Error ? e.message : t("Analysis failed")); } finally { setAnalysisLoading(false); } }, - [resolveExpectedUomId], + [resolveExpectedUomId, t], ); const analyzeByItem = useCallback( async (itemId: number) => { if (!Number.isFinite(itemId) || itemId <= 0) { - setScanError("無效 itemId,無法載入批號清單。"); + setScanError(t("Invalid itemId, cannot load lot list.")); return; } setLastItemId(itemId); @@ -376,17 +378,17 @@ const WorkbenchLotLabelPrintModal: React.FC = }); setSnackbar({ open: true, - message: "已載入同品可用批號清單", + message: t("Loaded available lots for this item"), severity: "success", }); } catch (e) { setAnalysis(null); - setScanError(e instanceof Error ? e.message : "分析失敗"); + setScanError(e instanceof Error ? e.message : t("Analysis failed")); } finally { setAnalysisLoading(false); } }, - [resolveExpectedUomId], + [resolveExpectedUomId, t], ); const handleAnalyze = useCallback(async () => { @@ -394,13 +396,13 @@ const WorkbenchLotLabelPrintModal: React.FC = const payload = safeParseScanPayload(raw); if (!payload) { setScanError( - '掃碼內容格式錯誤,請重新掃碼', + t("Invalid scan format. Please scan again."), ); setAnalysis(null); return; } await analyzePayload(payload); - }, [scanInput, analyzePayload]); + }, [scanInput, analyzePayload, t]); const handleRefreshLots = useCallback(async () => { const payload = lastPayload ?? safeParseScanPayload(scanInput.trim()); @@ -419,12 +421,12 @@ const WorkbenchLotLabelPrintModal: React.FC = if (!payload) { setSnackbar({ open: true, - message: "請先掃碼或查詢一次,才可刷新批號清單。", + message: t("Scan or look up once before refreshing the lot list."), severity: "info", }); return; } - }, [analyzeByItem, analyzePayload, initialItemId, lastItemId, lastPayload, scanInput]); + }, [analyzeByItem, analyzePayload, initialItemId, lastItemId, lastPayload, scanInput, t]); useEffect(() => { if (!open) return; @@ -527,7 +529,7 @@ const WorkbenchLotLabelPrintModal: React.FC = if (selectedPrinterId === "") { setSnackbar({ open: true, - message: "請先選擇印表機", + message: t("Please select a printer first"), severity: "error", }); return; @@ -535,7 +537,7 @@ const WorkbenchLotLabelPrintModal: React.FC = if (printQty < 1 || !Number.isFinite(printQty)) { setSnackbar({ open: true, - message: "列印張數需為大於等於 1 的整數", + message: t("Print quantity must be an integer of 1 or more"), severity: "error", }); return; @@ -550,25 +552,25 @@ const WorkbenchLotLabelPrintModal: React.FC = }); setSnackbar({ open: true, - message: `已送出列印:Lot ${lotNo}`, + message: t("Print sent: Lot {{lotNo}}", { lotNo }), severity: "success", }); } catch (e) { setSnackbar({ open: true, - message: e instanceof Error ? e.message : "列印失敗", + message: e instanceof Error ? e.message : t("Print failed"), severity: "error", }); } finally { setPrintingLotLineId(null); } }, - [selectedPrinterId, printQty], + [selectedPrinterId, printQty, t], ); return ( - 批號標籤列印(提貨台) + {t("Lot label print (pick station)")} {statusTitleText ? ( @@ -605,13 +607,13 @@ const WorkbenchLotLabelPrintModal: React.FC = > setScanInput(e.target.value)} fullWidth size="small" error={!!scanError} - helperText={scanError || "掃描後按 Enter 或點「查詢」"} + helperText={scanError || t("Scan then press Enter or click Look up")} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); @@ -625,7 +627,7 @@ const WorkbenchLotLabelPrintModal: React.FC = onClick={() => void handleAnalyze()} disabled={analysisLoading || !scanInput.trim()} > - {analysisLoading ? : "查詢"} + {analysisLoading ? : t("Look up")} @@ -651,16 +653,16 @@ const WorkbenchLotLabelPrintModal: React.FC = sx={{ minWidth: 260 }} disabled={printersLoading} > - 印表機 + {t("Printer")} { - const arr = selected as string[]; - if (arr.length === 0) { - return ( - - {t("lane_selectedNone")} - - ); - } - if (filterActive) - return t("lane_selectedCount", { - count: selectedVisible, - }); - return t("lane_selectedCount", { count: arr.length }); - }} - onChange={(e) => { - const value = e.target.value as unknown as string[]; - setSelectedLaneIds(value); - }} - MenuProps={{ - autoFocus: false, - MenuListProps: { autoFocus: false, dense: false }, - PaperProps: { - sx: { - maxHeight: 420, - minWidth: 360, - maxWidth: "min(100vw - 32px, 480px)", - }, - }, + - { + const arr = selected as string[]; + if (arr.length === 0) { + return ( + + {t("lane_selectedNone")} + + ); + } + if (filterActive) + return t("lane_selectedCount", { + count: selectedVisible, + }); + return t("lane_selectedCount", { count: arr.length }); + }} + onChange={(e) => { + const value = e.target.value as unknown as string[]; + setSelectedLaneIds( + Array.isArray(value) ? value : [String(value)], + ); }} - onClick={(e) => e.stopPropagation()} + MenuProps={{ + autoFocus: false, + PaperProps: { + component: LaneSelectMenuPaper, + }, + MenuListProps: { + autoFocus: false, + dense: false, + sx: { + flex: "1 1 320px", + minWidth: 280, + maxWidth: laneFilterPanelOpen ? 400 : "100%", + maxHeight: 420, + overflowY: "auto", + overflowX: "hidden", + py: 0, + }, + }, + }} + sx={{ mt: 1 }} > - - - setLaneFilter((prev) => ({ - ...prev, - query: e.target.value, - })) - } - onKeyDown={(e) => e.stopPropagation()} - onClick={(e) => e.stopPropagation()} - onMouseDown={(e) => e.stopPropagation()} - InputProps={{ - startAdornment: ( - e.stopPropagation()} + onMouseDown={(e) => e.stopPropagation()} + > + + + setLaneFilter((prev) => ({ + ...prev, + query: e.target.value, + })) + } + onKeyDown={(e) => e.stopPropagation()} + onClick={(e) => e.stopPropagation()} + onMouseDown={(e) => e.stopPropagation()} + InputProps={{ + startAdornment: ( + + + + ), + }} + sx={{ + flex: 1, + minWidth: 0, + "& .MuiOutlinedInput-root": { + borderRadius: 2, + bgcolor: "grey.50", + }, + "& .MuiInputBase-input": { + textAlign: "left", + fontSize: "0.8125rem", + color: "text.secondary", + py: 0.75, + }, + "& .MuiInputBase-input::placeholder": { + opacity: 1, + color: "text.disabled", + textAlign: "left", + }, + }} + /> + + + e.stopPropagation()} + onClick={(e) => { + e.stopPropagation(); + setLaneFilterPanelOpen((open) => { + const next = !open; + if (next) { + setLaneFilter((prev) => ({ + ...prev, + floor: "2F", + zone: "all", + weekday: "all", + area: [], + })); + } + return next; + }); + }} sx={{ - mr: 0.5, - display: "inline-flex", - color: "text.disabled", + flexShrink: 0, + width: 32, + height: 32, }} > - - - ), - }} - sx={{ - flex: 1, - minWidth: 0, - "& .MuiOutlinedInput-root": { - borderRadius: 2, - bgcolor: "grey.50", - }, - "& .MuiInputBase-input": { - textAlign: "left", - fontSize: "0.8125rem", - color: "text.secondary", - py: 0.75, - }, - "& .MuiInputBase-input::placeholder": { - opacity: 1, - color: "text.disabled", - textAlign: "left", - }, - }} - /> - - - e.stopPropagation()} - onClick={(e) => { - e.stopPropagation(); - setLaneFilterAnchor(e.currentTarget); - }} - sx={{ - flexShrink: 0, - width: 32, - height: 32, - }} - > - - - - - - - - {visibleLaneOptions.map((lane) => { + + + + + + + + {visibleLaneOptions.map((lane) => { const checked = selectedLaneIds.includes(lane.id); const rem = lane.remark != null && @@ -6659,61 +7420,8 @@ const RouteBoard: React.FC = () => { ); })} - - - setLaneFilterAnchor(null)} - anchorOrigin={{ vertical: "bottom", horizontal: "left" }} - transformOrigin={{ vertical: "top", horizontal: "left" }} - > - - - - {t("floor_label")} - - - - - - - - - + + {routeBoardTab === "board" && ( + + + + + + + {t("adjTitle")} + + {t("adjDescription")} + + + { + setAdjDate(e.target.value); + setAdjMessage(null); + }} + disabled={adjRunning} + InputLabelProps={{ shrink: true }} + inputProps={{ max: dayjs().format("YYYY-MM-DD") }} + /> + + + + {adjError && {adjError}} + {adjMessage && {adjMessage}} + {adjRunning && } + + + + + + + + + { + setTab(v); + setFixError(null); + setFixMessage(null); + setSearchError(null); + }} + > + + + + + + + {tab === "day" && ( + + + + setSelected(v)} + views={["year", "month", "day"]} + openTo="day" + minDate={FIRST_LEDGER_DAY} + maxDate={dayjs()} + /> + + + {t("calendarHint")} + + + + + + + {selected ? selected.format("YYYY-MM-DD") : t("selectDate")} + + {detailError && {detailError}} + {fixError && {fixError}} + {fixMessage && {fixMessage}} + {chainProgress && {chainProgress}} + {detailLoading && } + {detail && !detailLoading && ( + <> + + {t("dayLedgerCount", { cnt: detail.cnt })} + + + + )} + + + {t("stepsTitle")} + + + {t("stepsHint")} + + + {DAY_FIX_STEPS.map((step) => ( + + setDaySteps((prev) => ({ ...prev, [step]: checked })) + } + /> + } + label={t(DAY_STEP_I18N[step])} + /> + ))} + + + + + + + + + {t("rangeTitle")} + + + {t("rangeHint")} + + + setChainFrom(e.target.value)} + disabled={chainRunning} + InputLabelProps={{ shrink: true }} + /> + setChainTo(e.target.value)} + disabled={chainRunning} + InputLabelProps={{ shrink: true }} + /> + + + + + + {t("exportTitle")} + + + {t("exportHint")} + + + {EXPORT_PARTS.map((part) => ( + + setExportParts((prev) => ({ ...prev, [part]: checked })) + } + /> + } + label={t(EXPORT_PART_I18N[part])} + /> + ))} + + + + {exportError && {exportError}} + + setExportFrom(e.target.value)} + InputLabelProps={{ shrink: true }} + /> + setExportTo(e.target.value)} + InputLabelProps={{ shrink: true }} + /> + + + + + + + )} + + {tab === "inventory" && ( + + + + {t("invTabHint")} + + + setInvQuery(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") void onSearchInventory(); + }} + /> + + + {searchError && {searchError}} + {invHits.length > 0 && ( + + + + {t("colInventoryId")} + {t("colItemCode")} + {t("colUomId")} + {t("colLedgerRows")} + + + + {invHits.map((h) => ( + void loadInventoryScope(h.inventoryId)} + sx={{ cursor: "pointer" }} + > + {h.inventoryId} + {h.itemCode ?? t("checkDash")} + {h.uomId ?? t("checkDash")} + {h.ledgerCnt} + + ))} + +
+ )} + {fixError && {fixError}} + {fixMessage && {fixMessage}} + {scopeLoading && } + {scope?.kind === "inventory" && !scopeLoading && ( + <> + + {t("invScopeSummary", { + itemCode: scope.itemCode ?? "?", + id: scope.id, + uomId: scope.uomId ?? "?", + firstDate: scope.firstDate, + lastDate: scope.lastDate, + cnt: scope.cnt, + lastBalance: scope.lastBalance ?? t("checkDash"), + })} + + + + + + + )} +
+
+ )} + + {tab === "lot" && ( + + + + {t("lotTabHint")} + + + setLotQuery(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") void onSearchLot(); + }} + /> + + + {searchError && {searchError}} + {lotHits.length > 0 && ( + + + + {t("colLotLineId")} + {t("colLotNo")} + {t("colItemCode")} + {t("colInventoryId")} + {t("colLedgerRows")} + + + + {lotHits.map((h) => ( + void loadLotScope(h.inventoryLotLineId)} + sx={{ cursor: "pointer" }} + > + {h.inventoryLotLineId} + {h.lotNo ?? t("checkDash")} + {h.itemCode ?? t("checkDash")} + {h.inventoryId ?? t("checkDash")} + {h.ledgerCnt} + + ))} + +
+ )} + {fixError && {fixError}} + {fixMessage && {fixMessage}} + {scopeLoading && } + {scope?.kind === "lot" && !scopeLoading && ( + <> + + {t("lotScopeSummary", { + lotNo: scope.lotNo ?? "?", + id: scope.id, + itemCode: scope.itemCode ?? "?", + firstDate: scope.firstDate, + lastDate: scope.lastDate, + cnt: scope.cnt, + lastLotQtyAfter: scope.lastLotQtyAfter ?? t("checkDash"), + })} + + + + + + + )} +
+
+ )} + + ); +}; + +export default StockLedgerFixPageClient; diff --git a/src/components/StockTakeManagement/ApproverStockTake.tsx b/src/components/StockTakeManagement/ApproverStockTake.tsx index e2bdbb13..503c82c6 100644 --- a/src/components/StockTakeManagement/ApproverStockTake.tsx +++ b/src/components/StockTakeManagement/ApproverStockTake.tsx @@ -33,6 +33,10 @@ import { batchSaveApproverStockTakeRecords, updateStockTakeRecordStatusToNotMatch, } from "@/app/api/stockTake/actions"; +import { stockTakeQtyEndAdornment } from "./stockTakeQtyAdornment"; +import StockTakeQtyGapHint from "./StockTakeQtyGapHint"; +import { stockTakeHiddenOnHand, stockTakeQtyGapWarnText } from "./stockTakeQtyGapWarning"; +import { useStockTakeQtyGapWarnPercent } from "./useStockTakeQtyGapWarnPercent"; import { useSession } from "next-auth/react"; import { SessionWithTokens } from "@/config/authConfig"; import dayjs from "dayjs"; @@ -52,6 +56,7 @@ const ApproverStockTake: React.FC = ({ onSnackbar, }) => { const { t } = useTranslation(["stockTake", "common"]); + const qtyGapWarnPercent = useStockTakeQtyGapWarnPercent(); const { data: session } = useSession() as { data: SessionWithTokens | null }; const [inventoryLotDetails, setInventoryLotDetails] = useState([]); @@ -61,6 +66,7 @@ const ApproverStockTake: React.FC = ({ // 每个记录的选择状态,key 为 detail.id const [qtySelection, setQtySelection] = useState>({}); const [approverQty, setApproverQty] = useState>({}); + const [gapCheckOpen, setGapCheckOpen] = useState>({}); const [approverBadQty, setApproverBadQty] = useState>({}); const [saving, setSaving] = useState(false); const [batchSaving, setBatchSaving] = useState(false); @@ -255,7 +261,19 @@ const ApproverStockTake: React.FC = ({ selectedSession.stockTakeId ); - onSnackbar(t("Approver stock take record saved successfully"), "success"); + const gapText = + selection === "approver" + ? stockTakeQtyGapWarnText(t, approverQty[detail.id] || "", stockTakeHiddenOnHand(detail), qtyGapWarnPercent) + : null; + if (selection === "approver") { + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:approver`]: true })); + } + onSnackbar( + gapText + ? `${t("Approver stock take record saved successfully")} ${gapText}` + : t("Approver stock take record saved successfully"), + gapText ? "warning" : "success", + ); // 計算最終數量(合格數) const goodQty = finalQty - finalBadQty; @@ -292,7 +310,7 @@ const ApproverStockTake: React.FC = ({ } finally { setSaving(false); } - }, [selectedSession, qtySelection, approverQty, approverBadQty, t, currentUserId, onSnackbar, page, pageSize, loadDetails]); + }, [selectedSession, qtySelection, approverQty, approverBadQty, t, currentUserId, onSnackbar, page, pageSize, loadDetails, qtyGapWarnPercent]); const handleUpdateStatusToNotMatch = useCallback(async (detail: InventoryLotDetailResponse) => { if (!detail.stockTakeRecordId) { @@ -587,6 +605,7 @@ const ApproverStockTake: React.FC = ({ )} {hasSecond && ( + <> = ({ size="small" type="number" value={approverQty[detail.id] || ""} + onFocus={() => { + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:approver`]: false })); + if (selection !== "approver") { + setQtySelection({ ...qtySelection, [detail.id]: "approver" }); + } + }} + onBlur={() => + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:approver`]: true })) + } onChange={(e) => setApproverQty({ ...approverQty, [detail.id]: e.target.value })} + InputProps={{ + endAdornment: stockTakeQtyEndAdornment(detail.uomShortDesc), + }} sx={{ - width: 130, - minWidth: 130, + width: 168, + minWidth: 168, '& .MuiInputBase-input': { height: '1.4375em', padding: '4px 8px' } }} placeholder={t("Stock Take Qty") } - disabled={selection !== "approver"} /> = ({ = {formatNumber(parseFloat(approverQty[detail.id] || "0") - parseFloat(approverBadQty[detail.id] || "0"))} + + )} {(() => { diff --git a/src/components/StockTakeManagement/ApproverStockTakeAll.tsx b/src/components/StockTakeManagement/ApproverStockTakeAll.tsx index 91f57485..11f94ec4 100644 --- a/src/components/StockTakeManagement/ApproverStockTakeAll.tsx +++ b/src/components/StockTakeManagement/ApproverStockTakeAll.tsx @@ -53,6 +53,10 @@ import { type ApproverInventoryLotDetailsQuery, } from "@/app/api/stockTake/actions"; import { fetchStockTakeSections } from "@/app/api/warehouse/actions"; +import { stockTakeQtyEndAdornment, StockTakeQtyWithUnit } from "./stockTakeQtyAdornment"; +import StockTakeQtyGapHint from "./StockTakeQtyGapHint"; +import { stockTakeHiddenOnHand, stockTakeQtyGapWarnText } from "./stockTakeQtyGapWarning"; +import { useStockTakeQtyGapWarnPercent } from "./useStockTakeQtyGapWarnPercent"; import { useSession } from "next-auth/react"; import { SessionWithTokens } from "@/config/authConfig"; import dayjs from "dayjs"; @@ -226,6 +230,7 @@ const ApproverStockTakeAll: React.FC = ({ onSnackbar, }) => { const { t } = useTranslation(["stockTake", "common"]); + const qtyGapWarnPercent = useStockTakeQtyGapWarnPercent(); const { data: session } = useSession() as { data: SessionWithTokens | null }; const [inventoryLotDetails, setInventoryLotDetails] = useState([]); @@ -235,6 +240,7 @@ const ApproverStockTakeAll: React.FC = ({ const [searchVarianceFilterStrict, setSearchVarianceFilterStrict] = useState(false); const [qtySelection, setQtySelection] = useState>({}); const [approverQty, setApproverQty] = useState>({}); + const [gapCheckOpen, setGapCheckOpen] = useState>({}); const [approverBadQty, setApproverBadQty] = useState>({}); const [saving, setSaving] = useState(false); const [batchSaving, setBatchSaving] = useState(false); @@ -654,7 +660,19 @@ const ApproverStockTakeAll: React.FC = ({ try { await saveApproverStockTakeRecord(request, selectedSession.stockTakeId); - onSnackbar(t("Approver stock take record saved successfully"), "success"); + const gapText = + selection === "approver" + ? stockTakeQtyGapWarnText(t, approverQty[detail.id] || "", stockTakeHiddenOnHand(detail), qtyGapWarnPercent) + : null; + if (selection === "approver") { + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:approver`]: true })); + } + onSnackbar( + gapText + ? `${t("Approver stock take record saved successfully")} ${gapText}` + : t("Approver stock take record saved successfully"), + gapText ? "warning" : "success", + ); setInventoryLotDetails((prev) => prev.map((d) => @@ -688,7 +706,7 @@ const ApproverStockTakeAll: React.FC = ({ setSaving(false); } }, - [selectedSession, currentUserId, qtySelection, approverQty, approverBadQty, t, onSnackbar, mode] + [selectedSession, currentUserId, qtySelection, approverQty, approverBadQty, t, onSnackbar, mode, qtyGapWarnPercent] ); const handleUpdateStatusToNotMatch = useCallback( @@ -934,10 +952,13 @@ const ApproverStockTakeAll: React.FC = ({ flex: 1, sortable: false, renderCell: (params) => ( - - + + {params.row.itemCode || "-"} {params.row.itemName || "-"} - + {params.row.lotNo || "-"} {params.row.expiryDate @@ -1052,12 +1073,12 @@ const ApproverStockTakeAll: React.FC = ({ /> {t("First")}:{" "} - {formatNumber( - (detail.firstStockTakeQty ?? 0) + (detail.firstBadQty ?? 0) - )}{" "} - {/* - = {formatNumber(detail.firstStockTakeQty ?? 0)} - */} + )} @@ -1077,12 +1098,12 @@ const ApproverStockTakeAll: React.FC = ({ /> {t("Second")}:{" "} - {formatNumber( - (detail.secondStockTakeQty ?? 0) + (detail.secondBadQty ?? 0) - )}{" "} - {/* - = {formatNumber(detail.secondStockTakeQty ?? 0)} - */} + @@ -1108,6 +1129,18 @@ const ApproverStockTakeAll: React.FC = ({ size="small" type="number" value={approverQty[detail.id] || ""} + onFocus={() => { + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:approver`]: false })); + if (mode !== "approved" && selection !== "approver") { + setQtySelection({ + ...qtySelection, + [detail.id]: "approver", + }); + } + }} + onBlur={() => + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:approver`]: true })) + } onKeyDown={blockNonIntegerKeys} onChange={(e) => { const clean = sanitizeIntegerInput(e.target.value); @@ -1116,18 +1149,29 @@ const ApproverStockTakeAll: React.FC = ({ [detail.id]: clean, }); }} + InputProps={{ + endAdornment: stockTakeQtyEndAdornment(detail.uomShortDesc), + }} sx={{ - width: 72, - minWidth: 72, + width: 120, + minWidth: 120, "& .MuiInputBase-input": { py: 0.5, px: 1, }, }} // placeholder={t("Stock Take Qty")} - disabled={mode === "approved" || selection !== "approver"} + disabled={mode === "approved"} inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }} /> + + + {/* = {formatNumber(approverGoodQty)} @@ -1152,7 +1196,7 @@ const ApproverStockTakeAll: React.FC = ({ {summaryLine( `${t("Selected Qty")}:`, - formatNumber(selectedQty) + [formatNumber(selectedQty), detail.uomShortDesc?.trim()].filter(Boolean).join(" ") )} {summaryLine(`${t("Book Qty")}:`, formatNumber(bookQty))} {summaryLine( diff --git a/src/components/StockTakeManagement/PickerReStockTake.tsx b/src/components/StockTakeManagement/PickerReStockTake.tsx index 1c8ebd3b..925b1bbb 100644 --- a/src/components/StockTakeManagement/PickerReStockTake.tsx +++ b/src/components/StockTakeManagement/PickerReStockTake.tsx @@ -30,6 +30,10 @@ import { getInventoryLotDetailsBySectionNotMatch } from "@/app/api/stockTake/actions"; import { buildPickerBatchSaveRequests } from "./buildPickerBatchSaveRequests"; +import { stockTakeQtyEndAdornment, StockTakeQtyWithUnit } from "./stockTakeQtyAdornment"; +import StockTakeQtyGapHint from "./StockTakeQtyGapHint"; +import { stockTakeHiddenOnHand, stockTakeQtyGapWarnText } from "./stockTakeQtyGapWarning"; +import { useStockTakeQtyGapWarnPercent } from "./useStockTakeQtyGapWarnPercent"; import PickerBatchSaveFab from "./PickerBatchSaveFab"; import { useSession } from "next-auth/react"; import { SessionWithTokens } from "@/config/authConfig"; @@ -52,6 +56,7 @@ const PickerReStockTake: React.FC = ({ onSnackbar, }) => { const { t } = useTranslation(["stockTake", "common"]); + const qtyGapWarnPercent = useStockTakeQtyGapWarnPercent(); const { data: session } = useSession() as { data: SessionWithTokens | null }; const [inventoryLotDetails, setInventoryLotDetails] = useState([]); @@ -65,6 +70,7 @@ const PickerReStockTake: React.FC = ({ remark: string; }>>({}); const [saving, setSaving] = useState(false); + const [gapCheckOpen, setGapCheckOpen] = useState>({}); const [batchSaving, setBatchSaving] = useState(false); const [shortcutInput, setShortcutInput] = useState(""); const [page, setPage] = useState(0); @@ -246,7 +252,19 @@ const PickerReStockTake: React.FC = ({ currentUserId ); - onSnackbar(t("Stock take record saved successfully"), "success"); + const gapText = stockTakeQtyGapWarnText( + t, + totalQtyStr ?? "", + stockTakeHiddenOnHand(detail), + qtyGapWarnPercent, + ); + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:${isFirstSubmit ? "first" : "second"}`]: true })); + onSnackbar( + gapText + ? `${t("Stock take record saved successfully")} ${gapText}` + : t("Stock take record saved successfully"), + gapText ? "warning" : "success", + ); const savedId = result?.id ?? detail.stockTakeRecordId; setInventoryLotDetails((prev) => @@ -286,7 +304,7 @@ const PickerReStockTake: React.FC = ({ } finally { setSaving(false); } - }, [selectedSession, recordInputs, t, currentUserId, onSnackbar, page, pageSize, loadDetails]); + }, [selectedSession, recordInputs, t, currentUserId, onSnackbar, page, pageSize, loadDetails, qtyGapWarnPercent]); const isSubmitDisabled = useCallback((detail: InventoryLotDetailResponse): boolean => { if (selectedSession?.status?.toLowerCase() === "completed") { @@ -492,7 +510,7 @@ const PickerReStockTake: React.FC = ({ {t("Warehouse Location")} {t("Item-lotNo-ExpiryDate")} {t("UOM")} - {t("Stock Take Qty(include Bad Qty)= Available Qty")} + {t("Stock Take Qty(include Bad Qty)= Available Qty")} {t("Action")} {/*{t("Remark")}*/} {t("Record Status")} @@ -520,28 +538,40 @@ const PickerReStockTake: React.FC = ({ {detail.warehouseArea || "-"}{detail.warehouseSlot || "-"} - {detail.itemCode || "-"} {detail.itemName || "-"} + + {detail.itemCode || "-"} {detail.itemName || "-"} + {detail.lotNo || "-"} {detail.expiryDate ? dayjs(detail.expiryDate).format(OUTPUT_DATE_FORMAT) : "-"} {detail.uom || "-"} - + {/* First */} {!submitDisabled && isFirstSubmit ? ( + {t("First")}: + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:first`]: false })) + } + onBlur={() => + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:first`]: true })) + } inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }} onKeyDown={blockNonIntegerKeys} onChange={(e) => { @@ -553,9 +583,12 @@ const PickerReStockTake: React.FC = ({ [detail.id]: { ...(prev[detail.id] ?? defaultInputs), firstQty: val } })); }} + InputProps={{ + endAdornment: stockTakeQtyEndAdornment(detail.uomShortDesc), + }} sx={{ - width: 130, - minWidth: 130, + width: 148, + minWidth: 148, "& .MuiInputBase-input": { height: "1.4375em", padding: "4px 8px", @@ -590,28 +623,39 @@ const PickerReStockTake: React.FC = ({ placeholder={t("Bad Qty")} /> */} - - = {formatNumber(parseFloat(inputs.firstQty || "0") - parseFloat(inputs.firstBadQty || "0"))} - + + ) : detail.firstStockTakeQty != null ? ( {t("First")}:{" "} - {formatNumber((detail.firstStockTakeQty ?? 0) + (detail.firstBadQty ?? 0))}{" "} - {/* ({formatNumber(detail.firstBadQty ?? 0)}) */} - ={" "} - {formatNumber(detail.firstStockTakeQty ?? 0)} + ) : null} {/* Second */} {!submitDisabled && isSecondSubmit ? ( + {t("Second")}: + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:second`]: false })) + } + onBlur={() => + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:second`]: true })) + } inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }} onKeyDown={blockNonIntegerKeys} onChange={(e) => { @@ -623,9 +667,12 @@ const PickerReStockTake: React.FC = ({ [detail.id]: { ...(prev[detail.id] ?? defaultInputs), secondQty: clean } })); }} + InputProps={{ + endAdornment: stockTakeQtyEndAdornment(detail.uomShortDesc), + }} sx={{ - width: 130, - minWidth: 130, + width: 148, + minWidth: 148, "& .MuiInputBase-input": { height: "1.4375em", padding: "4px 8px", @@ -660,17 +707,21 @@ const PickerReStockTake: React.FC = ({ placeholder={t("Bad Qty")} /> */} - - = {formatNumber(parseFloat(inputs.secondQty || "0") - parseFloat(inputs.secondBadQty || "0"))} - + + ) : detail.secondStockTakeQty != null ? ( {t("Second")}:{" "} - {formatNumber((detail.secondStockTakeQty ?? 0) + (detail.secondBadQty ?? 0))}{" "} - {/* ({formatNumber(detail.secondBadQty ?? 0)}) */} - ={" "} - {formatNumber(detail.secondStockTakeQty ?? 0)} + ) : null} diff --git a/src/components/StockTakeManagement/PickerStockTake.tsx b/src/components/StockTakeManagement/PickerStockTake.tsx index 220c7b3a..98a510a4 100644 --- a/src/components/StockTakeManagement/PickerStockTake.tsx +++ b/src/components/StockTakeManagement/PickerStockTake.tsx @@ -35,6 +35,10 @@ import { batchSavePickerStockTakeInputs, } from "@/app/api/stockTake/actions"; import { buildPickerBatchSaveRequests } from "./buildPickerBatchSaveRequests"; +import { stockTakeQtyEndAdornment, StockTakeQtyWithUnit } from "./stockTakeQtyAdornment"; +import StockTakeQtyGapHint from "./StockTakeQtyGapHint"; +import { stockTakeHiddenOnHand, stockTakeQtyGapWarnText } from "./stockTakeQtyGapWarning"; +import { useStockTakeQtyGapWarnPercent } from "./useStockTakeQtyGapWarnPercent"; import PickerBatchSaveFab from "./PickerBatchSaveFab"; import { useSession } from "next-auth/react"; import { SessionWithTokens } from "@/config/authConfig"; @@ -57,6 +61,7 @@ const PickerStockTake: React.FC = ({ onSnackbar, }) => { const { t } = useTranslation(["stockTake", "common"]); + const qtyGapWarnPercent = useStockTakeQtyGapWarnPercent(); const { data: session } = useSession() as { data: SessionWithTokens | null }; const [inventoryLotDetails, setInventoryLotDetails] = useState([]); @@ -72,7 +77,11 @@ const PickerStockTake: React.FC = ({ const [savingRecordId, setSavingRecordId] = useState(null); const [remark, setRemark] = useState(""); const [saving, setSaving] = useState(false); + /** Qty fields the user has left, or just saved. Warning stays hidden while typing. */ + const [gapCheckOpen, setGapCheckOpen] = useState>({}); const [batchSaving, setBatchSaving] = useState(false); + /** 已盤點列:按「更改」後才打開數量欄,再按「保存」。 */ + const [editingFirstIds, setEditingFirstIds] = useState>({}); const [shortcutInput, setShortcutInput] = useState(""); const [page, setPage] = useState(0); const [pageSize, setPageSize] = useState("all"); @@ -83,6 +92,7 @@ const PickerStockTake: React.FC = ({ const currentUserId = session?.id ? parseInt(session.id) : undefined; const handleBatchTestAllRef = useRef<() => Promise>(); const batchInFlightRef = useRef(false); + const saveInFlightRef = useRef(false); const isSessionCompleted = selectedSession?.status?.toLowerCase() === "completed"; const handleChangePage = useCallback((event: unknown, newPage: number) => { setPage(newPage); @@ -186,15 +196,42 @@ const PickerStockTake: React.FC = ({ }); }; + const canReviseFirstCount = useCallback((detail: InventoryLotDetailResponse): boolean => { + const sessionStatus = selectedSession?.status?.toLowerCase() ?? ""; + if (sessionStatus === "completed") { + return false; + } + const recordStatus = detail.stockTakeRecordStatus?.toLowerCase(); + if (recordStatus === "completed" || recordStatus !== "pass") { + return false; + } + if (detail.approverQty != null) { + return false; + } + if (detail.stockTakeRecordId == null) { + return false; + } + if (detail.firstStockTakeQty == null || detail.secondStockTakeQty != null) { + return false; + } + if ((detail.pickerReviseCount ?? 0) >= 2) { + return false; + } + return true; + }, [selectedSession?.status]); + const handleSaveStockTake = useCallback( async (detail: InventoryLotDetailResponse) => { - if (!selectedSession || !currentUserId) { + if (!selectedSession || !currentUserId || saveInFlightRef.current) { return; } - const isFirstSubmit = detail.firstStockTakeQty == null; + const revisingFirst = canReviseFirstCount(detail); + const isFirstSubmit = detail.firstStockTakeQty == null || revisingFirst; const isSecondSubmit = - detail.firstStockTakeQty != null && detail.secondStockTakeQty == null; + !revisingFirst && + detail.firstStockTakeQty != null && + detail.secondStockTakeQty == null; // 现在用户输入的是 total 和 bad,需要算 available = total - bad const totalQtyStr = isFirstSubmit ? recordInputs[detail.id]?.firstQty : recordInputs[detail.id]?.secondQty; @@ -225,6 +262,7 @@ const PickerStockTake: React.FC = ({ return; } + saveInFlightRef.current = true; setSaving(true); try { const request: SaveStockTakeRecordRequest = { @@ -233,6 +271,7 @@ const PickerStockTake: React.FC = ({ qty: availableValidated.qty, badQty: badValidated.qty, remark: isSecondSubmit ? (recordInputs[detail.id]?.remark || null) : null, + reviseFirstQty: revisingFirst, }; console.log("handleSaveStockTake: request:", request); console.log("handleSaveStockTake: selectedSession.stockTakeId:", selectedSession.stockTakeId); @@ -240,9 +279,24 @@ const PickerStockTake: React.FC = ({ await saveStockTakeRecord(request, selectedSession.stockTakeId, currentUserId); - onSnackbar(t("Stock take record saved successfully"), "success"); + const gapText = stockTakeQtyGapWarnText( + t, + totalQtyStr ?? "", + stockTakeHiddenOnHand(detail), + qtyGapWarnPercent, + ); + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:${isFirstSubmit ? "first" : "second"}`]: true })); + const oneChangeLeftText = + revisingFirst && (detail.pickerReviseCount ?? 0) === 0 ? t("oneChangeLeft") : ""; + const saveMessage = [t("Stock take record saved successfully"), gapText, oneChangeLeftText] + .filter(Boolean) + .join(" "); + onSnackbar(saveMessage, gapText || oneChangeLeftText ? "warning" : "success"); //await loadDetails(page, pageSize, { silent: true }); + if (revisingFirst) { + setEditingFirstIds((prev) => ({ ...prev, [detail.id]: false })); + } setInventoryLotDetails((prev) => prev.map((d) => d.id === detail.id @@ -251,10 +305,11 @@ const PickerStockTake: React.FC = ({ stockTakeRecordId: d.stockTakeRecordId ?? null, // 首次儲存後可從 response 取得,此處先保留 firstStockTakeQty: isFirstSubmit ? availableValidated.qty : d.firstStockTakeQty, firstBadQty: isFirstSubmit ? badValidated.qty : d.firstBadQty ?? null, - secondStockTakeQty: isSecondSubmit ? availableValidated.qty : d.secondStockTakeQty, - secondBadQty: isSecondSubmit ? badValidated.qty : d.secondBadQty ?? null, + secondStockTakeQty: revisingFirst ? null : (isSecondSubmit ? availableValidated.qty : d.secondStockTakeQty), + secondBadQty: revisingFirst ? null : (isSecondSubmit ? badValidated.qty : d.secondBadQty ?? null), remarks: isSecondSubmit ? (recordInputs[detail.id]?.remark || null) : d.remarks, stockTakeRecordStatus: "pass", + pickerReviseCount: revisingFirst ? (d.pickerReviseCount ?? 0) + 1 : d.pickerReviseCount, } : d ) @@ -277,6 +332,7 @@ const PickerStockTake: React.FC = ({ onSnackbar(errorMessage, "error"); } finally { setSaving(false); + saveInFlightRef.current = false; } }, [ @@ -286,6 +342,8 @@ const PickerStockTake: React.FC = ({ t, currentUserId, onSnackbar, + qtyGapWarnPercent, + canReviseFirstCount, ] ); @@ -540,7 +598,7 @@ const PickerStockTake: React.FC = ({ {t("Warehouse Location")} {t("Item-lotNo-ExpiryDate")} {t("UOM")} - {t("Stock Take Qty(include Bad Qty)= Available Qty")} + {t("Stock Take Qty(include Bad Qty)= Available Qty")} {t("Action")} {/*{t("Remark")}*/} {t("Record Status")} @@ -559,10 +617,28 @@ const PickerStockTake: React.FC = ({ ) : ( inventoryLotDetails.map((detail) => { const submitDisabled = isSubmitDisabled(detail); + const revisingFirst = canReviseFirstCount(detail); + const editingFirst = revisingFirst && !!editingFirstIds[detail.id]; + const sessionOpen = selectedSession?.status?.toLowerCase() !== "completed"; + const changeUsedUp = + sessionOpen && + detail.stockTakeRecordStatus?.toLowerCase() === "pass" && + detail.approverQty == null && + detail.firstStockTakeQty != null && + detail.secondStockTakeQty == null && + (detail.pickerReviseCount ?? 0) >= 2; + const showChangeButton = (revisingFirst || changeUsedUp) && !editingFirst; + const oneChanceLeft = revisingFirst && (detail.pickerReviseCount ?? 0) === 1; const isFirstSubmit = detail.firstStockTakeQty == null; const isSecondSubmit = detail.firstStockTakeQty != null && detail.secondStockTakeQty == null; + const showFirstInput = (!submitDisabled && isFirstSubmit) || editingFirst; + const savedFirstQty = sanitizeStockTakeQtyInput( + String(Math.trunc(Number(detail.firstStockTakeQty ?? 0))) + ); + const editedFirstQty = sanitizeStockTakeQtyInput(recordInputs[detail.id]?.firstQty || ""); + const firstQtyChanged = editedFirstQty !== "" && editedFirstQty !== savedFirstQty; return ( @@ -572,16 +648,19 @@ const PickerStockTake: React.FC = ({ - + {detail.itemCode || "-"} {detail.itemName || "-"} - + {detail.lotNo || "-"} {detail.expiryDate @@ -592,16 +671,23 @@ const PickerStockTake: React.FC = ({ {detail.uom || "-"} {/* Qty + Bad Qty 合并显示/输入 */} - + {/* First */} - {!submitDisabled && isFirstSubmit ? ( + {showFirstInput ? ( + {t("First")}: + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:first`]: false })) + } + onBlur={() => + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:first`]: true })) + } inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }} onKeyDown={blockNonIntegerKeys} onChange={(e) => { @@ -610,9 +696,12 @@ const PickerStockTake: React.FC = ({ if (val.includes("-")) return; setRecordInputs(prev => ({ ...prev, [detail.id]: { ...prev[detail.id], firstQty: val } })); }} + InputProps={{ + endAdornment: stockTakeQtyEndAdornment(detail.uomShortDesc), + }} sx={{ - width: 130, - minWidth: 130, + width: 148, + minWidth: 148, "& .MuiInputBase-input": { height: "1.4375em", padding: "4px 8px", @@ -652,40 +741,47 @@ const PickerStockTake: React.FC = ({ placeholder={t("Bad Qty")} /> */} + + + + ) : detail.firstStockTakeQty != null ? ( + - = - {formatNumber( - parseFloat(recordInputs[detail.id]?.firstQty || "0") - - parseFloat(recordInputs[detail.id]?.firstBadQty || "0") - )} + {t("First")}:{" "} + + - ) : detail.firstStockTakeQty != null ? ( - - {t("First")}:{" "} - {formatNumber( - (detail.firstStockTakeQty ?? 0) + - (detail.firstBadQty ?? 0) - )}{" "} - {/* - ( - {formatNumber( - detail.firstBadQty ?? 0 - )} - */} - ={" "} - {formatNumber(detail.firstStockTakeQty ?? 0)} - ) : null} {/* Second */} {!submitDisabled && isSecondSubmit ? ( + {t("Second")}: + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:second`]: false })) + } + onBlur={() => + setGapCheckOpen((prev) => ({ ...prev, [`${detail.id}:second`]: true })) + } inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }} onKeyDown={blockNonIntegerKeys} onChange={(e) => { @@ -694,9 +790,12 @@ const PickerStockTake: React.FC = ({ if (val.includes("-")) return; setRecordInputs(prev => ({ ...prev, [detail.id]: { ...prev[detail.id], secondQty: val } })); }} + InputProps={{ + endAdornment: stockTakeQtyEndAdornment(detail.uomShortDesc), + }} sx={{ - width: 130, - minWidth: 130, + width: 148, + minWidth: 148, "& .MuiInputBase-input": { height: "1.4375em", padding: "4px 8px", @@ -728,30 +827,30 @@ const PickerStockTake: React.FC = ({ placeholder={t("Bad Qty")} /> */} + + + + ) : detail.secondStockTakeQty != null ? ( + - = - {formatNumber( - parseFloat(recordInputs[detail.id]?.secondQty || "0") - - parseFloat(recordInputs[detail.id]?.secondBadQty || "0") - )} + {t("Second")}:{" "} + + - ) : detail.secondStockTakeQty != null ? ( - - {t("Second")}:{" "} - {formatNumber( - (detail.secondStockTakeQty ?? 0) + - (detail.secondBadQty ?? 0) - )}{" "} - {/* - ( - {formatNumber( - detail.secondBadQty ?? 0 - )} - */} - ={" "} - {formatNumber(detail.secondStockTakeQty ?? 0)} - ) : null} {!detail.firstStockTakeQty && @@ -772,13 +871,39 @@ const PickerStockTake: React.FC = ({ - + {oneChanceLeft && ( + + {t("oneChangeLeft")} + + )} {/* Remark */} diff --git a/src/components/StockTakeManagement/StockTakeQtyGapHint.tsx b/src/components/StockTakeManagement/StockTakeQtyGapHint.tsx new file mode 100644 index 00000000..3323d5e1 --- /dev/null +++ b/src/components/StockTakeManagement/StockTakeQtyGapHint.tsx @@ -0,0 +1,40 @@ +"use client"; + +import Typography from "@mui/material/Typography"; +import { useTranslation } from "react-i18next"; +import { STOCK_TAKE_QTY_GAP_WARN_PERCENT, stockTakeQtyGapWarnText } from "./stockTakeQtyGapWarning"; + +/** Shown after the field is left, or flagged on save. Does not show the hidden on-hand quantity. */ +export default function StockTakeQtyGapHint({ + entered, + currentQty, + open, + threshold = STOCK_TAKE_QTY_GAP_WARN_PERCENT, +}: { + entered: string; + currentQty: number | null | undefined; + /** False while the user is still typing. */ + open: boolean; + /** Warn when the count differs from on-hand by at least this percent. */ + threshold?: number; +}) { + const { t } = useTranslation("stockTake"); + if (!open) return null; + const text = stockTakeQtyGapWarnText(t, entered, currentQty, threshold); + if (!text) return null; + return ( + + {text} + + ); +} diff --git a/src/components/StockTakeManagement/StockTakeTab.tsx b/src/components/StockTakeManagement/StockTakeTab.tsx index ad4af356..2ef820ba 100644 --- a/src/components/StockTakeManagement/StockTakeTab.tsx +++ b/src/components/StockTakeManagement/StockTakeTab.tsx @@ -1,14 +1,23 @@ "use client"; -import { Box, Tab, Tabs, Snackbar, Alert, CircularProgress, Typography } from "@mui/material"; -import { useState, useCallback, useEffect } from "react"; +import { Box, Tab, Tabs, Snackbar, Alert, CircularProgress, Typography, TextField, Button, Stack } from "@mui/material"; +import { useState, useCallback, useEffect, useRef } from "react"; +import { useSession } from "next-auth/react"; import { useTranslation } from "react-i18next"; +import { AUTH } from "@/authorities"; +import { SessionWithTokens } from "@/config/authConfig"; import { AllPickedStockTakeListReponse, getLatestApproverStockTakeHeader } from "@/app/api/stockTake/actions"; import PickerCardList from "./PickerCardList"; import type { PickerCardListFilters } from "./PickerCardList"; import PickerStockTake from "./PickerStockTake"; import PickerReStockTake from "./PickerReStockTake"; import ApproverStockTakeAll from "./ApproverStockTakeAll"; +import { useStockTakeQtyGapWarnPercent } from "./useStockTakeQtyGapWarnPercent"; +import { + parseQtyGapWarnPercent, + saveStockTakeQtyGapWarnPercent, +} from "./qtyGapWarnSettingClient"; +import { STOCK_TAKE_QTY_GAP_WARN_PERCENT } from "./stockTakeQtyGapWarning"; type ViewScope = "picker" | "approver-all"; const DEFAULT_PICKER_CARD_LIST_FILTERS: PickerCardListFilters = { @@ -21,6 +30,14 @@ const DEFAULT_PICKER_CARD_LIST_FILTERS: PickerCardListFilters = { const StockTakeTab: React.FC = () => { const { t } = useTranslation(["stockTake", "common"]); + const { data: session } = useSession() as { data: SessionWithTokens | null }; + const isAdmin = (session?.abilities ?? session?.user?.abilities ?? []).some( + (ability) => String(ability).trim() === AUTH.ADMIN, + ); + const qtyGapWarnPercent = useStockTakeQtyGapWarnPercent(); + const [qtyGapDraft, setQtyGapDraft] = useState(String(STOCK_TAKE_QTY_GAP_WARN_PERCENT)); + const [qtyGapSaving, setQtyGapSaving] = useState(false); + const qtyGapSaveLock = useRef(false); const [tabValue, setTabValue] = useState(0); const [selectedSession, setSelectedSession] = useState(null); const [viewMode, setViewMode] = useState<"details" | "reStockTake">("details"); @@ -66,6 +83,31 @@ const StockTakeTab: React.FC = () => { }); }, []); + useEffect(() => { + setQtyGapDraft(String(qtyGapWarnPercent)); + }, [qtyGapWarnPercent]); + + const saveQtyGapWarnPercent = useCallback(async () => { + if (!isAdmin || qtyGapSaveLock.current) return; + const parsed = Number(qtyGapDraft.trim()); + if (!Number.isInteger(parsed) || parsed < 0 || parsed > 1000) { + handleSnackbar(t("qtyGapWarnPercentInvalid"), "warning"); + return; + } + qtyGapSaveLock.current = true; + setQtyGapSaving(true); + try { + await saveStockTakeQtyGapWarnPercent(parsed); + setQtyGapDraft(String(parseQtyGapWarnPercent(String(parsed)))); + handleSnackbar(t("qtyGapWarnPercentSaved"), "success"); + } catch (e) { + handleSnackbar(e instanceof Error ? e.message : t("qtyGapWarnPercentInvalid"), "error"); + } finally { + qtyGapSaveLock.current = false; + setQtyGapSaving(false); + } + }, [handleSnackbar, isAdmin, qtyGapDraft, t]); + useEffect(() => { if (tabValue !== 1 && tabValue !== 2) return; setApproverLoading(true); @@ -103,9 +145,15 @@ const StockTakeTab: React.FC = () => { setSnackbar({ ...snackbar, open: false })} + onClose={(_event, reason) => { + if (reason === "clickaway") return; + setSnackbar((prev) => ({ ...prev, open: false })); + }} > - setSnackbar({ ...snackbar, open: false })} severity={snackbar.severity}> + setSnackbar((prev) => ({ ...prev, open: false }))} + severity={snackbar.severity} + > {snackbar.message} @@ -115,6 +163,46 @@ const StockTakeTab: React.FC = () => { return ( + {isAdmin && ( + + + {t("qtyGapWarnPercent")} + + setQtyGapDraft(e.target.value.replace(/[^\d]/g, ""))} + inputProps={{ min: 0, max: 1000, inputMode: "numeric" }} + sx={{ + width: 88, + m: 0, + "& .MuiFilledInput-root": { height: 40 }, + "& .MuiFilledInput-input.MuiInputBase-inputSizeSmall": { + height: 40, + boxSizing: "border-box", + paddingTop: 0, + paddingBottom: 0, + lineHeight: "40px", + }, + }} + /> + + + )} { @@ -186,9 +274,15 @@ const StockTakeTab: React.FC = () => { setSnackbar({ ...snackbar, open: false })} + onClose={(_event, reason) => { + if (reason === "clickaway") return; + setSnackbar((prev) => ({ ...prev, open: false })); + }} > - setSnackbar({ ...snackbar, open: false })} severity={snackbar.severity}> + setSnackbar((prev) => ({ ...prev, open: false }))} + severity={snackbar.severity} + > {snackbar.message} diff --git a/src/components/StockTakeManagement/qtyGapWarnSettingClient.ts b/src/components/StockTakeManagement/qtyGapWarnSettingClient.ts new file mode 100644 index 00000000..ac6e81ee --- /dev/null +++ b/src/components/StockTakeManagement/qtyGapWarnSettingClient.ts @@ -0,0 +1,49 @@ +"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 })); +} diff --git a/src/components/StockTakeManagement/stockTakeQtyAdornment.tsx b/src/components/StockTakeManagement/stockTakeQtyAdornment.tsx new file mode 100644 index 00000000..88e7b7c2 --- /dev/null +++ b/src/components/StockTakeManagement/stockTakeQtyAdornment.tsx @@ -0,0 +1,55 @@ +"use client"; + +import InputAdornment from "@mui/material/InputAdornment"; +import Typography from "@mui/material/Typography"; + +/** Large unit reminder inside the count field, same style as PO stock-in qty. */ +export function stockTakeQtyEndAdornment(uomShortDesc?: string | null) { + const label = uomShortDesc?.trim() ?? ""; + if (!label) return undefined; + return ( + + + {label} + + + ); +} + +/** Saved count with the same large unit label, e.g. 140 包. */ +export function StockTakeQtyWithUnit({ + qty, + uomShortDesc, +}: { + qty: string; + uomShortDesc?: string | null; +}) { + const unit = uomShortDesc?.trim() ?? ""; + return ( + <> + {qty} + {unit ? ( + + {unit} + + ) : null} + + ); +} diff --git a/src/components/StockTakeManagement/stockTakeQtyGapWarning.ts b/src/components/StockTakeManagement/stockTakeQtyGapWarning.ts new file mode 100644 index 00000000..5bdb1144 --- /dev/null +++ b/src/components/StockTakeManagement/stockTakeQtyGapWarning.ts @@ -0,0 +1,62 @@ +/** Warn when the typed count is this far from hidden on-hand, either higher or lower. Save stays allowed. */ +export const STOCK_TAKE_QTY_GAP_WARN_PERCENT = 50; + +export type StockTakeQtyGap = + | { kind: "percent"; pct: number } + | { kind: "over" }; + +/** + * On-hand used only for the gap check. Prefer the stock-take book qty (frozen for this count); + * fall back to live available qty. Callers must not render this number. + */ +export function stockTakeHiddenOnHand(detail: { + bookQty?: number | null; + availableQty?: number | null; +}): number | null { + if (detail.bookQty != null && Number.isFinite(Number(detail.bookQty))) { + return Number(detail.bookQty); + } + if (detail.availableQty != null && Number.isFinite(Number(detail.availableQty))) { + return Number(detail.availableQty); + } + return null; +} + +/** Null when the field is empty, or the gap is within the threshold. */ +export function stockTakeQtyGapWarning( + enteredRaw: string, + currentQty: number | null | undefined, + threshold = STOCK_TAKE_QTY_GAP_WARN_PERCENT, +): StockTakeQtyGap | null { + const raw = enteredRaw.trim(); + if (!raw) return null; + const entered = Number(raw); + if (!Number.isFinite(entered)) return null; + if (currentQty == null || !Number.isFinite(Number(currentQty))) return null; + const current = Number(currentQty); + if (current === 0) { + return entered === 0 ? null : { kind: "over" }; + } + const pct = (Math.abs(entered - current) / Math.abs(current)) * 100; + if (pct + 1e-9 < threshold) return null; + return { kind: "percent", pct: Math.round(pct) }; +} + +export function stockTakeQtyGapWarnText( + t: (key: string, options?: Record) => string, + enteredRaw: string, + currentQty: number | null | undefined, + threshold = STOCK_TAKE_QTY_GAP_WARN_PERCENT, +): string | null { + const gap = stockTakeQtyGapWarning(enteredRaw, currentQty, threshold); + if (!gap) return null; + if (gap.kind === "percent") { + return t("stockTakeQtyGapWarn", { + pct: gap.pct, + threshold, + }); + } + return t("stockTakeQtyGapWarnOver", { + threshold, + }); +} diff --git a/src/components/StockTakeManagement/useStockTakeQtyGapWarnPercent.ts b/src/components/StockTakeManagement/useStockTakeQtyGapWarnPercent.ts new file mode 100644 index 00000000..289214b2 --- /dev/null +++ b/src/components/StockTakeManagement/useStockTakeQtyGapWarnPercent.ts @@ -0,0 +1,33 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { STOCK_TAKE_QTY_GAP_WARN_PERCENT } from "./stockTakeQtyGapWarning"; +import { + fetchStockTakeQtyGapWarnPercent, + STOCK_TAKE_QTY_GAP_SETTING_EVENT, +} from "./qtyGapWarnSettingClient"; + +/** Warning threshold from settings (`STOCK_TAKE.qtyGapWarnPercent`), default 50. */ +export function useStockTakeQtyGapWarnPercent(): number { + const [percent, setPercent] = useState(STOCK_TAKE_QTY_GAP_WARN_PERCENT); + + useEffect(() => { + let cancelled = false; + fetchStockTakeQtyGapWarnPercent() + .then((n) => { + if (!cancelled) setPercent(n); + }) + .catch(() => {}); + const onChange = (event: Event) => { + const next = (event as CustomEvent).detail; + if (Number.isFinite(next)) setPercent(next); + }; + window.addEventListener(STOCK_TAKE_QTY_GAP_SETTING_EVENT, onChange); + return () => { + cancelled = true; + window.removeEventListener(STOCK_TAKE_QTY_GAP_SETTING_EVENT, onChange); + }; + }, []); + + return percent; +} diff --git a/src/components/charts/SafeApexCharts.tsx b/src/components/charts/SafeApexCharts.tsx index 9b29f4b1..0e41126b 100644 --- a/src/components/charts/SafeApexCharts.tsx +++ b/src/components/charts/SafeApexCharts.tsx @@ -150,6 +150,34 @@ function buildApexConfig( const EMPTY_MESSAGE = "暫無圖表資料(後端無法連線或此區間無資料)。"; +/** Apex mutates `options` in place (circular refs). Never throw during render. */ +function safeStringify(value: unknown): string { + const seen = new WeakSet(); + try { + return JSON.stringify(value, (_key, nested) => { + if (typeof nested === "function") return undefined; + if (typeof nested === "object" && nested !== null) { + if (seen.has(nested)) return undefined; + seen.add(nested); + } + return nested; + }); + } catch { + return ""; + } +} + +function destroyChart(chartRef: { current: { destroy: () => void } | null }) { + const current = chartRef.current; + chartRef.current = null; + if (!current) return; + try { + current.destroy(); + } catch { + /* ignore */ + } +} + export default function SafeApexCharts(props: SafeApexChartsProps) { const { type, series, options, height, width, chartRevision, allowZeroSeries = false, ...rest } = props; const containerRef = useRef(null); @@ -162,18 +190,11 @@ export default function SafeApexCharts(props: SafeApexChartsProps) { sanitized = alignSeriesToCategoryCount(sanitized, cats.length); } - if (shouldShowPlaceholder(type, options, sanitized, allowZeroSeries)) { - return ( - - {EMPTY_MESSAGE} - - ); - } - let chartOptions = options; let renderSeries: ApexChartProps["series"] = sanitized; + let showPlaceholder = shouldShowPlaceholder(type, options, sanitized, allowZeroSeries); - if (isRadialChart(type) && isNumberArray(sanitized)) { + if (!showPlaceholder && isRadialChart(type) && isNumberArray(sanitized)) { const prev = Array.isArray(options?.labels) ? (options!.labels as unknown[]) : []; const pairs = sanitized.map((v, i) => { const n = Number.isFinite(v) ? v : 0; @@ -183,20 +204,31 @@ export default function SafeApexCharts(props: SafeApexChartsProps) { }); const nonzero = pairs.filter((p) => p.v > 0); if (nonzero.length === 0) { - return ( - - {EMPTY_MESSAGE} - - ); + showPlaceholder = true; + } else { + renderSeries = nonzero.map((p) => p.v); + chartOptions = { ...options, labels: nonzero.map((p) => p.label) }; } - renderSeries = nonzero.map((p) => p.v); - chartOptions = { ...options, labels: nonzero.map((p) => p.label) }; } const chartType = String(type ?? "line"); - const configSnapshot = `${String(chartRevision ?? "")}|${chartType}|${JSON.stringify(renderSeries ?? null)}|${JSON.stringify(chartOptions ?? {})}|${String(height ?? "")}|${String(width ?? "")}`; + const configSnapshot = [ + String(chartRevision ?? ""), + chartType, + String(showPlaceholder), + safeStringify(renderSeries ?? null), + safeStringify(cats ?? null), + safeStringify(chartOptions?.labels ?? null), + String(height ?? ""), + String(width ?? ""), + ].join("|"); useEffect(() => { + if (showPlaceholder) { + destroyChart(chartRef); + return; + } + const el = containerRef.current; if (!el) return; @@ -219,12 +251,7 @@ export default function SafeApexCharts(props: SafeApexChartsProps) { if (disposed || containerRef.current !== el) { if (chartRef.current === instance) { - try { - instance.destroy(); - } catch { - /* ignore */ - } - chartRef.current = null; + destroyChart(chartRef); } return; } @@ -236,21 +263,21 @@ export default function SafeApexCharts(props: SafeApexChartsProps) { return () => { disposed = true; - const c = chartRef.current; - chartRef.current = null; - if (c) { - try { - c.destroy(); - } catch { - /* ignore */ - } - } + destroyChart(chartRef); }; }, [configSnapshot]); const minH = typeof height === "number" ? height : typeof height === "string" ? height : 240; const dom = rest as { className?: string; id?: string; style?: CSSProperties; sx?: object }; + if (showPlaceholder) { + return ( + + {EMPTY_MESSAGE} + + ); + } + return ( { + const refreshToken = token.refreshToken; + if (!refreshToken || !REFRESH_TOKEN_API_PATH || REFRESH_TOKEN_API_PATH === "undefined/refresh-token") { + return { + ...token, + error: "RefreshAccessTokenError", + refreshFailedAt: Date.now(), + }; + } + + try { + const res = await fetch(REFRESH_TOKEN_API_PATH, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ refreshToken }), + }); + if (!res.ok) { + return { + ...token, + error: "RefreshAccessTokenError", + refreshFailedAt: Date.now(), + }; + } + const data = (await res.json()) as { + accessToken?: string; + refreshToken?: string; + }; + if (!data.accessToken) { + return { + ...token, + error: "RefreshAccessTokenError", + refreshFailedAt: Date.now(), + }; + } + return { + ...token, + accessToken: data.accessToken, + refreshToken: data.refreshToken ?? refreshToken, + error: undefined, + refreshFailedAt: undefined, + }; + } catch { + return { + ...token, + error: "RefreshAccessTokenError", + refreshFailedAt: Date.now(), + }; + } +} + // Extend the built-in types declare module "next-auth" { interface Session { @@ -13,6 +85,7 @@ declare module "next-auth" { /** JWT expiry (seconds since epoch); used to avoid redirecting to dashboard when token is expired */ exp?: number; locale?: string; + error?: string; } interface User { @@ -31,6 +104,9 @@ declare module "next-auth/jwt" { refreshToken?: string; abilities: string[]; locale?: string; + error?: string; + /** Epoch ms of last failed refresh — used as cooldown to avoid hammering /refresh-token */ + refreshFailedAt?: number; } } @@ -72,7 +148,7 @@ export const authOptions: AuthOptions = { signIn: "/login", }, callbacks: { - // Persist custom fields into the JWT token + // Persist custom fields into the JWT token; refresh backend access JWT near expiry async jwt({ token, user, trigger, session }) { // First sign-in: `user` is available if (user) { @@ -80,21 +156,49 @@ export const authOptions: AuthOptions = { token.accessToken = user.accessToken; token.refreshToken = user.refreshToken; token.abilities = user.abilities ?? []; + token.error = undefined; + token.refreshFailedAt = undefined; const loginLocale = (user as { locale?: string }).locale; if (loginLocale) { token.locale = loginLocale; } + return token; } - if (trigger === "update" && session && typeof session === "object" && "locale" in session) { - const next = (session as { locale?: string }).locale; - if (next === "zh" || next === "en") { - token.locale = next; + if (trigger === "update" && session && typeof session === "object") { + if ("locale" in session) { + const next = (session as { locale?: string }).locale; + if (next === "zh" || next === "en") { + token.locale = next; + } + } + if ("accessToken" in session && typeof (session as { accessToken?: string }).accessToken === "string") { + token.accessToken = (session as { accessToken: string }).accessToken; + } + if ("refreshToken" in session && typeof (session as { refreshToken?: string }).refreshToken === "string") { + token.refreshToken = (session as { refreshToken: string }).refreshToken; } } - // On subsequent calls (token refresh, session access), user is not present - // so we just return the existing token with custom fields preserved + const expiresAt = backendAccessTokenExpiresAtMs(token.accessToken); + // Can't parse exp → leave as-is (avoid refresh thrash). Still-valid → keep. + if (expiresAt === null || Date.now() < expiresAt - ACCESS_TOKEN_REFRESH_SKEW_MS) { + return token; + } + + // Cooldown after a failed refresh so session polls don't hammer /refresh-token + if ( + token.refreshFailedAt && + Date.now() - token.refreshFailedAt < REFRESH_FAILURE_COOLDOWN_MS + ) { + return token; + } + + // Access token expired or near expiry — refresh using refresh token + if (token.refreshToken) { + return refreshAccessToken(token); + } + return token; }, @@ -106,6 +210,7 @@ export const authOptions: AuthOptions = { session.abilities = token.abilities as string[]; session.exp = token.exp as number | undefined; session.locale = token.locale as string | undefined; + session.error = token.error as string | undefined; // Also add abilities to session.user for easier client-side access if (session.user) { diff --git a/src/config/reportConfig.ts b/src/config/reportConfig.ts index f60a290a..483e61cf 100644 --- a/src/config/reportConfig.ts +++ b/src/config/reportConfig.ts @@ -1,5 +1,5 @@ /** FP-MTMS Version Checklist | Functions Ref. No. 39 | v1.0.0 | 2026-08-03 */ -export type FieldType = 'date' | 'text' | 'select' | 'number' | 'checkbox'; +export type FieldType = 'date' | 'month' | 'text' | 'select' | 'number' | 'checkbox'; import { NEXT_PUBLIC_API_URL } from "@/config/api"; @@ -29,6 +29,8 @@ export interface ReportField { multiline?: boolean; /** Rows for multiline text areas. Default 4. */ minRows?: number; + /** Month fields: GET returning { earliest: "YYYY-MM-DD" }. List runs from that month through the current month. */ + earliestMonthEndpoint?: string; } export type ReportResponseType = 'pdf' | 'excel'; @@ -316,19 +318,23 @@ export const REPORTS: ReportDefinition[] = [ pasteItemCodeField(), ] }, - /* Hidden for now: 庫存流水帳報告 (rep-020) { id: "rep-020", title: "庫存流水帳報告", apiEndpoint: `${NEXT_PUBLIC_API_URL}/report/print-stock-lot-ledger`, responseType: "excel", fields: [ - { label: "期間起 Period From(永遠該月1日)", name: "lastInDateStart", type: "date", required: true }, + { + label: "期間起 Period From", + name: "lastInDateStart", + type: "month", + required: true, + earliestMonthEndpoint: `${NEXT_PUBLIC_API_URL}/report/stock-lot-ledger-earliest`, + }, { label: "期間迄 Period To", name: "lastInDateEnd", type: "date", required: true }, - { label: "貨品編號 Item Code", name: "itemCode", type: "text", required: false }, + asyncItemCodeField(), ], }, - */ /* { id: "rep-007", diff --git a/src/i18n/en/common.json b/src/i18n/en/common.json index a3b15c4e..e07fb3ca 100644 --- a/src/i18n/en/common.json +++ b/src/i18n/en/common.json @@ -1,131 +1,133 @@ { - "Actions": "操作", - "Add Document": "新增文件", + "Actions": "Actions", + "Add Document": "Add Document", "All": "All", - "Allergic Substances": "過敏原", + "Allergic Substances": "Allergens", "An error has occurred. Please try again later.": "An error has occurred. Please try again later.", - "Are you sure you want to delete this item?": "您確定要刪除此項目嗎?", - "Back": "返回", - "Basic Info": "基本資訊", + "Are you sure you want to delete this item?": "Are you sure you want to delete this item?", + "Back": "Back", + "Basic Info": "Basic Info", "Bom Required Qty": "BOM Required Qty", "Bom UOM": "BOM UOM", - "Brand": "品牌", - "CMB": "消耗品", - "CO": "消耗品", - "Cancel": "取消", - "Column Name": "欄位名稱", - "Coming soon": "即將推出", - "Complexity": "複雜度", - "Confirm": "確認", - "Confirm Delete": "確認刪除", - "Cost (HKD)": "費用 (HKD)", - "Current total": "目前總和", - "Day Before Yesterday": "前天", - "Delete": "刪除", - "Delete Failed": "刪除失敗", + "Brand": "Brand", + "CMB": "Consumable", + "CO": "Consumable", + "Cancel": "Cancel", + "Column Name": "Column Name", + "Coming soon": "Coming soon", + "Complexity": "Complexity", + "Confirm": "Confirm", + "Confirm Delete": "Confirm Delete", + "Cost (HKD)": "Cost (HKD)", + "Current total": "Current total", + "Day Before Yesterday": "Day Before Yesterday", + "Delete": "Delete", + "Delete Failed": "Delete Failed", "Do you want to delete?": "Do you want to delete?", - "Density": "濃淡", - "Depth": "顔色深淺度 深1淺5", - "Description": "描述", - "Details": "詳情", - "Duration (Minutes)": "時間(分)", - "Edit": "編輯", - "Enter any additional observations or notes...": "輸入其他觀察或備註...", - "Enter or select remark": "輸入或選擇備註", + "Density": "Density", + "Depth": "Color depth (dark 1 / light 5)", + "Description": "Description", + "Details": "Details", + "Duration (Minutes)": "Duration (Minutes)", + "Edit": "Edit", + "Enter any additional observations or notes...": "Enter any additional observations or notes...", + "Enter or select remark": "Enter or select remark", "Error saving data": "Error saving data", - "Failed to fetch data": "無法取得資料", - "Filter": "過濾", - "Finished Good Detail": "成品出倉詳情", - "Finished Good Management": "成品出倉管理", - "Finished Good Order": "成品出倉", - "Float": "浮沉", - "General Data": "基本資料", - "Grade {{grade}}": "等級 {{grade}}", - "Invoice": "發票", - "Invoice Date": "發票日期", + "Failed to fetch data": "Failed to fetch data", + "Filter": "Filter", + "Finished Good Detail": "Finished Good Detail", + "Finished Good Management": "Finished Good Management", + "Finished Good Order": "Finished Good Order", + "Float": "Float", + "General Data": "General Data", + "Grade {{grade}}": "Grade {{grade}}", + "Invoice": "Invoice", + "Invoice Date": "Invoice Date", "IP": "IP", "Item Code": "Item Code", "Item Name": "Item Name", - "Loading": "載入中...", - "Loading order summary": "正在載入訂單摘要", - "Location": "位置", - "MA": "材料", - "MAT": "材料", - "MI": "雜項", - "Material Name": "材料清單", + "Loading": "Loading...", + "Loading order summary": "Loading order summary", + "Location": "Location", + "MA": "Material", + "MAT": "Material", + "MI": "Miscellaneous", + "Material Name": "Material List", "Name": "Name", - "Min": "最小值", - "NM": "雜項及非消耗品", - "No": "否", - "No Lot": "沒有批號", - "No data available": "沒有資料", - "No options": "沒有選項", - "Order": "順序", + "Min": "Min", + "NM": "Miscellaneous and non-consumables", + "No": "No", + "No Lot": "No Lot", + "No data available": "No data available", + "No options": "No options", + "Order": "Order", "Pending": "Pending", "Port": "Port", - "Please Select BOM": "請選擇 BOM", - "Please try again later.": "請稍後重試。", - "Project Code": "專案代碼", - "Project Code and Name": "專案代碼與名稱", - "QC Template not found": "找不到 QC 範本", - "Qty": "數量", - "RM": "原料", - "Range": "範圍", - "Refresh": "重新載入", - "Remarks": "備註", - "Remove Document": "移除文件", - "Report": "報告", + "Please Select BOM": "Please select BOM", + "Please try again later.": "Please try again later.", + "Project Code": "Project Code", + "Project Code and Name": "Project Code and Name", + "QC Template not found": "QC template not found", + "Qty": "Qty", + "RM": "Raw material", + "Range": "Range", + "Refresh": "Refresh", + "Remarks": "Remarks", + "Remove Document": "Remove Document", + "Report": "Report", "Reset": "Reset", - "Row per page": "每頁行數", - "Rows per page": "每頁行數", - "Sales Qty": "銷售數量", - "Sales UOM": "銷售單位", - "Save": "儲存", - "Saving": "儲存中", + "Row per page": "Rows per page", + "Rows per page": "Rows per page", + "Sales Qty": "Sales Qty", + "Sales UOM": "Sales UOM", + "Save": "Save", + "Saving": "Saving", "Search": "Search", + "More criteria": "More criteria", + "Fewer criteria": "Fewer criteria", "Search Criteria": "Search Criteria", - "Select Date": "選擇日期", - "Session expired or unauthorized.": "工作階段已過期或未經授權。", + "Select Date": "Select Date", + "Session expired or unauthorized.": "Session expired or unauthorized.", "Sign out": "Sign out", "Language": "Language", - "Status": "狀態", - "Stock Qty": "庫存數量", - "Supporting Document": "證明文件", - "Task": "任務", - "Time Sequence": "時段", + "Status": "Status", + "Stock Qty": "Stock Qty", + "Supporting Document": "Supporting Document", + "Task": "Task", + "Time Sequence": "Time Sequence", "Type": "Type", - "Today": "今天", - "Total weighting must equal 1": "權重總和必須等於 1", - "Unauthorized: Please log in again": "未經授權:請重新登入", - "Uom": "單位", - "Update Failed": "更新失敗", - "Update Success": "更新成功", - "Weighting must be a number": "權重必須為數字", - "Yes": "是", - "Yesterday": "昨天", - "all": "全部", + "Today": "Today", + "Total weighting must equal 1": "Total weighting must equal 1", + "Unauthorized: Please log in again": "Unauthorized: Please log in again", + "Uom": "UOM", + "Update Failed": "Update Failed", + "Update Success": "Update Success", + "Weighting must be a number": "Weighting must be a number", + "Yes": "Yes", + "Yesterday": "Yesterday", + "all": "All", "bomWeighting": "BOM Weighting Score", - "cmb": "消耗品", - "collapsible table": "可折疊表格", - "consumable": "消耗品", - "consumables": "消耗品", - "create": "新增", - "edit": "編輯", - "expand row": "展開行", - "group mode": "群組模式", - "item": "貨品", - "items": "物品", - "mat": "原料", - "menu": "選單", - "nm": "雜項及非消耗品", - "non-consumables": "非消耗品", - "other": "其他", - "profile": "個人資料", - "revert": "還原", - "settings": "設定", - "stockRecord": "盤點記錄", - "stocktakemanagement": "盤點管理", - "testing sections tabs": "測試區域分頁", - "warehouse": "倉庫", - "材料": "材料" + "cmb": "Consumable", + "collapsible table": "Collapsible table", + "consumable": "Consumable", + "consumables": "Consumables", + "create": "Create", + "edit": "Edit", + "expand row": "Expand row", + "group mode": "Group mode", + "item": "Item", + "items": "Items", + "mat": "Raw material", + "menu": "Menu", + "nm": "Miscellaneous and non-consumables", + "non-consumables": "Non-consumables", + "other": "Other", + "profile": "Profile", + "revert": "Revert", + "settings": "Settings", + "stockRecord": "Stock record", + "stocktakemanagement": "Stock take management", + "testing sections tabs": "Testing section tabs", + "warehouse": "Warehouse", + "材料": "Material" } diff --git a/src/i18n/en/doWorkbench.json b/src/i18n/en/doWorkbench.json index 321a91a6..a74b25be 100644 --- a/src/i18n/en/doWorkbench.json +++ b/src/i18n/en/doWorkbench.json @@ -45,5 +45,47 @@ "DO Workbench Search": "DO Workbench Search", "completed": "completed", "items": "items", - "pending": "pending" + "pending": "pending", + "Pick Order Detail": "Pick Detail", + "Etra Pick Order Detail": "Etra", + "Finished Good Record": "FG Record", + "Finished Good Record (All)": "FG Record (All)", + "Ticket Release Table": "Ticket Release", + "FG Carton Qty": "Carton Qty", + "成品出倉出箱數量": "Carton Qty", + "Truck Routing Summary": "Routing Summary", + "送貨路線摘要": "Truck Routing Summary", + "車線-X": "Truck X", + "Confirm print drafts": "Print {{count}} draft(s)?", + "Truck Routing Summary (Workbench)": "Truck Routing Summary (Workbench)", + "2/F or 4/F": "2/F or 4/F", + "Lane": "Lane", + "Shop Code": "Shop group", + "Shop code": "Shop code", + "Back to previous level": "Back", + "All lanes": "All lanes", + "All shops": "All shop groups", + "Cartons by lane": "Cartons by lane", + "Cartons by shop": "Cartons by shop", + "Cartons by shop group": "Cartons by shop group", + "Cartons by floor": "Cartons by floor", + "Share": "Share", + "Click a row to filter": "Click a row to filter", + "Click a bar to filter": "Click a bar to filter", + "Reset filters": "Reset filters", + "Cartons": "Cartons", + "Date": "Date", + "Download Excel": "Download Excel", + "Download this view Excel": "Download Excel (Selected)", + "Download period Excel": "Download Excel (Complete)", + "Download this view Excel hint": "Excel of the current floor, lane, shop, and date, plus the chart breakdown.", + "Download period Excel hint": "Excel with last 7 days, this month, and this year. Not limited to the current view.", + "Filtered": "Filtered", + "Breakdown": "Breakdown", + "All floors": "All floors", + "FG carton qty filtered title": "FG carton qty (filtered) - {{floor}} - {{lane}} - {{shop}} - {{date}}", + "Generating...": "Generating...", + "Download report (PDF)": "Download report (PDF)", + "Unpicked orders confirm download": "This lane still has {{count}} unpicked order(s).\nPrint / download the truck routing summary anyway?", + "Failed to download Workbench truck routing summary. Please try again later.": "Failed to download Workbench truck routing summary. Please try again later." } diff --git a/src/i18n/en/inventory.json b/src/i18n/en/inventory.json index 716b1ab5..5d170b12 100644 --- a/src/i18n/en/inventory.json +++ b/src/i18n/en/inventory.json @@ -16,7 +16,14 @@ "Download QR Code": "Download QR Code", "Edit mode": "Edit mode", "Enter item code or name to search": "Enter item code or name to search", + "Area": "Area", "Expiry Date": "Expiry Date", + "Floor": "Floor", + "Item Search": "Item Search", + "Location Search": "Location Search", + "Select a floor to search by location.": "Select a floor to search by location.", + "Select floor first": "Select a floor first", + "Select warehouse first": "Select a warehouse first", "FG": "Finished good", "Failed to transfer stock": "Failed to transfer stock", "Failed to transfer stock. Please try again.": "Failed to transfer stock. Please try again.", @@ -53,6 +60,7 @@ "Remove": "Remove", "Reset": "Reset", "SFG": "Semi-finished good", + "Slot": "Slot", "Save": "Save", "Save failed": "Save failed", "Saved successfully": "Saved successfully", diff --git a/src/i18n/en/jo.json b/src/i18n/en/jo.json index 06a212c3..dcfa37ea 100644 --- a/src/i18n/en/jo.json +++ b/src/i18n/en/jo.json @@ -32,6 +32,8 @@ "BOM Type": "BOM Type", "Back": "Back", "Back to List": "Back to List", + "Back to Process": "Back to Process Steps", + "Back to Process Steps": "Back to Process Steps", "Bad Item Qty": "Bad Item Qty", "Bad Package Qty": "Bad Package Qty", "Bag": "Bag", diff --git a/src/i18n/en/navigation.json b/src/i18n/en/navigation.json index c1265c7d..96567961 100644 --- a/src/i18n/en/navigation.json +++ b/src/i18n/en/navigation.json @@ -49,6 +49,8 @@ "nav.settings.demandForecast": "Demand Forecast Setting", "nav.settings.bomWeighting": "BOM Weighting Score List", "nav.settings.masterDataIssues": "BOM / Item UOM Issues", + "nav.settings.stockLedgerFix": "Stock Ledger Fix", + "nav.breadcrumb.stockLedgerFix": "Stock Ledger Fix", "nav.settings.qrCodeHandle": "QR Code Handle", "nav.settings.importTesting": "Import Testing", "nav.settings.importExcel": "Import Excel", diff --git a/src/i18n/en/pickOrder.json b/src/i18n/en/pickOrder.json index db082bee..9bda0fff 100644 --- a/src/i18n/en/pickOrder.json +++ b/src/i18n/en/pickOrder.json @@ -58,7 +58,7 @@ "Lines": "Lines", "Before Today": "Before Today", "Truck X": "Truck X", - "Finsihed good items": "Finsihed good items", + "Finsihed good items": "Finished good items", "kinds": "kinds", "Completed Date": "Completed Date", "Completed Time": "Completed Time", @@ -147,8 +147,8 @@ "Etra": "Etra", "Exit Etra view": "Exit Etra view", "Etra Pick Order Detail": "Etra Pick Order Detail", - "Etra incomplete badge tooltip": "Etra incomplete badge tooltip", - "Etra incomplete badge tooltip none": "Etra incomplete badge tooltip none", + "Etra incomplete badge tooltip": "Incomplete extra tickets today: {{count}} (pending/released, excluding completed)", + "Etra incomplete badge tooltip none": "No incomplete extra tickets", "Back to normal assign tab": "Back to normal assign tab", "Enter isExtra workbench view?": "Enter isExtra workbench view?", "Etra view groups all add-on tickets by shop and lane for the selected date.": "Etra view groups all add-on tickets by shop and lane for the selected date.", @@ -179,7 +179,6 @@ "Confirm Search": "Search", "Merge Etra ticket search prompt": "Enter shop (optional) and date, then click Search to load merge candidates.", "Merge Etra ticket search failed": "Failed to load merge candidates. Ensure the backend is updated and restarted.", - "Truck X": "Truck X", "Pick Order": "Pick Order", "Type": "Type", "Product Type": "Product Type", @@ -529,14 +528,14 @@ "Floor ticket": "Floor ticket", "2F ticket": "2F ticket", "4F ticket": "4F ticket", - "4F lane panel legend": "4F lane panel legend", - "Loading sequence n": "Loading sequence n", - "lot QR code": "lot QR code", + "4F lane panel legend": "Lane — loading sequence (unassigned/total)", + "Loading sequence n": "Board {{n}}", + "lot QR code": "Lot QR Code", "label Printer": "label Printer", "Loading Sequence": "Loading Sequence", "Ticket No": "Ticket No", "The scanned lot inventory line is unavailable. Cannot switch or bind; pick line was not updated.": "The scanned lot inventory line is unavailable. Cannot switch or bind; pick line was not updated.", - "is unavable. Please check around have available QR code or not.": "is unavable. Please check around have available QR code or not.", + "is unavable. Please check around have available QR code or not.": "This lot is unavailable. Please check around for an available QR code.", "Lot switch failed; pick line was not marked as checked.": "Lot switch failed; pick line was not marked as checked.", "Lot confirmation failed. Please try again.": "Lot confirmation failed. Please try again.", "Powder Mixture": "Powder Mixture", @@ -559,5 +558,100 @@ "passed": "Passed", "failed": "Failed", "confirm_accept_with_fail": "There are failed QC items. Confirm to accept stock out?", - "No pending pick line left for this item. It may already be completed or fully processed.": "No pending pick line left for this item. It may already be completed or fully processed." + "No pending pick line left for this item. It may already be completed or fully processed.": "No pending pick line left for this item. It may already be completed or fully processed.", + "FG Carton Qty": "FG Carton Qty", + "成品出倉出箱數量": "FG Carton Qty", + "Truck Routing Summary": "Truck Routing Summary", + "送貨路線摘要": "Truck Routing Summary", + "車線-X": "Truck X", + "Lot QR Code": "Lot QR Code", + " 批號 QR 碼": "Lot QR Code", + "Cannot determine this lot status": "Cannot determine this lot status", + "Lot status: expired": "Lot status: expired", + "This pick line was rejected. Please scan another lot.": "This pick line was rejected. Please scan another lot.", + "This pick line is already completed. No further pick needed.": "This pick line is already completed. No further pick needed.", + "No lot bound / no available stock line. Please scan nearby inbound or transfer QR.": "No lot bound / no available stock line. Please scan nearby inbound or transfer QR.", + "Lot status: depleted (no remaining stock)": "Lot status: depleted (no remaining stock)", + "Lot status: depleted (available qty is 0)": "Lot status: depleted (available qty is 0)", + "Lot status: unavailable (not put away or line unavailable)": "Lot status: unavailable (not put away or line unavailable)", + "Lot status: ready to pick": "Lot status: ready to pick", + "This lot ({{lot}}) was rejected and cannot be used. Please scan another lot.": "This lot ({{lot}}) was rejected and cannot be used. Please scan another lot.", + "No lot information for this item in the current order": "No lot information for this item in the current order", + "Lot label print (pick station)": "Lot label print (pick station)", + "Scan content": "Scan content", + "Scan then press Enter or click Look up": "Scan then press Enter or click Look up", + "Look up": "Look up", + "Clear": "Clear", + "Printer": "Printer", + "Please select": "Please select", + "Print copies": "Print copies", + "Refresh lot list": "Refresh lot list", + "Selected printer": "Selected: {{printer}}", + "Item code name": "Item: {{code}} {{name}}", + "No available lots on this floor": "No available lots on this floor (available qty > 0).", + " (current lot)": " (current lot)", + "Location with value": "Location: {{location}}", + "Available qty with uom": "Available qty: {{qty}} UOM: {{uom}}", + "Print label": "Print label", + "Show QR": "Show QR", + "This row has no QR payload": "This row has no QR payload (stockInLineId required)", + "This pick line already scanned or completed, QR cannot be shown": "This pick line is already scanned or completed, so QR cannot be shown", + "No lots available to print labels": "No lots available to print labels", + "Failed to load printer list": "Failed to load printer list", + "Loaded available lots for this item": "Loaded available lots for this item", + "Analysis failed": "Look-up failed", + "Invalid itemId, cannot load lot list.": "Invalid item ID, cannot load lot list.", + "Invalid scan format. Please scan again.": "Invalid scan format. Please scan again.", + "Scan or look up once before refreshing the lot list.": "Scan or look up once before refreshing the lot list.", + "Print quantity must be an integer of 1 or more": "Print quantity must be an integer of 1 or more", + "Print sent: Lot {{lotNo}}": "Print sent: Lot {{lotNo}}", + "Print failed": "Print failed", + "Failed to load FG carton quantity. Please try again later.": "Failed to load FG carton quantity. Please try again later.", + "Cartons": "Cartons", + "{{count}} cartons": "{{count}} cartons", + "No chart data": "No chart data", + "2/F carton qty": "2/F carton qty", + "4/F carton qty": "4/F carton qty", + "Truck X carton qty": "Truck X carton qty", + "Total carton qty": "Total carton qty", + "Summary": "Summary", + "All floors": "All floors", + "Last 7 days": "Last 7 days", + "This month": "This month", + "This year": "This year", + "FG carton qty last 7 days title": "FG carton qty (last 7 days) - {{floor}} - as of {{date}}", + "FG carton qty this month title": "FG carton qty (this month) - {{floor}} - {{period}}", + "FG carton qty this year title": "FG carton qty (this year) - {{floor}} - {{period}}", + "Exporting...": "Exporting...", + "Download Excel": "Download Excel", + "Download this view Excel": "Download Excel (Selected)", + "Download period Excel": "Download Excel (Complete)", + "Download this view Excel hint": "Excel of the current floor, lane, shop, and date, plus the chart breakdown.", + "Download period Excel hint": "Excel with last 7 days, this month, and this year. Not limited to the current view.", + "Filtered": "Filtered", + "Breakdown": "Breakdown", + "FG carton qty filtered title": "FG carton qty (filtered) - {{floor}} - {{lane}} - {{shop}} - {{date}}", + "Truck Routing Summary (Workbench)": "Truck Routing Summary (Workbench)", + "2/F or 4/F": "2/F or 4/F", + "Lane": "Lane", + "Shop Code": "Shop group", + "Shop code": "Shop code", + "Back to previous level": "Back", + "All lanes": "All lanes", + "All shops": "All shop groups", + "Cartons by lane": "Cartons by lane", + "Cartons by shop": "Cartons by shop", + "Cartons by shop group": "Cartons by shop group", + "Cartons by floor": "Cartons by floor", + "Share": "Share", + "Click a row to filter": "Click a row to filter", + "Click a bar to filter": "Click a bar to filter", + "Reset filters": "Reset filters", + "Generating...": "Generating...", + "Download report (PDF)": "Download report (PDF)", + "Unpicked orders confirm download": "This lane still has {{count}} unpicked order(s).\nPrint / download the truck routing summary anyway?", + "Failed to download Workbench truck routing summary. Please try again later.": "Failed to download Workbench truck routing summary. Please try again later.", + "Confirm print drafts": "Print {{count}} draft(s)?", + "Floor": "Floor", + "All": "All" } diff --git a/src/i18n/en/productionProcess.json b/src/i18n/en/productionProcess.json index efdff3e8..17f8b3c1 100644 --- a/src/i18n/en/productionProcess.json +++ b/src/i18n/en/productionProcess.json @@ -10,6 +10,8 @@ "Auto-refresh every 10 minutes": "Auto-refresh every 10 minutes", "Back": "Back", "Back to List": "Back to List", + "Back to Process": "Back to Process Steps", + "Back to Process Steps": "Back to Process Steps", "Bag": "Bag", "Bag Consumption": "Bag Consumption", "Balance": "Balance", diff --git a/src/i18n/en/purchaseOrder.json b/src/i18n/en/purchaseOrder.json index f75266b5..d7865538 100644 --- a/src/i18n/en/purchaseOrder.json +++ b/src/i18n/en/purchaseOrder.json @@ -145,6 +145,7 @@ "email supplier": "Email Supplier", "confirm putaway": "Confirm & Complete Put Away", "confirm qc result": "Confirm QC Result", + "Mark all QC OK and accept": "Mark all QC OK and accept", "warehouse": "Warehouse", "qcItem": "QC Item", "passed": "Passed", diff --git a/src/i18n/en/report.json b/src/i18n/en/report.json index a9558ab7..b8ad8a2c 100644 --- a/src/i18n/en/report.json +++ b/src/i18n/en/report.json @@ -25,6 +25,12 @@ "cancel": "Cancel", "confirmDownloadPdf": "Confirm download PDF", "confirmDownloadExcel": "Confirm download Excel", + "semiFgDownloadDailyExcel": "Download daily columns (Excel)", + "semiFgGeneratingDailyExcel": "Generating daily Excel...", + "semiFgConfirmDailyExcel": "Confirm download daily Excel", + "semiFgDailyRangeRequired": "Enter the production date from and to. The daily Excel only includes that range.", + "semiFgDailyRangeInvalid": "The start date cannot be after the end date.", + "semiFgDailyRangeTooLong": "The date range cannot be longer than 366 days.", "semiFgConfirmTitle": "Selected item codes — FG / Semi-FG Production Analysis Report", "semiFgConfirmHint": "Please confirm the selected item codes and their categories:", "semiFgColItem": "Item code and name", @@ -130,6 +136,14 @@ "itemCodePaste": "Paste item codes from Excel. Separate with spaces, commas, or new lines" } }, + "rep-020": { + "title": "Stock Lot Ledger Report", + "fields": { + "lastInDateStart": "Period From", + "lastInDateEnd": "Period To", + "itemCode": "Item Code" + } + }, "rep-007": { "title": "Stock Balance Report", "fields": { diff --git a/src/i18n/en/routeboard.json b/src/i18n/en/routeboard.json index d7622d59..9a362c8e 100644 --- a/src/i18n/en/routeboard.json +++ b/src/i18n/en/routeboard.json @@ -106,7 +106,7 @@ "lane_noMatchFilter": "No lanes match (clear search or floor filter)", "floor_label": "Floor", "floor_all": "All", - "filter_clear": "Clear", + "filter_clear": "Clear all", "filter_apply": "OK", "btn_addLane": "Add lane", "tools_title": "Tools", diff --git a/src/i18n/en/shop.json b/src/i18n/en/shop.json index d0fdfb34..e3a50d49 100644 --- a/src/i18n/en/shop.json +++ b/src/i18n/en/shop.json @@ -132,8 +132,26 @@ "confirm_restoreDiscardsEdits": "Scheduling a version restore will discard other unsaved board changes (drags, deletes, pending shops/lanes, logistics fields, etc.). Continue?", "confirm_restoreSaveWillDropStaging": "Save will apply the snapshot restore first; other staged edits in this save will be skipped. Continue?", "confirm_schedule_removeShop": "Remove this shop from the lane? It will be scheduled for deletion when you submit.", - "departureDialog_hint": "Applies to all shop rows on this lane; press \"Save changes\" above to persist.", - "departureDialog_title": "Edit departure time", + "departureDialog_hint": "Name and departure apply to every master row on this lane. Press \"Save changes\" to write them. Existing delivery tickets keep the old name; later releases use the new name.", + "departureDialog_title": "Edit lane", + "departureDialog_nameLabel": "Lane name", + "laneEditTooltip": "Edit lane name and departure time (written when you press Save changes)", + "confirm_weekdayToken": "The weekday token in the lane name will change or become unreadable. 4F assignment matches Mon–Sun inside the name. Apply anyway?", + "confirm_renameLane": "Rename \"{{from}}\" to \"{{to}}\".\n{{unfinished}} unfinished delivery ticket(s) stay on the old name (handlers: {{handlers}}).\n{{completed}} completed ticket(s) stay on the old name.\nLater releases use the new name.\n{{schedules}} open schedule line(s) will change from/to.\nNothing is written until you press Save changes.", + "confirm_restoreKeepsTickets": "Restore puts lane master data, and open schedules that point at the current name, back to this snapshot. Unfinished delivery tickets stay on the current name.", + "rename_noHandlers": "none", + "rename_none": "none", + "rename_savePartial": "Renamed: {{ok}}. Failed: {{fail}}. The failed lane was not written. Successful lanes stay renamed. Refresh, then save again.", + "renameErr_preview": "Could not load ticket and schedule counts, so this edit was not applied.", + "renameErr_LANE_NAME_EMPTY": "Lane name cannot be blank", + "renameErr_LANE_NAME_TOO_LONG": "Lane name is limited to 50 characters", + "renameErr_LANE_NAME_RESERVED": "\"車線-X\" cannot be used or renamed", + "renameErr_LANE_NAME_TAKEN": "This floor and remark already has that lane", + "renameErr_LANE_NAME_REMARK_AMBIGUOUS": "This floor already has the same name with a different remark. Delivery tickets cannot tell them apart.", + "renameErr_LANE_NOT_FOUND": "No live lane rows were found, so nothing was written", + "renameErr_LANE_TIME_INVALID": "Departure time is not a valid time", + "renameLog_title": "Lane renames", + "renameLog_line": "{{when}} {{who}}: {{from}} → {{to}} ({{floor}})", "departureEditAria": "Edit departure time", "departureTooltipEditSave": "Edit departure time (saved with \"Save changes\")", "departureTooltipNeedShops": "Add shops before setting departure time", @@ -212,9 +230,14 @@ "err_save": "Save failed", "exportRoutes": "Export routes", "filter_apply": "OK", - "filter_clear": "Clear", + "filter_clear": "Clear all", "floor_all": "All", "floor_label": "Floor", + "lane_filter": "Filter", + "laneFilter_special": "Lane code", + "laneFilter_zone": "Zone", + "laneFilter_weekday": "Weekday", + "laneFilter_area": "Area", "id": "id", "importRoutes": "Import routes", "import_staged_preview": "Import preview loaded: {{file}} ({{sheets}} sheet(s) / {{rows}} rows). Press \"Save changes\" to persist.", diff --git a/src/i18n/en/stockLedgerFix.json b/src/i18n/en/stockLedgerFix.json new file mode 100644 index 00000000..09b6c5a4 --- /dev/null +++ b/src/i18n/en/stockLedgerFix.json @@ -0,0 +1,155 @@ +{ + "pageTitle": "Stock Ledger Fix", + "inventory10Title": "1.0 Inventory (Plan A)", + "inventory10Description": "Keeps existing IDs. Adds UOMs that exist on lots but not in inventory. onHand = Σ(in−out) by item+UOM. Rows with no lots become 0. When an item has multiple old rows, only one stock-UOM bucket is kept; the rest are marked deleted=1. Run this while inbound/outbound is paused, then Fix day by day.", + "inventory10LoadError": "Could not load inventory 1.0 preview (ADMIN / TESTING required)", + "inventory10Preview": "Existing inventory: {{rows}} rows; lot item+UOM pairs: {{lotPairs}}; missing: {{missing}}; stockUomId still NULL: {{nullUom}} rows.", + "inventory10Running": "Recalculating…", + "inventory10Run": "Run inventory 1.0 (A)", + "inventory10Confirm": "Plan A: keep existing inventory.id; backfill stockUomId from lots (if the old uomId is stock, revert it to base); insert missing (itemId, stockUomId) rows; recalculate onHand/unavailable from lot in−out. Does not write onHoldQty or change inventory_lot_line. Continue?", + "inventory10Done": "Inventory 1.0 complete: patched stockUomId {{patched}} rows, inserted {{inserted}}, orphans deleted {{orphans}}, outQty NULL to 0 {{outQty}}, recalculated {{updated}}, still missing UOM {{missingAfter}}, still NULL stockUomId {{nullAfter}}", + "inventory10Fail": "Inventory 1.0 failed", + "adjTitle": "2.7 ADJ", + "adjDescription": "Run 2.7a first, then 2.7b. 2.7a only handles lot lines where out qty is greater than in qty: in qty is raised to match out qty, and an inbound ADJ is written on that same lot. 2.7b only fills each lot's own gap (lot remain minus ledger remain), does not change the lot line, then rebuilds those bucket balances from in/out. Lots that already match are skipped.", + "adjDateLabel": "ADJ date", + "adjDateRequired": "Please enter an ADJ date", + "adjDateFuture": "ADJ date cannot be in the future", + "adjDateAndPreviewRequired": "Please enter an ADJ date and preview first", + "adjTodayFreeze": "Today (freeze night)", + "adjYesterday": "Yesterday", + "adjLoadError": "Could not load ADJ preview (ADMIN / TESTING required)", + "adjPreviewSummary": "ADJ date {{date}}; {{lotCount}} lots can be processed (over-issue remain→0: {{overIssueCount}}, total {{sumOverIssue}}; miss in {{adjInCount}}, out {{adjOutCount}}); missing in total {{sumMissIn}}, missing out total {{sumMissOut}}; SKU net {{skuNet}}{{skuNetNote}}{{revNote}}. Table shows at most 20 rows (over-issue first).", + "adjSkuNetNote": " (non-zero means missing in has no matching missing out)", + "adjRevNote": "; includes reverse ADJ {{count}} lots (ledger over-recorded)", + "adjColLotLineId": "lotLineId", + "adjColItemCode": "itemCode", + "adjColLineInOut": "line in/out", + "adjColLedgerInOut": "ledger in/out", + "adjColMissIn": "Missing in", + "adjColMissOut": "Missing out", + "adjColOverIssue": "Over-issue", + "adjPreviewing": "Previewing…", + "adjPreviewAgain": "Refresh preview", + "adjPreview": "Preview", + "adjApplying": "Writing ADJ…", + "adjApply": "Apply ADJ", + "adjApply27a": "Apply 2.7a", + "adjApply27b": "Apply 2.7b", + "adjConfirm27a": "On {{date}}, find lot lines where out qty is greater than in qty, raise in qty to match out qty, and write one inbound ADJ (the difference) plus an adjustment record on that lot. Lines already patched are skipped. Continue?", + "adjConfirm27b": "On {{date}}, for lots whose remain differs from that lot's ledger in/out, write one ADJ for the difference and do not change the lot line. After that, those bucket balances are rebuilt from in/out. Lots that already match are skipped. Continue?", + "adjDone27a": "2.7a {{date}}: lot lines {{insertedIn}}, adjustment records {{adjustmentRecords}}, lotQty {{filledLotQty}}, balance {{filledBalance}}, day close {{dayRowsWritten}}", + "adjDone27b": "2.7b {{date}}: in {{insertedIn}}, out {{insertedOut}}, adjustment records {{adjustmentRecords}}, lotQty {{filledLotQty}}, balance {{filledBalance}}, day close {{dayRowsWritten}}", + "adjConfirm": "On {{date}}, first patch over-issue remain→0 ({{overIssueCount}} lots, total {{sumOverIssue}}; this changes lot inQty). Then fill miss ADJ: inbound {{adjInCount}}, outbound {{adjOutCount}}. All inbound lines share one inbound document; all outbound lines share one outbound document (miss does not change lot qty). Missing in total {{sumMissIn}}, missing out total {{sumMissOut}}. Continue?", + "adjDone": "ADJ {{date}}: over-issue remain→0 {{overIssuePatched}}, in {{insertedIn}}, out {{insertedOut}}, lotQty {{filledLotQty}}, balance {{filledBalance}}, day close {{dayRowsWritten}}", + "adjFail": "ADJ align failed", + "tabCalendar": "Calendar", + "tabInventory": "Inventory", + "tabLot": "Lot line", + "calendarHint": "Click the title at the top-left to pick year, then month.\nChanging month does not load data; click a day to inspect that day.\nToday can be fixed (freeze-dump night).", + "selectDate": "Select a date", + "dayLoadError": "Could not load the day’s check", + "dayLedgerCount": "{{cnt}} ledger rows that day", + "cannotFixFuture": "Cannot fix a future date", + "cannotFixFutureRange": "Cannot fix a future date (today is allowed for freeze-dump night)", + "pickAtLeastOneStep": "Select at least one step (default runs all of 2.1–2.6)", + "allSteps216": "all 2.1–2.6", + "confirmPartialSteps": "Run only {{steps}} ({{date}}). Unchecked steps will not be recalculated. Continue?", + "fixDayDone": "Fixed {{date}} ({{steps}}): lot {{lot}}, uom {{uom}}, inventory {{inventory}}, lotQty {{lotQty}}, balance {{balance}}, day close {{dayRows}}{{lotNote}}", + "fixFailed": "Fix failed", + "fixing": "Fixing…", + "fixThisDay": "Fix this day", + "stepsTitle": "Steps (all selected by default)", + "stepsHint": "After applying SQL, if you only need to change inventoryId, tick 2.3 only. Unchecked steps are not recalculated.", + "selectAll": "Select all", + "step21": "2.1 lot", + "step22": "2.2 uom", + "step23": "2.3 inventoryId", + "step24": "2.4 lotQty", + "step25": "2.5 balance", + "step26": "2.6 day close", + "rangeTitle": "Range fix (2.1–2.6 in one run)", + "rangeHint": "Uses the steps ticked above. One API call, but runs day by day (same SQL as a single-day fix, commit per day). Today is allowed (freeze-dump night). Frontend timeout is about 20 minutes; for a large range, export SQL instead.", + "rangeFromRequired": "Please fill range from / to", + "toMustBeGteFrom": "to must be ≥ from", + "fromTooEarly": "from cannot be earlier than {{date}}", + "rangeConfirm": "Fix {{from}} → {{to}} (steps: {{steps}}). Runs day by day (commit each day). Days already finished are kept if it fails mid-way. Continue?", + "rangeProgress": "Range fix {{from}} → {{to}} ({{steps}}) in progress…", + "rangeDone": "Range fix complete {{date}} ({{steps}}): lot {{lot}}, uom {{uom}}, inventory {{inventory}}, lotQty {{lotQty}}, balance {{balance}}, day close {{dayRows}}{{lotNote}}", + "rangeFail": "Range fix failed", + "rangeRunning": "Range fix in progress…", + "rangeRun": "Range fix", + "from": "from", + "to": "to", + "exportTitle": "Export patched SQL (for the new database)", + "exportHint": "Tick the sections to export (same as day-fix steps). Apply order: 1.0 → 2.1 → ledger (±2.3) → 2.7 inbound/outbound documents + adjustment records + ADJ → 2.6. A full file matches the fixed database when production is frozen, IDs match, and the date range covers every fixed day. Default exports only ledger + day close (legacy behaviour).", + "exportPickAtLeastOne": "Select at least one export section", + "export23Without10": "2.3 inventoryId is ticked but 1.0 inventory is not: if production is missing the new IDs, UPDATE will point at empty rows. Tick 1.0 as well (full file). Export anyway?", + "exportFail": "Export failed", + "exporting": "Exporting…", + "exportSql": "Export .sql", + "exportDefault": "Default", + "exportFull": "Full file", + "exportFromToRequired": "Please fill from / to", + "export10": "1.0 inventory", + "export21": "2.1 soft-delete ledger + outbound lot lines", + "export23": "2.3 inventoryId", + "exportLedger": "ledger lot/uom/lotQty/balance", + "export26": "2.6 day close", + "export27": "2.7 ADJ + inbound/outbound documents + adjustment records", + "invTabHint": "Search by itemCode or inventoryId. Fix recalculates lotQty, day close, and balance for this item’s ledger up to today — no need to click the calendar day by day. If the warehouse is still writing this item during the day, new ledger rows after the fix are still handled by the live writer.", + "invSearchLabel": "itemCode / inventoryId", + "searching": "Searching…", + "search": "Search", + "searchFailed": "Search failed", + "colInventoryId": "inventoryId", + "colItemCode": "itemCode", + "colUomId": "uomId", + "colLedgerRows": "ledger rows", + "invLoadError": "Could not load inventory", + "invScopeSummary": "{{itemCode}} / inventory {{id}} / uom {{uomId}}; {{firstDate}} → {{lastDate}}; {{cnt}} rows; last balance {{lastBalance}}", + "invFixConfirm": "This will recalculate lotQty and day close for all ledger rows of this inventory up to today, plus this item’s balance. Continue?", + "invFixDone": "Fixed inventory {{id}}: lot {{lot}}, uom {{uom}}, inventory {{inventory}}, lotQty {{lotQty}}, balance {{balance}}, day close {{dayRows}}{{lotNote}}", + "fixThisInventory": "Fix this inventory", + "lotTabHint": "Search by lotNo or inventoryLotLineId. Fix only recalculates this lot’s lotQty and day close; it does not change balance.", + "lotSearchLabel": "lotNo / lot line id", + "colLotLineId": "lot line id", + "colLotNo": "lotNo", + "lotLoadError": "Could not load lot", + "lotScopeSummary": "{{lotNo}} / lot {{id}} / {{itemCode}}; {{firstDate}} → {{lastDate}}; {{cnt}} rows; last lotQtyAfter {{lastLotQtyAfter}}", + "lotFixConfirm": "This only fixes this lot’s lotQty and day close; it will not change the item’s balance. Continue?", + "lotFixDone": "Fixed lot {{id}}: lot {{lot}}, uom {{uom}}, inventory {{inventory}}, lotQty {{lotQty}}, day close {{dayRows}}{{lotNote}}", + "lotLineFixNote": "; soft-deleted unlinked lots {{deleted}}, blank out lines deleted {{blankOut}}, out lines aligned to ledger {{alignedOut}}, existing lot matched {{matched}}, mismatched {{mismatched}}", + "fixThisLot": "Fix this lot", + "checkItem": "Item", + "checkStatus": "Status", + "checkCorrect": "Correct", + "checkMiss": "Missing", + "checkIncorrect": "Incorrect", + "checkReason": "Reason", + "checkRows": "Rows", + "checkDash": "—", + "canAutoFix": "Can auto-fix (handled by Fix)", + "cannotAutoFix": "Cannot auto-fix (Fix will not clear these: old TKE new lots / true over-issue / no lot source)", + "verdictCorrect": "correct", + "verdictMiss": "miss", + "verdictOverIssue": "over-issue", + "verdictCanFix": "can fix", + "verdictCannotFix": "cannot fix", + "verdictIncorrect": "incorrect", + "part": { + "lot": "inventoryLotLineId", + "uom": "uomId", + "inventory": "inventoryId", + "lotQty": "lotQtyBefore/After (lot already exists)", + "overIssue": "over-issue (lotQty < 0)", + "balance": "balance", + "dayTable": "stock_lot_day", + "fixable21a": "Can fix 2.1a: SIL/SOL already has a lot line", + "fixable21b": "Can fix 2.1b: inventoryLotId has only one line", + "fixableLotQty": "Can fix: lot exists but lotQty is missing", + "cannotNoSource": "Cannot fix: no SIL/SOL lot source", + "cannotMultiLine": "Cannot fix: same lot has multiple warehouse lines", + "earlyTke": "Cannot fix: old TKE opened a new lot (sibling surplus)", + "realOver": "Cannot fix: over-issue is not old TKE (true over-issue / ledger mismatch)" + } +} diff --git a/src/i18n/en/stockTake.json b/src/i18n/en/stockTake.json index faaef94f..a866d2bb 100644 --- a/src/i18n/en/stockTake.json +++ b/src/i18n/en/stockTake.json @@ -98,6 +98,8 @@ "Return": "Return", "Rows per page": "Rows per page", "Save": "Save", + "Change": "Change", + "oneChangeLeft": "Only 1 change left", "Search": "Search", "Search Criteria": "Search Criteria", "Search section code or name": "Search code or name (e.g. ST-042 or drinks)", @@ -116,7 +118,7 @@ "Stock Take Management": "Stock Take Management", "Stock Take Qty": "Stock Take Qty", "Stock Take Qty Data and Variance Analysis": "Stock Take Qty Data and Variance Analysis", - "Stock Take Qty(include Bad Qty)= Available Qty": "Stock Take Qty(include Bad Qty)= Available Qty", + "Stock Take Qty(include Bad Qty)= Available Qty": "Stock Take Qty", "Stock Take Round": "Stock Take Round", "Stock Take Section": "Stock Take Section", "Stock Take Section (can use , to search multiple sections)": "Stock Take Section (can use , to search multiple sections)", @@ -173,6 +175,11 @@ "sections unit": "area(s)", "selected stock take qty": "selected stock take qty", "start time": "start time", + "qtyGapWarnPercent": "Qty variance warning %", + "qtyGapWarnPercentSaved": "Qty gap warning percent saved", + "qtyGapWarnPercentInvalid": "Enter a whole number from 0 to 1000", + "stockTakeQtyGapWarn": "Please check the entry. The count differs from current stock by {{pct}}%.", + "stockTakeQtyGapWarnOver": "Please check the entry. The count differs from current stock by more than {{threshold}}%.", "stockTaking": "Stock taking", "stock_take": "Stock take", "variance Percentage": "variance Percentage" diff --git a/src/i18n/en/ticketReleaseTable.json b/src/i18n/en/ticketReleaseTable.json index 6fc5468a..bb0a9732 100644 --- a/src/i18n/en/ticketReleaseTable.json +++ b/src/i18n/en/ticketReleaseTable.json @@ -16,11 +16,11 @@ "Departure Time": "Departure Time", "Floor": "Floor", "Force complete DO": "Force complete DO", - "Force complete hint": "Force complete hint", + "Force complete hint": "Marks the ticket completed and archived without changing picked quantities. Use when all lines are submitted but the system did not complete.", "Handler Name": "Handler Name", "Last updated": "Last updated", "Loading Sequence": "Loading Sequence", - "Manager only hint": "Manager only hint", + "Manager only hint": "Admin only", "No data available": "No data available", "Now": "Now", "Number of FG Items (Order Item(s) Count)": "Number of FG Items (Order Item(s) Count)", @@ -29,7 +29,7 @@ "Reload data": "Reload data", "Required Delivery Date": "Required Delivery Date", "Revert assignment": "Revert assignment", - "Revert assignment hint": "Revert assignment hint", + "Revert assignment hint": "Clears the assigned handler so the ticket returns to unassigned and can be taken again.", "Rows per page": "Rows per page", "Select All": "Select All", "Select Date": "Select Date", diff --git a/src/i18n/zh/common.json b/src/i18n/zh/common.json index 6753daf4..4bafa529 100644 --- a/src/i18n/zh/common.json +++ b/src/i18n/zh/common.json @@ -86,6 +86,8 @@ "Save": "儲存", "Saving": "儲存中", "Search": "搜索", + "More criteria": "更多條件", + "Fewer criteria": "收起條件", "Search Criteria": "搜索條件", "Select Date": "選擇日期", "Session expired or unauthorized.": "工作階段已過期或未經授權。", diff --git a/src/i18n/zh/doWorkbench.json b/src/i18n/zh/doWorkbench.json index 367c74db..2d446a83 100644 --- a/src/i18n/zh/doWorkbench.json +++ b/src/i18n/zh/doWorkbench.json @@ -45,5 +45,42 @@ "Auto-refresh every 5 minutes": "每5分鐘自動刷新", "Last updated": "最後更新", "Truck Information": "車線資訊", - "Actions": "操作" + "Actions": "操作", + "FG Carton Qty": "成品出倉出箱數量", + "成品出倉出箱數量": "成品出倉出箱數量", + "Truck Routing Summary": "送貨路線摘要", + "送貨路線摘要": "送貨路線摘要", + "車線-X": "車線-X", + "Confirm print drafts": "確認列印 {{count}} 張草稿?", + "Truck Routing Summary (Workbench)": "送貨路線摘要 (Workbench)", + "2/F or 4/F": "2/F 或 4/F", + "Lane": "車線", + "Shop Code": "店鋪組別", + "Shop code": "店鋪編號", + "Back to previous level": "返回上一層", + "All lanes": "全部車線", + "All shops": "全部店鋪組別", + "Cartons by lane": "按車線統計箱數", + "Cartons by shop": "按店鋪編號統計箱數", + "Cartons by shop group": "按店鋪組別統計箱數", + "Cartons by floor": "按樓層統計箱數", + "Share": "佔比", + "Click a row to filter": "點選列以篩選", + "Click a bar to filter": "點選長條以篩選", + "Reset filters": "重設篩選", + "Cartons": "箱數", + "Date": "日期", + "Download Excel": "下載 Excel", + "Download this view Excel": "下載 Excel(已選)", + "Download period Excel": "下載 Excel(完整)", + "Download this view Excel hint": "匯出目前樓層、車線、店鋪組別、日期的箱數,以及圖表分項。", + "Download period Excel hint": "匯出近7天、本月、本年的箱數,不限目前篩選畫面。", + "Filtered": "篩選", + "Breakdown": "分項", + "All floors": "全部樓層", + "FG carton qty filtered title": "成品出倉出箱數量(篩選)- {{floor}} - {{lane}} - {{shop}} - {{date}}", + "Generating...": "生成中...", + "Download report (PDF)": "下載報告 (PDF)", + "Unpicked orders confirm download": "此車線仍有 {{count}} 張訂單未執拾。\n是否仍要列印 / 下載送貨路線摘要?", + "Failed to download Workbench truck routing summary. Please try again later.": "下載 Workbench 送貨路線摘要失敗,請稍後再試。" } diff --git a/src/i18n/zh/inventory.json b/src/i18n/zh/inventory.json index 79c76ecf..8513855b 100644 --- a/src/i18n/zh/inventory.json +++ b/src/i18n/zh/inventory.json @@ -16,7 +16,14 @@ "Download QR Code": "下載", "Edit mode": "編輯模式", "Enter item code or name to search": "輸入貨品編號或名稱以搜索", + "Area": "區域", "Expiry Date": "到期日", + "Floor": "樓層", + "Item Search": "貨品搜尋", + "Location Search": "倉位搜尋", + "Select a floor to search by location.": "請先選擇樓層以搜尋倉位。", + "Select floor first": "請先選擇樓層", + "Select warehouse first": "請先選擇倉庫", "FG": "成品", "Failed to transfer stock": "轉倉失敗", "Failed to transfer stock. Please try again.": "轉倉失敗,請重試。", @@ -53,6 +60,7 @@ "Remove": "移除", "Reset": "重置", "SFG": "半成品", + "Slot": "儲位", "Save": "儲存", "Save failed": "儲存失敗", "Saved successfully": "儲存成功", diff --git a/src/i18n/zh/jo.json b/src/i18n/zh/jo.json index 84135db3..ffe12d1a 100644 --- a/src/i18n/zh/jo.json +++ b/src/i18n/zh/jo.json @@ -34,6 +34,8 @@ "BOM Type": "BOM 類型", "Back": "返回", "Back to List": "返回列表", + "Back to Process": "返回列表", + "Back to Process Steps": "返回列表", "Bad Item Qty": "不良物品數量", "Bad Package Qty": "不良包裝數量", "Bag": "包裝袋", diff --git a/src/i18n/zh/navigation.json b/src/i18n/zh/navigation.json index ae2c426d..46c8eceb 100644 --- a/src/i18n/zh/navigation.json +++ b/src/i18n/zh/navigation.json @@ -81,6 +81,8 @@ "nav.settings.items": "物品", "nav.settings.itemDefaultShelfLife": "物品預設保質期", "nav.settings.masterDataIssues": "BOM / 物料單位問題", + "nav.settings.stockLedgerFix": "庫存帳修復", + "nav.breadcrumb.stockLedgerFix": "庫存帳修復", "nav.settings.priceInquiry": "價格查詢", "nav.settings.printer": "列印機", "nav.settings.qcCategory": "QC 品檢模板", diff --git a/src/i18n/zh/pickOrder.json b/src/i18n/zh/pickOrder.json index d9465c5e..bdde2cf7 100644 --- a/src/i18n/zh/pickOrder.json +++ b/src/i18n/zh/pickOrder.json @@ -568,5 +568,102 @@ "Lot status is unavailable. Cannot switch or bind; pick line was not updated.": "批號狀態為「不可用」,無法換批或綁定;揀貨行未更新。", "No lot rows. Select a line in the table above.": "尚無批號資料。請在上方表格勾選一行提料單明細。", "No stock out line for this lot": "此批號尚無出庫行,無法提交。", - "No pending pick line left for this item. It may already be completed or fully processed.": "此貨品已無待揀行,可能已完成或不在本單可掃範圍。" - } \ No newline at end of file + "No pending pick line left for this item. It may already be completed or fully processed.": "此貨品已無待揀行,可能已完成或不在本單可掃範圍。", + + "FG Carton Qty": "成品出倉出箱數量", + "成品出倉出箱數量": "成品出倉出箱數量", + "Truck Routing Summary": "送貨路線摘要", + "送貨路線摘要": "送貨路線摘要", + "車線-X": "車線-X", + "Lot QR Code": "批號 QR 碼", + " 批號 QR 碼": "批號 QR 碼", + "Cannot determine this lot status": "無法判斷此批號狀態", + "Lot status: expired": "此批號狀態:已過期", + "This pick line was rejected. Please scan another lot.": "此出庫行:已拒絕,請改掃其他批號", + "This pick line is already completed. No further pick needed.": "此出庫行:已完成,無需再提貨", + "No lot bound / no available stock line. Please scan nearby inbound or transfer QR.": "尚未綁定批號/無可用庫存列:請掃描週邊入庫或轉倉 QR", + "Lot status: depleted (no remaining stock)": "此批號狀態:已用畢(無剩餘庫存)", + "Lot status: depleted (available qty is 0)": "此批號狀態:已用畢(可用量為 0)", + "Lot status: unavailable (not put away or line unavailable)": "此批號狀態:庫存不可用(未上架或行狀態不可用)", + "Lot status: ready to pick": "此批號狀態:可提貨", + "This lot ({{lot}}) was rejected and cannot be used. Please scan another lot.": "此批次({{lot}})已被拒絕,無法使用。請掃描其他批次。", + "No lot information for this item in the current order": "當前訂單中沒有此物品的批次資訊", + "Lot label print (pick station)": "批號標籤列印(提貨台)", + "Scan content": "掃碼內容", + "Scan then press Enter or click Look up": "掃描後按 Enter 或點「查詢」", + "Look up": "查詢", + "Clear": "清除", + "Printer": "印表機", + "Please select": "請選擇", + "Print copies": "列印張數", + "Refresh lot list": "刷新批號清單", + "Selected printer": "已選:{{printer}}", + "Item code name": "品號:{{code}} {{name}}", + "No available lots on this floor": "找不到該樓層有可用批號(availableQty > 0)。", + " (current lot)": "(當前批次)", + "Location with value": "位置:{{location}}", + "Available qty with uom": "可用量:{{qty}} 單位:{{uom}}", + "Print label": "列印標籤", + "Show QR": "顯示 QR", + "This row has no QR payload": "此列無法取得 QR payload(需 stockInLineId)", + "This pick line already scanned or completed, QR cannot be shown": "此出庫行已掃碼或已完成,無法顯示 QR", + "No lots available to print labels": "沒有任何批號可列印標籤", + "Failed to load printer list": "載入印表機清單失敗", + "Loaded available lots for this item": "已載入同品可用批號清單", + "Analysis failed": "分析失敗", + "Invalid itemId, cannot load lot list.": "無效 itemId,無法載入批號清單。", + "Invalid scan format. Please scan again.": "掃碼內容格式錯誤,請重新掃碼", + "Scan or look up once before refreshing the lot list.": "請先掃碼或查詢一次,才可刷新批號清單。", + "Print quantity must be an integer of 1 or more": "列印張數需為大於等於 1 的整數", + "Print sent: Lot {{lotNo}}": "已送出列印:Lot {{lotNo}}", + "Print failed": "列印失敗", + "Failed to load FG carton quantity. Please try again later.": "載入成品出倉出箱數量失敗,請稍後再試。", + "Cartons": "箱數", + "{{count}} cartons": "{{count}} 箱", + "No chart data": "沒有圖表資料", + "Total": "總數", + "2/F carton qty": "2/F 出箱數", + "4/F carton qty": "4/F 出箱數", + "Truck X carton qty": "車線-X 出箱數", + "Total carton qty": "總出箱數", + "Summary": "彙總", + "All floors": "全部樓層", + "Last 7 days": "最近7天", + "This month": "本月", + "This year": "本年", + "FG carton qty last 7 days title": "成品出倉出箱數量(最近7天)- {{floor}} - 基準日 {{date}}", + "FG carton qty this month title": "成品出倉出箱數量(本月)- {{floor}} - {{period}}", + "FG carton qty this year title": "成品出倉出箱數量(本年)- {{floor}} - {{period}}", + "Exporting...": "匯出中...", + "Download Excel": "下載 Excel", + "Download this view Excel": "下載 Excel(已選)", + "Download period Excel": "下載 Excel(完整)", + "Download this view Excel hint": "匯出目前樓層、車線、店鋪組別、日期的箱數,以及圖表分項。", + "Download period Excel hint": "匯出近7天、本月、本年的箱數,不限目前篩選畫面。", + "Filtered": "篩選", + "Breakdown": "分項", + "FG carton qty filtered title": "成品出倉出箱數量(篩選)- {{floor}} - {{lane}} - {{shop}} - {{date}}", + "Truck Routing Summary (Workbench)": "送貨路線摘要 (Workbench)", + "2/F or 4/F": "2/F 或 4/F", + "Lane": "車線", + "Shop Code": "店鋪組別", + "Shop code": "店鋪編號", + "Back to previous level": "返回上一層", + "All lanes": "全部車線", + "All shops": "全部店鋪組別", + "Cartons by lane": "按車線統計箱數", + "Cartons by shop": "按店鋪編號統計箱數", + "Cartons by shop group": "按店鋪組別統計箱數", + "Cartons by floor": "按樓層統計箱數", + "Share": "佔比", + "Click a row to filter": "點選列以篩選", + "Click a bar to filter": "點選長條以篩選", + "Reset filters": "重設篩選", + "Generating...": "生成中...", + "Download report (PDF)": "下載報告 (PDF)", + "Unpicked orders confirm download": "此車線仍有 {{count}} 張訂單未執拾。\n是否仍要列印 / 下載送貨路線摘要?", + "Failed to download Workbench truck routing summary. Please try again later.": "下載 Workbench 送貨路線摘要失敗,請稍後再試。", + "Confirm print drafts": "確認列印 {{count}} 張草稿?", + "Floor": "樓層", + "All": "全部" +} diff --git a/src/i18n/zh/productionProcess.json b/src/i18n/zh/productionProcess.json index 814ff3fc..d0130616 100644 --- a/src/i18n/zh/productionProcess.json +++ b/src/i18n/zh/productionProcess.json @@ -10,6 +10,8 @@ "Auto-refresh every 10 minutes": "每10分鐘自動刷新", "Back": "返回", "Back to List": "返回列表", + "Back to Process": "返回列表", + "Back to Process Steps": "返回列表", "Bag": "包裝袋", "Bag Consumption": "包裝袋消耗", "Balance": "可用數量", diff --git a/src/i18n/zh/purchaseOrder.json b/src/i18n/zh/purchaseOrder.json index 99664477..ac82c0f3 100644 --- a/src/i18n/zh/purchaseOrder.json +++ b/src/i18n/zh/purchaseOrder.json @@ -145,6 +145,7 @@ "email supplier": "電郵供應商", "confirm putaway": "確定及完成上架", "confirm qc result": "確定品檢結果", + "Mark all QC OK and accept": "全部合格並接受", "warehouse": "倉庫", "qcItem": "品檢項目", "passed": "接受", diff --git a/src/i18n/zh/report.json b/src/i18n/zh/report.json index 86517558..c74e58e8 100644 --- a/src/i18n/zh/report.json +++ b/src/i18n/zh/report.json @@ -25,6 +25,12 @@ "cancel": "取消", "confirmDownloadPdf": "確認下載 PDF", "confirmDownloadExcel": "確認下載 Excel", + "semiFgDownloadDailyExcel": "下載每日欄位 Excel", + "semiFgGeneratingDailyExcel": "生成每日 Excel...", + "semiFgConfirmDailyExcel": "確認下載每日 Excel", + "semiFgDailyRangeRequired": "請先輸入完成生產日期(由、至),每日欄位 Excel 只會輸出這段日期。", + "semiFgDailyRangeInvalid": "完成生產日期「由」不可晚於「至」。", + "semiFgDailyRangeTooLong": "日期範圍不可超過 366 日。", "semiFgConfirmTitle": "已選擇的物料編號以及列印成品/半成品生產分析報告", "semiFgConfirmHint": "請確認以下已選擇的物料編號及其類別:", "semiFgColItem": "物料編號及名稱", @@ -130,6 +136,14 @@ "itemCodePaste": "可從 Excel 貼上多個貨品編號,以空格、逗號或換行分隔" } }, + "rep-020": { + "title": "庫存流水帳報告", + "fields": { + "lastInDateStart": "期間起", + "lastInDateEnd": "期間迄", + "itemCode": "貨品編號" + } + }, "rep-007": { "title": "庫存結餘報告", "fields": { diff --git a/src/i18n/zh/routeboard.json b/src/i18n/zh/routeboard.json index 7e990a5c..f08a6bd9 100644 --- a/src/i18n/zh/routeboard.json +++ b/src/i18n/zh/routeboard.json @@ -106,7 +106,7 @@ "lane_noMatchFilter": "無符合條件的車線(清除搜索或樓層篩選)", "floor_label": "樓層", "floor_all": "全部", - "filter_clear": "清除", + "filter_clear": "清除全部", "filter_apply": "確定", "btn_addLane": "新增車線", "tools_title": "操作工具", diff --git a/src/i18n/zh/shop.json b/src/i18n/zh/shop.json index 27eee2dd..2aa03545 100644 --- a/src/i18n/zh/shop.json +++ b/src/i18n/zh/shop.json @@ -106,7 +106,12 @@ "lane_selectAll": "全選", "floor_label": "樓層", "floor_all": "全部", - "filter_clear": "清除", + "lane_filter": "篩選", + "laneFilter_special": "車線", + "laneFilter_zone": "區", + "laneFilter_weekday": "星期", + "laneFilter_area": "地區", + "filter_clear": "清除全部", "filter_apply": "確定", "btn_addLane": "新增車線", "tools_title": "操作工具", @@ -200,8 +205,26 @@ "dialog_editLogisticsTitle": "編輯物流公司", "btn_apply": "套用", "addShop_confirm": "確認", - "departureDialog_title": "編輯出車時間", - "departureDialog_hint": "套用至此車線所有店鋪列。", + "departureDialog_title": "編輯車線", + "departureDialog_nameLabel": "車線名稱", + "departureDialog_hint": "名稱與出車時間會套用到此車線全部店鋪。\n 既有送貨訂單維持舊名稱;之後放單才用新名稱。\n 按上方「儲存更改」才寫入。", + "laneEditTooltip": "編輯車線名稱與出車時間(按「儲存更改」才寫入)", + "confirm_weekdayToken": "車線名稱裡的星期代碼會改變,或改完後無法辨認。4F 派車是用名稱裡的 Mon–Sun 對日子。仍要套用?", + "confirm_renameLane": "把「{{from}}」改成「{{to}}」。\n未完成出倉票 {{unfinished}} 張維持舊名稱(負責人:{{handlers}})。\n已完成 {{completed}} 張維持舊名稱。\n之後放單才用新名稱。\n未完成排程 {{schedules}} 筆的起迄名稱會改。\n按「儲存更改」後才寫入。", + "confirm_restoreKeepsTickets": "還原會把車線主檔,以及指向目前名稱的未完成排程,改回此版本的名稱。未完成的出倉票會留在現在的名稱,不會跟回去。", + "rename_noHandlers": "無", + "rename_none": "無", + "rename_savePartial": "已改名:{{ok}}。失敗:{{fail}}。失敗的那一桶沒有寫入;已經成功的不會自動改回去。請重新整理後再存。", + "renameErr_preview": "讀不到出倉票與排程數量,這次沒有套用。", + "renameErr_LANE_NAME_EMPTY": "車線名稱不可空白", + "renameErr_LANE_NAME_TOO_LONG": "車線名稱最多 50 字", + "renameErr_LANE_NAME_RESERVED": "不能使用或改掉「車線-X」", + "renameErr_LANE_NAME_TAKEN": "同一樓層、同一備註已有這條車線", + "renameErr_LANE_NAME_REMARK_AMBIGUOUS": "同一樓層已有相同名稱但備註不同,出倉票無法分辨,已拒絕", + "renameErr_LANE_NOT_FOUND": "找不到這條車線的主檔,沒有寫入", + "renameErr_LANE_TIME_INVALID": "出車時間格式不正確", + "renameLog_title": "車線改名紀錄", + "renameLog_line": "{{when}} {{who}}:{{from}} → {{to}}({{floor}})", "seqDialog_title": "編輯裝車順序", "logistics_colLaneCount": "{{count}} 條車線", "tooltip_openLaneBoard": "在車線看板開此車線", diff --git a/src/i18n/zh/stockLedgerFix.json b/src/i18n/zh/stockLedgerFix.json new file mode 100644 index 00000000..5abd23af --- /dev/null +++ b/src/i18n/zh/stockLedgerFix.json @@ -0,0 +1,155 @@ +{ + "pageTitle": "庫存帳修復", + "inventory10Title": "1.0 inventory(方案 A)", + "inventory10Description": "保留現有 id;lot 有、inventory 沒有的 UOM 會新增;onHand = Σ(in−out) 按 item+UOM。沒有 lot 的列會變成 0。同一料多顆舊列時只留一顆 stock UOM 桶,其餘 deleted=1。請在進出倉暫停時執行,再逐日 Fix。", + "inventory10LoadError": "無法載入 inventory 1.0 預覽(需要 ADMIN / TESTING)", + "inventory10Preview": "現有 inventory {{rows}} 列;lot 的 item+UOM {{lotPairs}} 組;缺 {{missing}} 組;stockUomId 仍 NULL {{nullUom}} 列。", + "inventory10Running": "重算中…", + "inventory10Run": "Run inventory 1.0 (A)", + "inventory10Confirm": "方案 A:保留現有 inventory.id;從 lot 回填 stockUomId(舊 uomId 是 stock 則改回 base);補缺 (itemId, stockUomId);用 lot 的 in−out 重算 onHand/unavailable。不寫 onHoldQty、不改 inventory_lot_line。確定執行?", + "inventory10Done": "inventory 1.0 完成:回填 stockUomId {{patched}} 列、新增 {{inserted}} 列、殘列 deleted {{orphans}}、outQty NULL 改 0 {{outQty}} 列、重算 {{updated}} 列、之後仍缺 UOM {{missingAfter}}、仍 NULL stockUomId {{nullAfter}}", + "inventory10Fail": "inventory 1.0 失敗", + "adjTitle": "2.7 ADJ", + "adjDescription": "先跑 2.7a,再跑 2.7b。2.7a 只處理出數量大於入數量的批號列:入數量改成和出數量一樣,並在同一條批寫入倉 ADJ。2.7b 只補每一條批自己的差額(批號列剩餘減帳本剩餘),不改批號列,再按進出重算這些桶的餘額。已經一樣的批不會再寫。", + "adjDateLabel": "ADJ 日期", + "adjDateRequired": "請填 ADJ 日期", + "adjDateFuture": "ADJ 日期不能是未來", + "adjDateAndPreviewRequired": "請填 ADJ 日期並先預覽", + "adjTodayFreeze": "今天(freeze 夜)", + "adjYesterday": "昨天", + "adjLoadError": "無法載入 ADJ 預覽(需要 ADMIN / TESTING)", + "adjPreviewSummary": "ADJ 日期 {{date}};可處理 {{lotCount}} 條 lot(超發 remain→0 {{overIssueCount}}、合計 {{sumOverIssue}};miss 入 {{adjInCount}}、出 {{adjOutCount}});缺入合計 {{sumMissIn}}、缺出合計 {{sumMissOut}};SKU 淨額 {{skuNet}}{{skuNetNote}}{{revNote}}。下列最多 20 列(超發優先)。", + "adjSkuNetNote": "(非 0 表示有缺入沒有對應缺出)", + "adjRevNote": ";含反向 ADJ {{count}} 條(ledger 多記)", + "adjColLotLineId": "lotLineId", + "adjColItemCode": "itemCode", + "adjColLineInOut": "line in/out", + "adjColLedgerInOut": "ledger in/out", + "adjColMissIn": "缺入", + "adjColMissOut": "缺出", + "adjColOverIssue": "超發", + "adjPreviewing": "預覽中…", + "adjPreviewAgain": "重新預覽", + "adjPreview": "預覽", + "adjApplying": "寫入 ADJ 中…", + "adjApply": "Apply ADJ", + "adjApply27a": "Apply 2.7a", + "adjApply27b": "Apply 2.7b", + "adjConfirm27a": "會在 {{date}} 找出出數量大於入數量的批號列,把入數量改成和出數量一樣,並在同一條批寫一筆入倉 ADJ(差額)和庫存調整記錄。已補過的列再跑不會再寫。確定?", + "adjConfirm27b": "會在 {{date}} 對「批號列剩餘」和「這條批的帳本進出」不一樣的批,各寫一筆 ADJ(差額),不改批號列。寫完後這幾個庫存桶的餘額會按進出重算。已經一樣的批不會再寫。確定?", + "adjDone27a": "2.7a {{date}}:批號列 {{insertedIn}}、調整記錄 {{adjustmentRecords}}、lotQty {{filledLotQty}}、balance {{filledBalance}}、日結 {{dayRowsWritten}}", + "adjDone27b": "2.7b {{date}}:入 {{insertedIn}}、出 {{insertedOut}}、調整記錄 {{adjustmentRecords}}、lotQty {{filledLotQty}}、balance {{filledBalance}}、日結 {{dayRowsWritten}}", + "adjConfirm": "會在 {{date}} 先修超發 remain→0({{overIssueCount}} 條 lot,合計 {{sumOverIssue}},會改 lot inQty)。再補 miss ADJ:入向 {{adjInCount}} 筆、出向 {{adjOutCount}} 筆。入向全部掛同一張入倉單、出向全部掛同一張出倉單(miss 不改 lot 數量)。缺入合計 {{sumMissIn}}、缺出合計 {{sumMissOut}}。確定?", + "adjDone": "ADJ {{date}}:超發 remain→0 {{overIssuePatched}}、入 {{insertedIn}}、出 {{insertedOut}}、lotQty {{filledLotQty}}、balance {{filledBalance}}、日結 {{dayRowsWritten}}", + "adjFail": "ADJ 對齊失敗", + "tabCalendar": "日曆", + "tabInventory": "Inventory", + "tabLot": "Lot line", + "calendarHint": "點左上標題可先選年再選月。換月不會查資料;點某一天才檢查當天。今天可修(freeze dump 夜)。", + "selectDate": "請選日期", + "dayLoadError": "無法載入當日檢查", + "dayLedgerCount": "當天 ledger {{cnt}} 列", + "cannotFixFuture": "不能修未來日期", + "cannotFixFutureRange": "不能修未來日期(今天可以,給 freeze dump 夜修)", + "pickAtLeastOneStep": "請至少勾一個步驟(預設全跑 2.1–2.6)", + "allSteps216": "全部 2.1–2.6", + "confirmPartialSteps": "只跑 {{steps}}({{date}})。未勾的步驟不會重算。確定?", + "fixDayDone": "已修 {{date}}({{steps}}):lot {{lot}}、uom {{uom}}、inventory {{inventory}}、lotQty {{lotQty}}、balance {{balance}}、日結 {{dayRows}}{{lotNote}}", + "fixFailed": "修復失敗", + "fixing": "修復中…", + "fixThisDay": "Fix this day", + "stepsTitle": "步驟(預設全跑)", + "stepsHint": "套 SQL 後只改 inventoryId 時只勾 2.3。只跑部分時未勾的不會重算。", + "selectAll": "全選", + "step21": "2.1 lot", + "step22": "2.2 uom", + "step23": "2.3 inventoryId", + "step24": "2.4 lotQty", + "step25": "2.5 balance", + "step26": "2.6 日結", + "rangeTitle": "區間修(2.1–2.6 一次)", + "rangeHint": "使用上面勾的步驟,一次 API 但改為逐日(與單日修相同 SQL,每天 commit)。可含今天(freeze dump 夜)。前端最長約 20 分鐘;大區間仍建議匯出 SQL。", + "rangeFromRequired": "請填區間修 from / to", + "toMustBeGteFrom": "to 必須 ≥ from", + "fromTooEarly": "from 不能早於 {{date}}", + "rangeConfirm": "一次修 {{from}} → {{to}}(步驟:{{steps}})。改為逐日跑(每天 commit)。中途失敗時已跑完的天會留下。確定?", + "rangeProgress": "區間修 {{from}} → {{to}}({{steps}})進行中…", + "rangeDone": "區間修完成 {{date}}({{steps}}):lot {{lot}}、uom {{uom}}、inventory {{inventory}}、lotQty {{lotQty}}、balance {{balance}}、日結 {{dayRows}}{{lotNote}}", + "rangeFail": "區間修失敗", + "rangeRunning": "區間修中…", + "rangeRun": "區間修", + "from": "from", + "to": "to", + "exportTitle": "匯出已修 SQL(新庫用)", + "exportHint": "勾選要匯出的段落(同日修步驟)。套檔順序:1.0 → 2.1 → ledger(±2.3)→ 2.7 入出倉單+調整記錄+ADJ → 2.6。完整檔且正式庫 freeze/id 同源、日期蓋過全部已修日子時,結果與已修庫相同。預設只匯 ledger+日結(舊行為)。", + "exportPickAtLeastOne": "請至少勾一個匯出項目", + "export23Without10": "已勾 2.3 inventoryId 但未勾 1.0 inventory:正式庫若缺新 id,UPDATE 會指到空列。建議一併勾 1.0(完整檔)。仍要匯出?", + "exportFail": "匯出失敗", + "exporting": "匯出中…", + "exportSql": "匯出 .sql", + "exportDefault": "預設", + "exportFull": "完整檔", + "exportFromToRequired": "請填 from / to", + "export10": "1.0 inventory", + "export21": "2.1 軟刪流水帳+出倉列批號", + "export23": "2.3 inventoryId", + "exportLedger": "ledger lot/uom/lotQty/balance", + "export26": "2.6 日結", + "export27": "2.7 ADJ+入出倉單+調整記錄", + "invTabHint": "搜 itemCode 或 inventoryId。Fix 會重算這顆料到今天為止全部流水的 lotQty、日結與 balance,不必逐日點日曆。白天倉還在寫這顆料時,修完後新流水仍由 live writer 接。", + "invSearchLabel": "itemCode / inventoryId", + "searching": "搜尋中…", + "search": "搜尋", + "searchFailed": "搜尋失敗", + "colInventoryId": "inventoryId", + "colItemCode": "itemCode", + "colUomId": "uomId", + "colLedgerRows": "ledger 列", + "invLoadError": "無法載入 inventory", + "invScopeSummary": "{{itemCode}} / inventory {{id}} / uom {{uomId}};{{firstDate}} → {{lastDate}};{{cnt}} 列;最後 balance {{lastBalance}}", + "invFixConfirm": "會重算這顆 inventory 到今天為止全部 ledger 的 lotQty、日結,以及這顆料的 balance。確定?", + "invFixDone": "已修 inventory {{id}}:lot {{lot}}、uom {{uom}}、inventory {{inventory}}、lotQty {{lotQty}}、balance {{balance}}、日結 {{dayRows}}{{lotNote}}", + "fixThisInventory": "Fix this inventory", + "lotTabHint": "搜 lotNo 或 inventoryLotLineId。Fix 只重算這張 lot 的 lotQty 與日結,不改 balance。", + "lotSearchLabel": "lotNo / lot line id", + "colLotLineId": "lot line id", + "colLotNo": "lotNo", + "lotLoadError": "無法載入 lot", + "lotScopeSummary": "{{lotNo}} / lot {{id}} / {{itemCode}};{{firstDate}} → {{lastDate}};{{cnt}} 列;最後 lotQtyAfter {{lastLotQtyAfter}}", + "lotFixConfirm": "只修這張 lot 的 lotQty 與日結,不會改整顆料的 balance。確定?", + "lotFixDone": "已修 lot {{id}}:lot {{lot}}、uom {{uom}}、inventory {{inventory}}、lotQty {{lotQty}}、日結 {{dayRows}}{{lotNote}}", + "lotLineFixNote": "、軟刪未連批號 {{deleted}}、出倉列空而軟刪 {{blankOut}}、出倉列已改跟帳本 {{alignedOut}}、已有批號相符 {{matched}}、不相符 {{mismatched}}", + "fixThisLot": "Fix this lot", + "checkItem": "項目", + "checkStatus": "狀態", + "checkCorrect": "正確", + "checkMiss": "缺", + "checkIncorrect": "不正確", + "checkReason": "原因", + "checkRows": "列數", + "checkDash": "—", + "canAutoFix": "可自動修(按 Fix 會處理)", + "cannotAutoFix": "不能自動修(Fix 不會消;舊 TKE 開新批/真超發/沒有 lot 來源)", + "verdictCorrect": "correct", + "verdictMiss": "miss", + "verdictOverIssue": "over-issue", + "verdictCanFix": "可修", + "verdictCannotFix": "不能修", + "verdictIncorrect": "incorrect", + "part": { + "lot": "inventoryLotLineId", + "uom": "uomId", + "inventory": "inventoryId", + "lotQty": "lotQtyBefore/After(lot 已有)", + "overIssue": "over-issue (lotQty < 0)", + "balance": "balance", + "dayTable": "stock_lot_day", + "fixable21a": "可修 2.1a:SIL/SOL 已有 lot line", + "fixable21b": "可修 2.1b:inventoryLotId 僅一條 line", + "fixableLotQty": "可修:lot 已有但缺 lotQty", + "cannotNoSource": "不能修:沒有 SIL/SOL lot 來源", + "cannotMultiLine": "不能修:同一 lot 有多條 warehouse line", + "earlyTke": "不能修:舊 TKE 開新批(sibling 盤盈)", + "realOver": "不能修:over-issue 非舊 TKE(真超發/帳不一致)" + } +} diff --git a/src/i18n/zh/stockTake.json b/src/i18n/zh/stockTake.json index aad4cd7a..3287df0f 100644 --- a/src/i18n/zh/stockTake.json +++ b/src/i18n/zh/stockTake.json @@ -8,6 +8,8 @@ "Remark": "備註", "Action": "操作", "Save": "保存", + "Change": "更改", + "oneChangeLeft": "只剩 1 次更改機會", "Selected Qty": "選擇數量", "Not Match": "要求重點", "Search Criteria": "搜索條件", @@ -53,7 +55,7 @@ "Warehouse Location": "倉庫位置", "Item-lotNo-ExpiryDate": "貨品-批號-到期日", "UOM": "單位", - "Stock Take Qty(include Bad Qty)= Available Qty": "盤點數= 可用數", + "Stock Take Qty(include Bad Qty)= Available Qty": "盤點數", "Record Status": "盤點狀態", "No data": "沒有數據", "Difference": "差異", @@ -61,6 +63,11 @@ "Second": "第二次", "Approver Input": "審核員輸入", "Stock Take Qty": "盤點數", + "qtyGapWarnPercent": "出入差異警告%", + "qtyGapWarnPercentSaved": "出入差異警告%已保存", + "qtyGapWarnPercentInvalid": "請輸入 0 至 1000 的整數", + "stockTakeQtyGapWarn": "請小心輸入查看,盤點數與現時倉存有 {{pct}}% 的出入", + "stockTakeQtyGapWarnOver": "請小心輸入查看,盤點數與現時倉存的出入已超過 {{threshold}}%", "Bad Qty": "不良數量", "selected stock take qty": "已選擇盤點數量", "book qty": "帳面庫存", diff --git a/src/utils/workbenchPickLotUtils.ts b/src/utils/workbenchPickLotUtils.ts index de0ab460..d73af4f6 100644 --- a/src/utils/workbenchPickLotUtils.ts +++ b/src/utils/workbenchPickLotUtils.ts @@ -150,44 +150,62 @@ export function buildUnpickableScanRowPatch( return patch; } -export function getWorkbenchSourceLotStatusSummary(lot: WorkbenchPickLotLike | null | undefined): { +export function getWorkbenchSourceLotStatusSummary( + lot: WorkbenchPickLotLike | null | undefined, + t?: PickOrderT, +): { severity: "success" | "warning" | "error"; text: string; } { + const tr = (key: string) => (t ? t(key) : key); if (!lot) { - return { severity: "warning", text: "無法判斷此批號狀態" }; + return { severity: "warning", text: tr("Cannot determine this lot status") }; } if (isWorkbenchSourceLotExpired(lot)) { - return { severity: "error", text: "此批號狀態:已過期" }; + return { severity: "error", text: tr("Lot status: expired") }; } const solSt = solStatusOf(lot); if (solSt === "rejected") { - return { severity: "warning", text: "此出庫行:已拒絕,請改掃其他批號" }; + return { + severity: "warning", + text: tr("This pick line was rejected. Please scan another lot."), + }; } if (solSt === "completed" || solSt === "partially_completed" || solSt === "partially_complete") { - return { severity: "warning", text: "此出庫行:已完成,無需再提貨" }; + return { + severity: "warning", + text: tr("This pick line is already completed. No further pick needed."), + }; } const isNoLotRow = lot.noLot === true || !lot.lotNo || String(lot.lotNo || "").trim() === ""; if (isNoLotRow) { return { severity: "warning", - text: "尚未綁定批號/無可用庫存列:請掃描週邊入庫或轉倉 QR", + text: tr( + "No lot bound / no available stock line. Please scan nearby inbound or transfer QR.", + ), }; } const av = String(lot.lotAvailability || "").toLowerCase(); if (av === "insufficient_stock") { - return { severity: "warning", text: "此批號狀態:已用畢(無剩餘庫存)" }; + return { + severity: "warning", + text: tr("Lot status: depleted (no remaining stock)"), + }; } const avail = Number(lot.availableQty); if (lot.lotNo && Number.isFinite(avail) && avail <= 0) { - return { severity: "warning", text: "此批號狀態:已用畢(可用量為 0)" }; + return { + severity: "warning", + text: tr("Lot status: depleted (available qty is 0)"), + }; } if (isInventoryLotLineUnavailable(lot)) { return { severity: "warning", - text: "此批號狀態:庫存不可用(未上架或行狀態不可用)", + text: tr("Lot status: unavailable (not put away or line unavailable)"), }; } - return { severity: "success", text: "此批號狀態:可提貨" }; + return { severity: "success", text: tr("Lot status: ready to pick") }; }