Преглед на файлове

Merge branch 'production' into fix負數倉

fix負數倉
CANCERYS\kw093 преди 3 седмици
родител
ревизия
635d1b7604
променени са 83 файла, в които са добавени 4890 реда и са изтрити 1233 реда
  1. +1
    -0
      package.json
  2. +88
    -0
      scripts/warmup-menu.mjs
  3. +120
    -36
      src/app/(main)/axios/AxiosProvider.tsx
  4. +55
    -31
      src/app/(main)/axios/axiosInstance.ts
  5. +17
    -2
      src/app/(main)/chart/delivery/page.tsx
  6. +155
    -30
      src/app/(main)/m18Syn/page.tsx
  7. +48
    -12
      src/app/(main)/report/AsyncItemCodeAutocomplete.tsx
  8. +83
    -27
      src/app/(main)/report/SemiFGProductionAnalysisReport.tsx
  9. +8
    -4
      src/app/(main)/report/bomShopSyncReportApi.ts
  10. +9
    -5
      src/app/(main)/report/grnReportApi.ts
  11. +151
    -55
      src/app/(main)/report/page.tsx
  12. +62
    -0
      src/app/(main)/report/parseItemCodeTokens.ts
  13. +7
    -1
      src/app/(main)/report/reportI18n.ts
  14. +65
    -8
      src/app/(main)/report/semiFGProductionAnalysisApi.ts
  15. +27
    -0
      src/app/(main)/settings/shop/layout.tsx
  16. +12
    -6
      src/app/(main)/settings/stockLedgerFix/page.tsx
  17. +0
    -2
      src/app/api/doworkbench/actions.ts
  18. +19
    -19
      src/app/api/itemTracing/schema.ts
  19. +0
    -2
      src/app/api/pickOrder/actions.ts
  20. +4
    -0
      src/app/api/po/index.ts
  21. +2
    -0
      src/app/api/settings/uom/index.ts
  22. +6
    -0
      src/app/api/stockTake/actions.ts
  23. +144
    -5
      src/app/utils/authToken.ts
  24. +37
    -10
      src/app/utils/clientAuthFetch.ts
  25. +4
    -0
      src/authorities.ts
  26. +8
    -1
      src/components/AppBar/Profile.tsx
  27. +1
    -0
      src/components/Breadcrumb/Breadcrumb.tsx
  28. +26
    -10
      src/components/DoWorkbench/DoWorkbenchTabs.tsx
  29. +151
    -91
      src/components/DoWorkbench/GoodPickExecutionWorkbenchRecord.tsx
  30. +16
    -9
      src/components/DoWorkbench/TruckRoutingSummaryTabWorkbench.tsx
  31. +26
    -16
      src/components/DoWorkbench/WorkbenchGoodPickExecutionDetail.tsx
  32. +48
    -44
      src/components/DoWorkbench/WorkbenchLotLabelPrintModal.tsx
  33. +903
    -179
      src/components/FinishedGoodSearch/FinishedGoodCartonDashboardTab.tsx
  34. +8
    -8
      src/components/LoginPage/LoginForm.tsx
  35. +2
    -0
      src/components/LogoutPage/LogoutPage.tsx
  36. +18
    -1
      src/components/NavigationContent/NavigationContent.tsx
  37. +4
    -4
      src/components/PickOrderSearch/WorkbenchPickExecution.tsx
  38. +8
    -2
      src/components/PoDetail/PoDetail.tsx
  39. +146
    -20
      src/components/PoDetail/PoDetailRow.tsx
  40. +5
    -4
      src/components/PoDetail/PoInputGrid.tsx
  41. +10
    -3
      src/components/PoDetail/PutAwayForm.tsx
  42. +3
    -2
      src/components/PoDetail/QcStockInModal.tsx
  43. +1
    -1
      src/components/PoDetail/StockInLineRowActions.tsx
  44. +60
    -0
      src/components/PoDetail/originSilPutAwayQty.ts
  45. +96
    -0
      src/components/PoDetail/poPurchaseUom.ts
  46. +85
    -5
      src/components/PoDetail/stockQtyRound.ts
  47. +37
    -75
      src/components/PoSearch/PoSearch.tsx
  48. +4
    -3
      src/components/Qc/QcComponent.tsx
  49. +51
    -4
      src/components/Qc/QcStockInModal.tsx
  50. +19
    -2
      src/components/SearchBox/SearchBox.tsx
  51. +265
    -184
      src/components/StockLedgerFix/StockLedgerFixPageClient.tsx
  52. +42
    -5
      src/components/StockTakeManagement/ApproverStockTake.tsx
  53. +65
    -21
      src/components/StockTakeManagement/ApproverStockTakeAll.tsx
  54. +75
    -24
      src/components/StockTakeManagement/PickerReStockTake.tsx
  55. +187
    -62
      src/components/StockTakeManagement/PickerStockTake.tsx
  56. +40
    -0
      src/components/StockTakeManagement/StockTakeQtyGapHint.tsx
  57. +100
    -6
      src/components/StockTakeManagement/StockTakeTab.tsx
  58. +49
    -0
      src/components/StockTakeManagement/qtyGapWarnSettingClient.ts
  59. +55
    -0
      src/components/StockTakeManagement/stockTakeQtyAdornment.tsx
  60. +62
    -0
      src/components/StockTakeManagement/stockTakeQtyGapWarning.ts
  61. +33
    -0
      src/components/StockTakeManagement/useStockTakeQtyGapWarnPercent.ts
  62. +59
    -32
      src/components/charts/SafeApexCharts.tsx
  63. +3
    -2
      src/config/api.ts
  64. +113
    -8
      src/config/authConfig.ts
  65. +22
    -0
      src/config/reportConfig.ts
  66. +112
    -110
      src/i18n/en/common.json
  67. +43
    -1
      src/i18n/en/doWorkbench.json
  68. +2
    -0
      src/i18n/en/navigation.json
  69. +103
    -9
      src/i18n/en/pickOrder.json
  70. +3
    -0
      src/i18n/en/purchaseOrder.json
  71. +48
    -6
      src/i18n/en/report.json
  72. +155
    -0
      src/i18n/en/stockLedgerFix.json
  73. +8
    -1
      src/i18n/en/stockTake.json
  74. +3
    -3
      src/i18n/en/ticketReleaseTable.json
  75. +2
    -0
      src/i18n/zh/common.json
  76. +38
    -1
      src/i18n/zh/doWorkbench.json
  77. +2
    -0
      src/i18n/zh/navigation.json
  78. +99
    -2
      src/i18n/zh/pickOrder.json
  79. +3
    -0
      src/i18n/zh/purchaseOrder.json
  80. +48
    -6
      src/i18n/zh/report.json
  81. +155
    -0
      src/i18n/zh/stockLedgerFix.json
  82. +8
    -1
      src/i18n/zh/stockTake.json
  83. +28
    -10
      src/utils/workbenchPickLotUtils.ts

+ 1
- 0
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",


+ 88
- 0
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)" : ""}`,
);
}

+ 120
- 36
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<string | null>(null);
const [isHydrated, setIsHydrated] = useState(false);
const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | 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 (
<AxiosContext.Provider value={axiosInstance}>
<TokenContext.Provider value={{ setAccessToken: handleSetAccessToken }}>
{/* Render children immediately – they will just not have the token for 1-2ms */}
{children}
</TokenContext.Provider>
</AxiosContext.Provider>
@@ -111,4 +195,4 @@ export const AxiosProvider: React.FC<{ children: React.ReactNode }> = ({ childre
};

export const useAxios = () => useContext(AxiosContext);
export const useToken = () => useContext(TokenContext);
export const useToken = () => useContext(TokenContext);

+ 55
- 31
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);
},


+ 17
- 2
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<Criteria>(defaultCriteria);
const [topItemsSelected, setTopItemsSelected] = useState<TopDeliveryItemOption[]>([]);
const [topItemOptions, setTopItemOptions] = useState<TopDeliveryItemOption[]>([]);
@@ -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() {
)}
</ChartCard>

{canSeeStaffPerformance && (
<ChartCard
title="員工發貨績效(每日揀貨數量與耗時)"
exportFilename="員工發貨績效"
@@ -496,6 +510,7 @@ export default function DeliveryChartPage() {
</>
)}
</ChartCard>
)}
</Box>
);
}

+ 155
- 30
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);
@@ -135,26 +210,63 @@ export default function M18SynPage() {
}
};

/** 送貨訂單:手動按 code 同步(可輸入多個 code,用逗號或換行分隔) */
const handleSyncM18DoByCode = async () => {
if (m18DoInFlightRef.current) return;
if (!m18DoCode.trim()) {
alert("Please enter DO / shop PO code.");
const raw = m18DoCode.trim();
if (!raw) {
alert("Please enter DO / shop PO code(s).");
return;
}
const codes = raw
.split(/[\n,]+/g)
.map((s) => s.trim())
.filter(Boolean);
if (codes.length === 0) {
alert("Please enter at least one code.");
return;
}
m18DoInFlightRef.current = true;
setIsSyncingM18Do(true);
setM18DoSyncResult("");
try {
const response = await clientAuthFetch(
`${NEXT_PUBLIC_API_URL}/m18/test/do-by-code?code=${encodeURIComponent(m18DoCode.trim())}`,
{ method: "GET" },
);
if (response.status === 401 || response.status === 403) return;
const text = await response.text();
setM18DoSyncResult(formatSyncResultText("送貨訂單", text));
if (!response.ok) {
alert(`Sync failed: ${response.status}`);
const outputs: string[] = [];
const okCodes: string[] = [];
const notFoundCodes: string[] = [];
const skippedReleasedCodes: string[] = [];
const otherFailCodes: string[] = [];
for (const code of codes) {
const response = await clientAuthFetch(
`${NEXT_PUBLIC_API_URL}/m18/test/do-by-code?code=${encodeURIComponent(code)}`,
{ method: "GET" },
);
if (response.status === 401 || response.status === 403) return;
const text = await response.text();
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 =
parsed.kind === "success" ? "成功同步" :
parsed.kind === "not_found" ? parsed.message :
parsed.message;
outputs.push(`${code}: ${perCodeMsg}${response.ok ? "" : ` (HTTP ${response.status})`}`);
}

outputs.push("");
outputs.push(`共${okCodes.length}張送貨訂單成功`);
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"));
} catch (e) {
console.error("M18 DO Sync By Code Error:", e);
alert("M18 DO sync failed. Check console/network.");
@@ -188,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(
@@ -200,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 =
@@ -213,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"));
@@ -272,6 +392,7 @@ export default function M18SynPage() {
</Typography>
<Typography variant="body2" color="textSecondary" sx={{ mb: 2 }}>
Requires 行政 (ADMIN) or M18同步 (M18_SYNC). Sync Purchase Order, Delivery Order, or product/material from M18 using document or item code.
「採購單」找不到時會自動改試「送貨訂單」;「送貨訂單」找不到時請改到「採購單」分頁。
</Typography>

<Tabs value={tabValue} onChange={(_, v) => setTabValue(v)} aria-label="M18 sync by code" centered variant="fullWidth">
@@ -312,18 +433,22 @@ export default function M18SynPage() {

<TabPanel value={tabValue} index={1}>
<Section title="M18 送貨訂單 — sync by code">
<Stack direction="row" spacing={2} sx={{ mb: 2, alignItems: "center" }}>
<Stack spacing={2} sx={{ mb: 2 }}>
<TextField
size="small"
label="DO / Shop PO Code"
value={m18DoCode}
onChange={(e) => setM18DoCode(e.target.value)}
placeholder="e.g. same document code as M18 shop PO"
sx={{ minWidth: 320 }}
placeholder="可輸入多個 code,用逗號或換行分隔"
fullWidth
multiline
minRows={6}
maxRows={14}
/>
<Button variant="contained" color="primary" onClick={handleSyncM18DoByCode} disabled={isSyncingM18Do}>
{isSyncingM18Do ? "Syncing..." : "Sync DO from M18"}
</Button>
<Box sx={{ display: "flex", justifyContent: "flex-end" }}>
<Button variant="contained" color="primary" onClick={handleSyncM18DoByCode} disabled={isSyncingM18Do}>
{isSyncingM18Do ? "Syncing..." : "Sync DO from M18"}
</Button>
</Box>
</Stack>
{m18DoSyncResult ? (
<TextField


+ 48
- 12
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<Props> = ({
label,
value,
onChange,
onInputValueChange,
placeholder,
disabled = false,
minChars = 2,
@@ -73,21 +77,47 @@ const AsyncItemCodeAutocomplete: React.FC<Props> = ({
};
}, [trimmedInput, minChars]);

const selectedCodes = useMemo(
() => new Set(value.map((code) => code.toUpperCase())),
[value],
);

const options = useMemo(() => {
const seen = new Set<string>();
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<Props> = ({
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<Props> = ({
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 : [])


+ 83
- 27
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,16 +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<string, string>;
prepareCriteria?: () => Record<string, string>;
requiredFieldLabels: string[];
loading: boolean;
setLoading: (loading: boolean) => void;
@@ -38,6 +43,7 @@ interface SemiFGProductionAnalysisReportProps {

export default function SemiFGProductionAnalysisReport({
criteria,
prepareCriteria,
requiredFieldLabels,
loading,
setLoading,
@@ -48,7 +54,8 @@ export default function SemiFGProductionAnalysisReport({
const [showConfirmDialog, setShowConfirmDialog] = useState(false);
const [selectedItemCodesInfo, setSelectedItemCodesInfo] = useState<ItemCodeWithCategory[]>([]);
const [itemCodesWithCategory, setItemCodesWithCategory] = useState<Record<string, ItemCodeWithCategory>>({});
const [exportFormat, setExportFormat] = useState<'pdf' | 'excel'>('pdf');
const [exportFormat, setExportFormat] = useState<ExportFormat>('pdf');
const inFlightRef = useRef(false);

// Fetch item codes with category when stockCategory changes
useEffect(() => {
@@ -68,24 +75,43 @@ export default function SemiFGProductionAnalysisReport({
}
}, [criteria.stockCategory]);

const handleExportClick = async (format: 'pdf' | 'excel') => {
const dailyRangeError = (activeCriteria: Record<string, string>): 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;
}
}

// If no itemCode is selected, export directly without confirmation
if (!criteria.itemCode) {
await executeExport(format);
const selectedCodes = parseItemCodeTokens(
[activeCriteria.itemCode, activeCriteria.itemCodePaste].filter(Boolean).join(' '),
);
if (selectedCodes.length === 0) {
await executeExport(format, activeCriteria);
return;
}

// If itemCode is selected, show confirmation dialog
const selectedCodes = criteria.itemCode.split(',').filter((code) => code.trim());
const itemCodesInfo: ItemCodeWithCategory[] = selectedCodes.map((code) => {
const codeTrimmed = code.trim();
const itemCodesInfo: ItemCodeWithCategory[] = selectedCodes.map((codeTrimmed) => {
const categoryInfo = itemCodesWithCategory[codeTrimmed];
return {
code: codeTrimmed,
@@ -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<string, string> = 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 (
<>
<div style={{ display: 'flex', gap: 16 }}>
@@ -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')}
</Button>
<Button
variant="outlined"
@@ -136,7 +185,20 @@ export default function SemiFGProductionAnalysisReport({
disabled={loading}
sx={{ px: 4 }}
>
{loading ? t('generatingExcel') : t('downloadExcel')}
{loading && exportFormat === 'excel' ? t('generatingExcel') : t('downloadExcel')}
</Button>
<Button
variant="outlined"
color="success"
size="large"
startIcon={<DownloadIcon />}
onClick={() => handleExportClick('excel-daily')}
disabled={loading}
sx={{ px: 4 }}
>
{loading && exportFormat === 'excel-daily'
? t('semiFgGeneratingDailyExcel')
: t('semiFgDownloadDailyExcel')}
</Button>
</div>

@@ -196,13 +258,7 @@ export default function SemiFGProductionAnalysisReport({
disabled={loading}
startIcon={<DownloadIcon />}
>
{loading
? exportFormat === 'excel'
? t('generatingExcel')
: t('generatingPdf')
: exportFormat === 'excel'
? t('confirmDownloadExcel')
: t('confirmDownloadPdf')}
{confirmLabel}
</Button>
</DialogActions>
</Dialog>


+ 8
- 4
src/app/(main)/report/bomShopSyncReportApi.ts Целия файл

@@ -2,6 +2,7 @@

import { NEXT_PUBLIC_API_URL } from "@/config/api";
import { clientAuthFetch } from "@/app/utils/clientAuthFetch";
import { buildItemCodePasteRequestBody } from "./parseItemCodeTokens";
import {
exportMultiSheetToXlsx,
} from "@/app/(main)/chart/_components/exportChartToXlsx";
@@ -124,12 +125,15 @@ function emptyMaterialSheetRow(
export async function fetchBomShopSyncReportData(
criteria: Record<string, string>,
): Promise<BomShopSyncReportResponse> {
const queryParams = new URLSearchParams(criteria).toString();
const url = `${NEXT_PUBLIC_API_URL}/report/bom-shop-sync-history?${queryParams}`;
const url = `${NEXT_PUBLIC_API_URL}/report/bom-shop-sync-history`;

const response = await clientAuthFetch(url, {
method: "GET",
headers: { Accept: "application/json" },
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(buildItemCodePasteRequestBody(criteria, "finishedItemCode")),
});

if (response.status === 401 || response.status === 403)


+ 9
- 5
src/app/(main)/report/grnReportApi.ts Целия файл

@@ -1,6 +1,7 @@
"use client";

import { NEXT_PUBLIC_API_URL } from "@/config/api";
import { buildItemCodePasteRequestBody } from './parseItemCodeTokens';
import { clientAuthFetch } from "@/app/utils/clientAuthFetch";
import {
exportChartToXlsx,
@@ -64,17 +65,20 @@ export interface GrnReportResponse {

/**
* Fetch GRN (Goods Received Note) report data by date range.
* Backend: GET /report/grn-report?receiptDateStart=&receiptDateEnd=&itemCode=
* Backend: POST /report/grn-report { receiptDateStart, receiptDateEnd, itemCodes }
*/
export async function fetchGrnReportData(
criteria: Record<string, string>
): Promise<{ rows: GrnReportRow[]; listedPoAmounts?: ListedPoAmounts }> {
const queryParams = new URLSearchParams(criteria).toString();
const url = `${NEXT_PUBLIC_API_URL}/report/grn-report?${queryParams}`;
const url = `${NEXT_PUBLIC_API_URL}/report/grn-report`;

const response = await clientAuthFetch(url, {
method: "GET",
headers: { Accept: "application/json" },
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(buildItemCodePasteRequestBody(criteria, "itemCode")),
});

if (response.status === 401 || response.status === 403)


+ 151
- 55
src/app/(main)/report/page.tsx Целия файл

@@ -26,6 +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, parseItemCodeTokens } from './parseItemCodeTokens';
import { NEXT_PUBLIC_API_URL } from '@/config/api';
import { clientAuthFetch } from '@/app/utils/clientAuthFetch';
import SemiFGProductionAnalysisReport from './SemiFGProductionAnalysisReport';
@@ -74,13 +75,22 @@ const FIELD_ERROR_SX = {
},
};

const ITEM_CODE_PASTE_POST_REPORTS = new Set([
'rep-004',
'rep-006',
'rep-007',
'rep-008',
'rep-011',
'rep-013',
]);

/** 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, optionLabel } = useReportLabels();
const { t, i18n, reportTitle, fieldLabel, fieldHint, optionLabel } = useReportLabels();
const isZh = (i18n.language || 'zh').startsWith('zh');
const dateDisplayFormat = isZh ? 'DD/MM/YYYY' : 'DD/MM/YYYY';
const includeGrnFinancialColumns =
@@ -88,6 +98,37 @@ export default function ReportPage() {

const [selectedReportId, setSelectedReportId] = useState<string>('');
const [criteria, setCriteria] = useState<Record<string, string>>({});
const criteriaRef = useRef<Record<string, string>>({});
const pendingItemCodeInputRef = useRef<Record<string, string>>({});
const updateCriteria = (
updater: Record<string, string> | ((prev: Record<string, string>) => Record<string, string>),
) => {
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<string, string> => {
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<Record<string, { label: string; value: string }[]>>({});
@@ -114,14 +155,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({});
}
};

@@ -133,7 +175,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);
@@ -242,7 +284,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',
@@ -254,7 +296,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.
@@ -319,19 +361,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();
};
@@ -339,15 +382,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');
@@ -358,7 +402,32 @@ export default function ReportPage() {
return p.toString();
};

const itemCodeFieldName = (): string =>
currentReport?.fields.some((f) => f.name === 'finishedItemCode')
? 'finishedItemCode'
: 'itemCode';

const isItemCodePastePostReport = (): boolean =>
!!currentReport && ITEM_CODE_PASTE_POST_REPORTS.has(currentReport.id);

const buildCriteriaQueryString = (): string => {
if (!currentReport) return '';
if (currentReport.id === 'rep-012') return buildRep012QueryString();
if (currentReport.id === 'rep-010') return buildRep010QueryString();
const merged = mergePastedItemCodes(criteriaRef.current, itemCodeFieldName());
const p = new URLSearchParams(merged);
if (currentReport.id === 'rep-016') {
const day = (merged.dateStart || '').trim();
if (day) {
p.set('dateStart', day);
p.set('dateEnd', day);
}
}
return p.toString();
};

const handlePrint = async () => {
flushPendingItemCodeInputs();
if (!currentReport) return;
if (!validateRequiredFields()) return;

@@ -375,6 +444,7 @@ export default function ReportPage() {
};

const handleExcelPrint = async () => {
flushPendingItemCodeInputs();
if (!currentReport) return;
if (!validateRequiredFields()) return;
await executeExcelReport();
@@ -386,41 +456,38 @@ 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.
let queryParams =
currentReport.id === 'rep-012'
? buildRep012QueryString()
: currentReport.id === 'rep-010'
? buildRep010QueryString()
: new URLSearchParams(criteria).toString();
// rep-016: single-day UI — mirror dateStart to dateEnd for backend API.
if (currentReport.id === 'rep-016') {
const p = new URLSearchParams(criteria);
const day = (criteria.dateStart || '').trim();
if (day) {
p.set('dateStart', day);
p.set('dateEnd', day);
}
queryParams = p.toString();
}
const excelUrl = `${currentReport.apiEndpoint}-excel?${queryParams}`;
const usesItemCodePastePost = isItemCodePastePostReport();
const excelUrl = usesItemCodePastePost
? `${currentReport.apiEndpoint}-excel`
: `${currentReport.apiEndpoint}-excel?${buildCriteriaQueryString()}`;

const response = await clientAuthFetch(excelUrl, {
method: 'GET',
headers: { Accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
});
const response = await clientAuthFetch(excelUrl, usesItemCodePastePost
? {
method: 'POST',
headers: {
Accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Content-Type': 'application/json',
},
body: JSON.stringify(buildItemCodePasteRequestBody(criteriaRef.current, itemCodeFieldName())),
}
: {
method: 'GET',
headers: { Accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
});

if (response.status === 401 || response.status === 403) return;
if (response.status === 204) {
@@ -472,18 +539,24 @@ export default function ReportPage() {

setLoading(true);
try {
let queryParams =
currentReport.id === 'rep-012'
? buildRep012QueryString()
: currentReport.id === 'rep-010'
? buildRep010QueryString()
: new URLSearchParams(criteria).toString();
const url = `${currentReport.apiEndpoint}?${queryParams}`;
const usesItemCodePastePost = isItemCodePastePostReport();
const url = usesItemCodePastePost
? currentReport.apiEndpoint
: `${currentReport.apiEndpoint}?${buildCriteriaQueryString()}`;

const response = await clientAuthFetch(url, {
method: 'GET',
headers: { 'Accept': 'application/pdf' },
});
const response = await clientAuthFetch(url, usesItemCodePastePost
? {
method: 'POST',
headers: {
Accept: 'application/pdf',
'Content-Type': 'application/json',
},
body: JSON.stringify(buildItemCodePasteRequestBody(criteriaRef.current, itemCodeFieldName())),
}
: {
method: 'GET',
headers: { Accept: 'application/pdf' },
});

if (response.status === 401 || response.status === 403) return;
if (!response.ok) {
@@ -574,7 +647,10 @@ export default function ReportPage() {
: currentValue;

// Use larger grid size for 成品/半成品生產分析報告
const gridSize = currentReport.id === 'rep-005' ? { xs: 12, sm: 12, md: 6 } : { xs: 12, sm: 6 };
const gridSize = field.multiline
? { xs: 12 }
: currentReport.id === 'rep-005' ? { xs: 12, sm: 12, md: 6 } : { xs: 12, sm: 6 };
const hintText = fieldHint(currentReport.id, field.name);

const disabledByCheckedCheckbox = currentReport.fields.some((f) => {
if (f.type !== 'checkbox' || criteria[f.name] !== 'true') return false;
@@ -653,7 +729,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}
/>
@@ -672,8 +754,19 @@ export default function ReportPage() {
<Autocomplete
multiple={field.multiple || false}
freeSolo
filterSelectedOptions
options={options.map(opt => 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
@@ -762,9 +855,11 @@ export default function ReportPage() {
fullWidth
required={field.required}
error={Boolean(fieldErrors[field.name])}
helperText={fieldErrors[field.name] || undefined}
helperText={fieldErrors[field.name] || hintText || undefined}
label={translatedLabel}
type={field.type}
type={field.multiline ? 'text' : field.type}
multiline={field.multiline}
minRows={field.multiline ? (field.minRows ?? 4) : undefined}
placeholder={field.placeholder}
disabled={disabledByCheckedCheckbox || disabledRep012Status || !!field.disabled}
sx={{
@@ -854,6 +949,7 @@ export default function ReportPage() {
{currentReport.id === 'rep-005' ? (
<SemiFGProductionAnalysisReport
criteria={criteria}
prepareCriteria={flushPendingItemCodeInputs}
requiredFieldLabels={currentReport.fields.filter(f => f.required && !criteria[f.name]).map(f => fieldLabel(currentReport.id, f))}
loading={loading}
setLoading={setLoading}


+ 62
- 0
src/app/(main)/report/parseItemCodeTokens.ts Целия файл

@@ -0,0 +1,62 @@
/** Split pasted / typed item codes from Excel or a text field. */
const ITEM_CODE_SEPARATORS = /[\s,;,、\u00A0\u3000]+/;

export function parseItemCodeTokens(raw: string | undefined | null): string[] {
if (!raw) return [];
const seen = new Set<string>();
const tokens: string[] = [];
for (const part of raw.split(ITEM_CODE_SEPARATORS)) {
const token = part.trim();
if (!token) continue;
const key = token.toUpperCase();
if (seen.has(key)) continue;
seen.add(key);
tokens.push(token);
}
return tokens;
}

export function resolveItemCodeFieldName(criteria: Record<string, string>): string {
return Object.prototype.hasOwnProperty.call(criteria, "finishedItemCode")
? "finishedItemCode"
: "itemCode";
}

/** Merge multi-select item codes with pasted `itemCodePaste`; drop the paste field from API params. */
export function mergePastedItemCodes(
criteria: Record<string, string>,
codeField = resolveItemCodeFieldName(criteria),
): Record<string, string> {
const next: Record<string, string> = { ...criteria };
delete next.itemCodePaste;
const merged = parseItemCodeTokens(
[criteria[codeField], criteria.itemCodePaste].filter(Boolean).join(" "),
);
if (merged.length > 0) {
next[codeField] = merged.join(",");
} else {
delete next[codeField];
}
return next;
}

/** POST body so pasted codes are not limited by URL length. */
export function buildItemCodePasteRequestBody(
criteria: Record<string, string>,
codeField = resolveItemCodeFieldName(criteria),
): Record<string, unknown> {
const itemCodes = parseItemCodeTokens(
[criteria[codeField], criteria.itemCodePaste].filter(Boolean).join(" "),
);
const body: Record<string, unknown> = {};
for (const [key, value] of Object.entries(criteria)) {
if (key === "itemCodePaste" || key === codeField) continue;
const trimmed = value?.trim();
if (trimmed) body[key] = trimmed;
}
if (itemCodes.length) {
body[codeField] = itemCodes.join(",");
body.itemCodes = itemCodes;
}
return body;
}

+ 7
- 1
src/app/(main)/report/reportI18n.ts Целия файл

@@ -19,6 +19,12 @@ export function useReportLabels() {
defaultValue: field.label,
});

const fieldHint = (reportId: string, fieldName: string, fallback = "") => {
const key = `reports.${reportId}.fieldHints.${fieldName}`;
if (!i18n.exists(key, { ns: "report" })) return fallback;
return String(t(key, { defaultValue: fallback }));
};

const optionLabel = (
reportId: string,
fieldName: string,
@@ -35,7 +41,7 @@ export function useReportLabels() {
const categoryTitle = (id: string, fallback: string) =>
t(`categories.${id}`, { defaultValue: fallback });

return { t, i18n, reportTitle, fieldLabel, optionLabel, categoryTitle };
return { t, i18n, reportTitle, fieldLabel, fieldHint, optionLabel, categoryTitle };
}

export function reportExcelT(


+ 65
- 8
src/app/(main)/report/semiFGProductionAnalysisApi.ts Целия файл

@@ -2,6 +2,7 @@

import { NEXT_PUBLIC_API_URL } from '@/config/api';
import { clientAuthFetch } from '@/app/utils/clientAuthFetch';
import { buildItemCodePasteRequestBody } from './parseItemCodeTokens';

export interface ItemCodeWithName {
code: string;
@@ -72,12 +73,15 @@ export const generateSemiFGProductionAnalysisReport = async (
criteria: Record<string, string>,
reportTitle: string = '成品/半成品生產分析報告'
): Promise<void> => {
const queryParams = new URLSearchParams(criteria).toString();
const url = `${NEXT_PUBLIC_API_URL}/report/print-semi-fg-production-analysis?${queryParams}`;
const url = `${NEXT_PUBLIC_API_URL}/report/print-semi-fg-production-analysis`;

const response = await clientAuthFetch(url, {
method: 'GET',
headers: { Accept: 'application/pdf' },
method: 'POST',
headers: {
Accept: 'application/pdf',
'Content-Type': 'application/json',
},
body: JSON.stringify(buildItemCodePasteRequestBody(criteria, 'itemCode')),
});

if (response.status === 401 || response.status === 403) throw new Error("Unauthorized");
@@ -111,12 +115,15 @@ export const generateSemiFGProductionAnalysisReportExcel = async (
criteria: Record<string, string>,
reportTitle: string = '成品/半成品生產分析報告'
): Promise<void> => {
const queryParams = new URLSearchParams(criteria).toString();
const url = `${NEXT_PUBLIC_API_URL}/report/print-semi-fg-production-analysis-excel?${queryParams}`;
const url = `${NEXT_PUBLIC_API_URL}/report/print-semi-fg-production-analysis-excel`;

const response = await clientAuthFetch(url, {
method: 'GET',
headers: { Accept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
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');
@@ -139,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<string, string>,
reportTitle: string = '成品/半成品生產分析報告'
): Promise<void> => {
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<string> {
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();
}

+ 27
- 0
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 (
<I18nProvider namespaces={["shop", "navigation", "common"]}>
{children}
</I18nProvider>
);
}

+ 12
- 6
src/app/(main)/settings/stockLedgerFix/page.tsx Целия файл

@@ -1,16 +1,22 @@
import { Metadata } from "next";
import PageTitleBar from "@/components/PageTitleBar";
import StockLedgerFixPageClient from "@/components/StockLedgerFix/StockLedgerFixPageClient";
import { getServerI18n, I18nProvider } from "@/i18n";

export const metadata: Metadata = {
title: "Stock Ledger Fix",
};
export async function generateMetadata(): Promise<Metadata> {
const { t } = await getServerI18n("stockLedgerFix");
return { title: t("pageTitle") };
}

const StockLedgerFixPage: React.FC = async () => {
const { t } = await getServerI18n("stockLedgerFix");

const StockLedgerFixPage: React.FC = () => {
return (
<>
<PageTitleBar title="Stock Ledger Fix" className="mb-4" />
<StockLedgerFixPageClient />
<PageTitleBar title={t("pageTitle")} className="mb-4" />
<I18nProvider namespaces={["stockLedgerFix", "navigation", "common"]}>
<StockLedgerFixPageClient />
</I18nProvider>
</>
);
};


+ 0
- 2
src/app/api/doworkbench/actions.ts Целия файл

@@ -216,7 +216,6 @@ export async function fetchWorkbenchStoreLaneSummary(
return serverFetchJson<StoreLaneSummary>(url, {
method: "GET",
cache: "no-store",
next: { revalidate: 0 },
});
}

@@ -235,7 +234,6 @@ export async function fetchWorkbenchEtraLaneSummary(
const data = await serverFetchJson<WorkbenchEtraShopLaneGroup[]>(url, {
method: "GET",
cache: "no-store",
next: { revalidate: 0 },
});
return Array.isArray(data) ? data : [];
}


+ 19
- 19
src/app/api/itemTracing/schema.ts Целия файл

@@ -85,7 +85,7 @@ const ItemLotTraceMaterialInputSchema: z.ZodType<Record<string, unknown>> = 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<Record<string, unknown>> = 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();


+ 0
- 2
src/app/api/pickOrder/actions.ts Целия файл

@@ -632,7 +632,6 @@ export async function fetchStoreLaneSummary(storeId: string, requiredDate?: stri
const response = await serverFetchJson<StoreLaneSummary>(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 },
},
);
};


+ 4
- 0
src/app/api/po/index.ts Целия файл

@@ -54,11 +54,15 @@ export interface StockUomForPoLine {
id: number;
stockUomCode: string;
stockUomDesc: string;
stockUomShortDesc?: string | null;
stockQty: number;
stockRatioN: number;
stockRatioD: number;
purchaseRatioN: number;
purchaseRatioD: number;
sourceRatioN?: number | null;
sourceRatioD?: number | null;
stockQtyInteger?: boolean | null;
}

// DEPRECIATED


+ 2
- 0
src/app/api/settings/uom/index.ts Целия файл

@@ -9,6 +9,8 @@ export interface Uom {
id: number;
code: string;
udfudesc: string;
/** Short UoM label from M18 (`udfShortDesc`), e.g. 箱. */
udfShortDesc?: string | null;
unit1: string;
unit1Qty: number;
unit2?: string;


+ 6
- 0
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;


+ 144
- 5
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<string | null> | 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<string | null> {
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<string | null> {
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;
}

+ 37
- 10
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<string | null> {
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<Response> {
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;
}
}


+ 4
- 0
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;

/**


+ 8
- 1
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<AppBarProps, "avatarImageSrc" | "profileName">;

@@ -51,7 +52,13 @@ const Profile: React.FC<Props> = ({ avatarImageSrc, profileName }) => {
{profileName}
</Typography>
<Divider />
<MenuItem onClick={() => signOut()} sx={{ py: 1.5, fontSize: "0.875rem" }}>
<MenuItem
onClick={() => {
clearBackendTokens();
void signOut();
}}
sx={{ py: 1.5, fontSize: "0.875rem" }}
>
{t("Sign out")}
</MenuItem>
</Menu>


+ 1
- 0
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",


+ 26
- 10
src/components/DoWorkbench/DoWorkbenchTabs.tsx Целия файл

@@ -186,7 +186,7 @@ const DoWorkbenchTabsInner: React.FC<Props> = ({ 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<Props> = ({ defaultTabIndex = 0, printerCom
<Tabs
value={tab}
onChange={handleTabChange}
variant="scrollable"
scrollButtons="auto"
allowScrollButtonsMobile
sx={{
width: "100%",
maxWidth: "100%",
minHeight: 48,
borderBottom: 1,
borderColor: "divider",
"& .MuiTabs-flexContainer": {
columnGap: 2,
rowGap: 1,
columnGap: 0.5,
},
/* 否則 Tab 內 overflow:hidden 會把 Badge 數字裁成紅點 */
"& .MuiTab-root": {
overflow: "visible",
minWidth: "auto",
px: 2,
minHeight: 48,
minWidth: 72,
maxWidth: "none",
px: 1.5,
py: 0.75,
whiteSpace: "nowrap",
lineHeight: 1.2,
textAlign: "center",
},
}}
>
@@ -297,7 +308,7 @@ const DoWorkbenchTabsInner: React.FC<Props> = ({ 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={
<Tooltip
@@ -329,7 +340,12 @@ const DoWorkbenchTabsInner: React.FC<Props> = ({ defaultTabIndex = 0, printerCom
<Typography
component="span"
variant="inherit"
sx={{ pr: etraIncompleteDopoCount > 0 ? 1 : 0 }}
sx={{
pr: etraIncompleteDopoCount > 0 ? 1 : 0,
whiteSpace: "nowrap",
lineHeight: 1.2,
textAlign: "center",
}}
>
{t("Etra Pick Order Detail")}
</Typography>
@@ -341,8 +357,8 @@ const DoWorkbenchTabsInner: React.FC<Props> = ({ defaultTabIndex = 0, printerCom
<Tab label={t("Finished Good Record")} value={2} />
<Tab label={t("Finished Good Record (All)")} value={3} />
<Tab label={t("Ticket Release Table")} value={4} />
<Tab label={t("成品出倉出箱數量")} value={5} />
<Tab label={t("送貨路線摘要")} value={6} />
<Tab label={t("FG Carton Qty")} value={5} />
<Tab label={t("Truck Routing Summary")} value={6} />
</Tabs>

<TabPanel value={tab} index={0}>
@@ -401,7 +417,7 @@ const DoWorkbenchTabsInner: React.FC<Props> = ({ 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> = (props) => (
<Suspense


+ 151
- 91
src/components/DoWorkbench/GoodPickExecutionWorkbenchRecord.tsx Целия файл

@@ -67,6 +67,8 @@ const GoodPickExecutionWorkbenchRecord: 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<CompletedDoPickOrderResponse[]>([]);
const initialSearchTargetDate = useMemo(
() => resolveWorkbenchRecordTargetDate(initialTargetDate),
@@ -183,6 +185,65 @@ const GoodPickExecutionWorkbenchRecord: React.FC<Props> = ({
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<void>((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<Props> = ({

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<Props> = ({
});
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<Props> = ({
});
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<Props> = ({
});
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<Props> = ({
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<Props> = ({
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<Props> = ({
<Button variant="outlined" onClick={() => void handleDetailClick(row)}>
{t("View Details")}
</Button>
<Button variant="contained" onClick={() => void handlePrintDN(row.doPickOrderRecordId)}>
<Button variant="contained" disabled={isPrinting} onClick={() => void handlePrintDN(row.doPickOrderRecordId)}>
{t("Print Pick Order")}
</Button>
<Button variant="contained" onClick={() => void handlePrintBoth(row.doPickOrderRecordId)}>
<Button variant="contained" disabled={isPrinting} onClick={() => void handlePrintBoth(row.doPickOrderRecordId)}>
{t("Print DN & Label")}
</Button>
<Button variant="contained" onClick={() => void handlePrintLabel(row.doPickOrderRecordId)}>
<Button variant="contained" disabled={isPrinting} onClick={() => void handlePrintLabel(row.doPickOrderRecordId)}>
{t("Print Label")}
</Button>
<Button variant="contained" onClick={() => void handleLabelReprint(row)}>
<Button variant="contained" disabled={isPrinting} onClick={() => void handleLabelReprint(row)}>
{t("Reprint Label(s)")}
</Button>
</CardActions>


+ 16
- 9
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<WorkbenchReportOption[]>([]);
const [laneOptions, setLaneOptions] = useState<WorkbenchReportOption[]>([]);
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 (
<Box sx={{ maxWidth: 820 }}>
<Typography variant="h6" sx={{ mb: 2 }}>
送貨路線摘要 (Workbench)
{t("Truck Routing Summary (Workbench)")}
</Typography>
<Stack direction={{ xs: "column", md: "row" }} spacing={2} sx={{ mb: 2 }}>
<TextField
select
fullWidth
label="2/F 或 4/F"
label={t("2/F or 4/F")}
value={storeId}
onChange={(e) => onStoreChange(e.target.value)}
>
{storeOptions.map((opt) => (
<MenuItem key={opt.value} value={opt.value}>
{opt.label}
{displayOptionLabel(opt.label)}
</MenuItem>
))}
</TextField>
<TextField
select
fullWidth
label="車線"
label={t("Lane")}
value={truckLanceCode}
onChange={(e) => setTruckLanceCode(e.target.value)}
disabled={!storeId}
>
{laneOptions.map((opt) => (
<MenuItem key={opt.value} value={opt.value}>
{opt.label}
{displayOptionLabel(opt.label)}
</MenuItem>
))}
</TextField>
<TextField
fullWidth
label="日期"
label={t("Date")}
type="date"
value={date}
InputLabelProps={{ shrink: true }}
@@ -146,7 +153,7 @@ const TruckRoutingSummaryTabWorkbench: React.FC = () => {
disabled={!canDownload}
onClick={onDownload}
>
{loading ? "生成中..." : "下載報告 (PDF)"}
{loading ? t("Generating...") : t("Download report (PDF)")}
</Button>
</Box>
);


+ 26
- 16
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, unknown>) => 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, unknown>) => 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;
}


+ 48
- 44
src/components/DoWorkbench/WorkbenchLotLabelPrintModal.tsx Целия файл

@@ -37,6 +37,7 @@ import {
printWorkbenchLotLabel,
} from "@/app/api/doworkbench/actions";
import { QRCodeSVG } from "qrcode.react";
import { useTranslation } from "react-i18next";

type ScanPayload = {
itemId: number;
@@ -167,6 +168,7 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
submitQty = null,
onSubmitQtyChange,
}) => {
const { t } = useTranslation();
const scanInputRef = useRef<HTMLInputElement | null>(null);
const [scanInput, setScanInput] = useState("");
const [scanError, setScanError] = useState<string | null>(null);
@@ -210,8 +212,8 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
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]);

const loadPrinters = useCallback(async () => {
@@ -224,13 +226,13 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
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;
@@ -283,23 +285,23 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
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);
@@ -325,17 +327,17 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
});
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 () => {
@@ -343,13 +345,13 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
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());
@@ -368,12 +370,12 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
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;
@@ -470,7 +472,7 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
if (selectedPrinterId === "") {
setSnackbar({
open: true,
message: "請先選擇印表機",
message: t("Please select a printer first"),
severity: "error",
});
return;
@@ -478,7 +480,7 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
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;
@@ -493,25 +495,25 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
});
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 (
<Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
<DialogTitle>批號標籤列印(提貨台)</DialogTitle>
<DialogTitle>{t("Lot label print (pick station)")}</DialogTitle>
<DialogContent>
<Stack spacing={2} sx={{ mt: 1 }}>
{statusTitleText ? (
@@ -548,13 +550,13 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
>
<TextField
inputRef={scanInputRef}
label="掃碼內容"
label={t("Scan content")}
value={scanInput}
onChange={(e) => 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();
@@ -568,7 +570,7 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
onClick={() => void handleAnalyze()}
disabled={analysisLoading || !scanInput.trim()}
>
{analysisLoading ? <CircularProgress size={18} /> : "查詢"}
{analysisLoading ? <CircularProgress size={18} /> : t("Look up")}
</Button>
<Button
variant="outlined"
@@ -578,7 +580,7 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
}}
disabled={analysisLoading}
>
清除
{t("Clear")}
</Button>
</Stack>
</>
@@ -594,16 +596,16 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
sx={{ minWidth: 260 }}
disabled={printersLoading}
>
<InputLabel>印表機</InputLabel>
<InputLabel>{t("Printer")}</InputLabel>
<Select
label="印表機"
label={t("Printer")}
value={selectedPrinterId}
onChange={(e) =>
setSelectedPrinterId((e.target.value as number) ?? "")
}
>
<MenuItem value="">
<em>{printersLoading ? "載入中..." : "請選擇"}</em>
<em>{printersLoading ? t("Loading") : t("Please select")}</em>
</MenuItem>
{printers.map((p) => (
<MenuItem key={p.id} value={p.id}>
@@ -614,7 +616,7 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
</FormControl>

<TextField
label="列印張數"
label={t("Print copies")}
size="small"
type="number"
inputProps={{ min: 1, step: 1 }}
@@ -626,7 +628,7 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =

{onWorkbenchScanPick ? (
<TextField
label="提交數量"
label={t("Submit Qty")}
size="small"
type="number"
inputProps={{ min: 0, step: 1 }}
@@ -651,7 +653,7 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
{analysisLoading ? (
<CircularProgress size={18} />
) : (
"刷新批號清單"
t("Refresh lot list")
)}
</Button>

@@ -661,7 +663,7 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
color="text.secondary"
sx={{ ml: { md: "auto" } }}
>
已選:{formatPrinterLabel(selectedPrinter)}
{t("Selected printer", { printer: formatPrinterLabel(selectedPrinter) })}
</Typography>
)}
</Stack>
@@ -669,12 +671,12 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
{analysis && (
<Box>
<Typography variant="subtitle1" sx={{ fontWeight: 700, mb: 1 }}>
品號:{analysis.itemCode} {analysis.itemName}
{t("Item code name", { code: analysis.itemCode, name: analysis.itemName })}
</Typography>

{filteredLots.length === 0 ? (
<Alert severity="warning">
找不到該樓層有可用批號(availableQty &gt; 0)。
{t("No available lots on this floor")}
</Alert>
) : (
<Stack spacing={1}>
@@ -717,14 +719,16 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
sx={{ fontWeight: lot._scanned ? 800 : 600 }}
>
Lot:{lot.lotNo}
{lot._scanned ? "(當前批次)" : ""}
{lot._scanned ? t(" (current lot)") : ""}
</Typography>
<Typography variant="body2" color="text.secondary">
位置:{loc || "—"}
{t("Location with value", { location: loc || "—" })}
</Typography>
<Typography variant="body2" color="text.secondary">
可用量:{Number(lot.availableQty).toLocaleString()}{" "}
單位:{lot.uom || ""}
{t("Available qty with uom", {
qty: Number(lot.availableQty).toLocaleString(),
uom: lot.uom || "",
})}
</Typography>
</Box>
<Stack
@@ -747,7 +751,7 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
{isPrinting ? (
<CircularProgress size={18} />
) : (
"列印標籤"
t("Print label")
)}
</Button>
{onWorkbenchScanPick ? (
@@ -756,9 +760,9 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
color="secondary"
title={
!lotQrPayload
? "此列無法取得 QR payload(需 stockInLineId)"
? t("This row has no QR payload")
: disableScanPick
? "此出庫行已掃碼或已完成,無法顯示 QR"
? t("This pick line already scanned or completed, QR cannot be shown")
: undefined
}
disabled={
@@ -772,7 +776,7 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
)
}
>
顯示 QR
{t("Show QR")}
</Button>
) : null}
</Stack>
@@ -809,14 +813,14 @@ const WorkbenchLotLabelPrintModal: React.FC<WorkbenchLotLabelPrintModalProps> =
<Typography variant="body2" color="text.secondary">

{onWorkbenchScanPick
? "沒有任何批號可列印標籤"
? t("No lots available to print labels")
: ""}
</Typography>
)}
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>關閉</Button>
<Button onClick={onClose}>{t("Close")}</Button>
</DialogActions>

<Snackbar


+ 903
- 179
src/components/FinishedGoodSearch/FinishedGoodCartonDashboardTab.tsx
Файловите разлики са ограничени, защото са твърде много
Целия файл


+ 8
- 8
src/components/LoginPage/LoginForm.tsx Целия файл

@@ -13,7 +13,7 @@ import { useEffect, useState } from "react";
import { SubmitHandler, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { SetupAxiosInterceptors } from "@/app/(main)/axios/axiosInstance";
import { useToken } from "@/app/(main)/axios/AxiosProvider";
import { persistBackendTokens } from "@/app/utils/authToken";
import { Visibility, VisibilityOff } from "@mui/icons-material";

type LoginFields = {
@@ -25,6 +25,7 @@ type SessionWithAbilities =
| ({
abilities: string[];
accessToken?: string;
refreshToken?: string;
} & Session)
| null;

@@ -53,7 +54,6 @@ const LoginForm: React.FC = () => {
const [serverError, setServerError] = useState<string>();

const router = useRouter();
const { setAccessToken } = useToken();

const [showPassword, setShowPassword] = useState(false);
const handleClickShowPassword = () => setShowPassword(!showPassword);
@@ -71,13 +71,13 @@ const LoginForm: React.FC = () => {
return;
}

// set auth to local storage
// Persist access + refresh in localStorage (Login is outside AxiosProvider)
const session = (await getSession()) as SessionWithAbilities;
// @ts-ignore
window.localStorage.setItem("accessToken", session?.accessToken ?? "");
setAccessToken(session?.accessToken ?? null);
SetupAxiosInterceptors(session?.accessToken ?? null);
// console.log(session)
const access = session?.accessToken ?? "";
if (access) {
persistBackendTokens(access, session?.refreshToken);
SetupAxiosInterceptors(access);
}
window.localStorage.setItem(
"abilities",
JSON.stringify(session?.abilities),


+ 2
- 0
src/components/LogoutPage/LogoutPage.tsx Целия файл

@@ -3,11 +3,13 @@
import { signOut } from "next-auth/react";
import { useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { clearBackendTokens } from "@/app/utils/authToken";

const LogoutPage = () => {
const params = useSearchParams();
const callbackUrl = params.get("callbackUrl");
useEffect(() => {
clearBackendTokens();
signOut({ redirect: true, callbackUrl: callbackUrl || "/" });
});



+ 18
- 1
src/components/NavigationContent/NavigationContent.tsx Целия файл

@@ -303,7 +303,7 @@ const NavigationContent: React.FC = () => {
icon: <Settings />,
labelKey: "nav.settings",
path: "",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN, AUTH.TRUCK_LANE],
children: [
{
id: "nav.settings.user",
@@ -325,78 +325,91 @@ const NavigationContent: React.FC = () => {
icon: <Category />,
labelKey: "nav.settings.items",
path: "/settings/items",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.itemDefaultShelfLife",
icon: <EventAvailable />,
labelKey: "nav.settings.itemDefaultShelfLife",
path: "/settings/itemDefaultShelfLife",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.equipment",
icon: <Build />,
labelKey: "nav.settings.equipment",
path: "/settings/equipment",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.warehouse",
icon: <Warehouse />,
labelKey: "nav.settings.warehouse",
path: "/settings/warehouse",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.printer",
icon: <Print />,
labelKey: "nav.settings.printer",
path: "/settings/printer",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.priceInquiry",
icon: <Assessment />,
labelKey: "nav.settings.priceInquiry",
path: "/settings/itemPrice",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.qcItem",
icon: <VerifiedUser />,
labelKey: "nav.settings.qcItem",
path: "/settings/qcItem",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.qcCategory",
icon: <Label />,
labelKey: "nav.settings.qcCategory",
path: "/settings/qcCategory",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.qcItemAll",
icon: <Checklist />,
labelKey: "nav.settings.qcItemAll",
path: "/settings/qcItemAll",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.shopAndTruck",
icon: <Storefront />,
labelKey: "nav.settings.shopAndTruck",
path: "/settings/shop/board",
requiredAbility: [AUTH.TRUCK_LANE, AUTH.ADMIN],
},
{
id: "nav.settings.deliveryOrderFloor",
icon: <Layers />,
labelKey: "nav.settings.deliveryOrderFloor",
path: "/settings/deliveryOrderFloor",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.demandForecast",
icon: <TrendingUp />,
labelKey: "nav.settings.demandForecast",
path: "/settings/rss",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.bomWeighting",
icon: <ViewModule />,
labelKey: "nav.settings.bomWeighting",
path: "/settings/bomWeighting",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.masterDataIssues",
@@ -410,24 +423,28 @@ const NavigationContent: React.FC = () => {
icon: <QrCodeIcon />,
labelKey: "nav.settings.qrCodeHandle",
path: "/settings/qrCodeHandle",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.importTesting",
icon: <Science />,
labelKey: "nav.settings.importTesting",
path: "/settings/m18ImportTesting",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.importExcel",
icon: <UploadFile />,
labelKey: "nav.settings.importExcel",
path: "/settings/importExcel",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
{
id: "nav.settings.importBom",
icon: <UploadFile />,
labelKey: "nav.settings.importBom",
path: "/settings/importBom",
requiredAbility: [AUTH.VIEW_USER, AUTH.ADMIN],
},
],
},


+ 4
- 4
src/components/PickOrderSearch/WorkbenchPickExecution.tsx Целия файл

@@ -654,11 +654,11 @@ const WorkbenchPickExecution: React.FC<Props> = ({ filterArgs }) => {
}
const reminder = workbenchLotLabelReminderText?.trim() ?? "";
if (reminder && isExpiredWorkbenchReminderMessage(reminder)) {
return { text: "此批號狀態:已過期", severity: "error" as const };
return { text: t("Lot status: expired"), severity: "error" as const };
}
const s = getWorkbenchSourceLotStatusSummary(workbenchLotLabelContextLot);
const s = getWorkbenchSourceLotStatusSummary(workbenchLotLabelContextLot, t);
return { text: s.text, severity: s.severity };
}, [workbenchLotLabelModalOpen, workbenchLotLabelContextLot, workbenchLotLabelReminderText]);
}, [workbenchLotLabelModalOpen, workbenchLotLabelContextLot, workbenchLotLabelReminderText, t]);

const handleJustComplete = useCallback(
async (row: LotRow) => {
@@ -1714,7 +1714,7 @@ const WorkbenchPickExecution: React.FC<Props> = ({ filterArgs }) => {
onClick={() => openWorkbenchLotLabelModalForLot(r)}
sx={{ flexShrink: 0, fontSize: "0.7rem", py: 0.25, minWidth: "auto", px: 1, whiteSpace: "nowrap" }}
>
{t(" 批號 QR 碼")}
{t("lot QR code")}
</Button>
) : null}
</Stack>


+ 8
- 2
src/components/PoDetail/PoDetail.tsx Целия файл

@@ -207,7 +207,7 @@ interface PolInputResult {
dnQty: string,
}

/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.4 | 2026-09-10 */
/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18 */
const PoDetail: React.FC<Props> = ({ po, warehouse, printerCombo }) => {
const cameras = useContext(CameraContext);
const { data: session } = useSession();
@@ -875,7 +875,13 @@ const PoDetail: React.FC<Props> = ({ po, warehouse, printerCombo }) => {
<TableCell align="left" sx={{ width: '75px' }}>{t("status")}</TableCell>
{/* {renderFieldCondition(FIRST_IN_FIELD) ? <TableCell align="right">{t("receivedQty")}</TableCell> : undefined} */}
<TableCell align="center" sx={{ width: '150px' }}>{t("productLotNo")}</TableCell>
{renderFieldCondition(SECOND_IN_FIELD) ? <TableCell align="center" sx={{ width: '150px' }}>{t("dnQty")}<br/>(以訂單單位計算)</TableCell> : undefined}
{renderFieldCondition(SECOND_IN_FIELD) ? (
<TableCell align="center" sx={{ width: 360, minWidth: 360 }}>
{t("dnQty")}
<br />
({t("dnQtyOrderUnitHint")})
</TableCell>
) : undefined}
<TableCell align="center" sx={{ width: '100px' }}></TableCell>
</TableRow>
</TableHead>


+ 146
- 20
src/components/PoDetail/PoDetailRow.tsx Целия файл

@@ -4,10 +4,13 @@ import { PurchaseOrderLine } from "@/app/api/po";
import {
Box,
Button,
InputAdornment,
Radio,
Stack,
TableCell,
TableRow,
TextField,
Typography,
alpha,
} from "@mui/material";
import { memo, useCallback, useEffect, useRef, useState } from "react";
@@ -16,6 +19,12 @@ import { decimalFormatter, integerFormatter } from "@/app/utils/formatUtil";
import { submitDialogWithWarning } from "../Swal/CustomAlerts";
import { createStockInLine } from "@/app/api/stockIn/actions";
import { previewPoBatchStockQty } from "./stockQtyRound";
import {
formatQtyWithPurchaseUom,
formatQtyWithStockUom,
poLineNeedsStockQtyConversion,
purchaseUomShortDesc,
} from "./poPurchaseUom";

const PURCHASE_STOCK_IN_ALERT_STATUSES = new Set(["pending", "receiving"]);

@@ -68,7 +77,7 @@ type Props = {
onSubmitted: (row: PurchaseOrderLine) => void;
};

/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.4 | 2026-09-10 */
/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18 */
export const PoDetailRow = memo(function PoDetailRow({
row,
selected,
@@ -108,6 +117,7 @@ export const PoDetailRow = memo(function PoDetailRow({
orderQty,
Number(row.stockUom?.stockQty ?? 0),
acceptedQty,
row.stockUom,
);

const doSubmit = () => {
@@ -186,6 +196,28 @@ export const PoDetailRow = memo(function PoDetailRow({
Number(receivedTotalText.replace(/,/g, "")) <= 0 ? "red" : "inherit";
const needsStockInAttention =
canSeeStockInReminders && purchaseOrderLineHasIncompleteStockIn(row);
const uomShort = purchaseUomShortDesc(row.uom);
const orderQtyWithUnit = formatQtyWithPurchaseUom(row.qty, row.uom);
const enteredBatchQty = Number(dnQtyInput.trim());
const hasEnteredBatchQty = Number.isInteger(enteredBatchQty) && enteredBatchQty > 0;
const showStockConversion =
hasEnteredBatchQty &&
poLineNeedsStockQtyConversion(
Number(row.qty ?? 0),
Number(row.stockUom?.stockQty ?? 0),
row.uom,
row.stockUom,
);
const convertedStockQty = previewPoBatchStockQty(
Number(row.qty ?? 0),
Number(row.stockUom?.stockQty ?? 0),
enteredBatchQty,
row.stockUom,
);
const convertedStockQtyWithUnit = formatQtyWithStockUom(
convertedStockQty,
row.stockUom,
);

return (
<TableRow
@@ -243,7 +275,19 @@ export const PoDetailRow = memo(function PoDetailRow({
>
{row.itemName}
</TableCell>
<TableCell align="right">{integerFormatter.format(row.qty)}</TableCell>
<TableCell
align="right"
sx={{
fontWeight: 800,
fontVariantNumeric: "tabular-nums",
whiteSpace: "nowrap",
fontSize: "1.05rem",
color: "text.primary",
}}
title={row.uom?.udfudesc || uomShort || undefined}
>
{orderQtyWithUnit}
</TableCell>
<TableCell align="right">{integerFormatter.format(row.processed)}</TableCell>
<TableCell align="left">{row.uom?.udfudesc}</TableCell>
<TableCell sx={{ color: highlightColor }} align="right">
@@ -268,25 +312,107 @@ export const PoDetailRow = memo(function PoDetailRow({
/>
</TableCell>
{showDnQty ? (
<TableCell align="center">
<TextField
id={`dnQty-${row.id}`}
label="此批來貨數量"
type="text"
variant="outlined"
value={dnQtyInput}
onChange={(e) => setDnQtyInput(e.target.value.replace(/[^\d]/g, ""))}
onBlur={() => onInputBlur(row.id, lotNoInput, dnQtyInput)}
<TableCell align="center" sx={{ py: 1, overflow: "visible" }}>
<Stack
direction="row"
spacing={1.25}
alignItems="center"
justifyContent="center"
flexWrap="nowrap"
sx={{ width: "max-content" }}
onClick={(e) => e.stopPropagation()}
InputProps={{
inputProps: {
min: 1,
step: 1,
inputMode: "numeric",
pattern: "[0-9]*",
},
}}
/>
>
<TextField
id={`dnQty-${row.id}`}
label={t("dnQty")}
type="text"
variant="outlined"
value={dnQtyInput}
onChange={(e) => setDnQtyInput(e.target.value.replace(/[^\d]/g, ""))}
onBlur={() => onInputBlur(row.id, lotNoInput, dnQtyInput)}
onClick={(e) => e.stopPropagation()}
sx={{
minWidth: 168,
width: 168,
flexShrink: 0,
"& .MuiInputLabel-root": {
maxWidth: "calc(100% - 44px)",
},
"& .MuiInputBase-input": {
pr: 0.5,
},
}}
InputLabelProps={{ shrink: true }}
InputProps={{
notched: true,
endAdornment: uomShort ? (
<InputAdornment position="end" sx={{ ml: 0.5 }}>
<Typography
component="span"
sx={{
fontWeight: 800,
fontSize: "1.05rem",
color: "primary.main",
lineHeight: 1,
}}
>
{uomShort}
</Typography>
</InputAdornment>
) : undefined,
inputProps: {
min: 1,
step: 1,
inputMode: "numeric",
pattern: "[0-9]*",
"aria-label": `${t("dnQty")} ${uomShort}`.trim(),
},
}}
/>
{showStockConversion && Number.isFinite(convertedStockQty) && convertedStockQty > 0 ? (
<Box
sx={{
flexShrink: 0,
width: "max-content",
boxSizing: "border-box",
px: 1.25,
py: 0.75,
borderRadius: 1,
bgcolor: (theme) => alpha(theme.palette.primary.main, 0.1),
border: 1,
borderColor: "primary.main",
textAlign: "center",
}}
title={row.stockUom?.stockUomDesc || convertedStockQtyWithUnit}
>
<Typography
component="div"
sx={{
fontSize: "0.7rem",
lineHeight: 1.2,
color: "text.secondary",
fontWeight: 600,
}}
>
{t("stockQtyRef")}
</Typography>
<Typography
component="div"
sx={{
fontWeight: 800,
fontSize: "1rem",
lineHeight: 1.3,
color: "primary.main",
fontVariantNumeric: "tabular-nums",
whiteSpace: "nowrap",
px: 0.25,
}}
>
{convertedStockQtyWithUnit}
</Typography>
</Box>
) : null}
</Stack>
</TableCell>
) : null}
<TableCell align="center">


+ 5
- 4
src/components/PoDetail/PoInputGrid.tsx Целия файл

@@ -61,7 +61,7 @@ import DoDisturbIcon from "@mui/icons-material/DoDisturb";
import { useSession } from "next-auth/react";
// import { SessionWithTokens } from "src/config/authConfig";
import QcStockInModal from "../Qc/QcStockInModal";
import { decimalFormatter, integerFormatter } from "@/app/utils/formatUtil";
import { decimalFormatter } from "@/app/utils/formatUtil";
import { PrinterCombo } from "@/app/api/settings/printer";
import { EscalationResult } from "@/app/api/escalation";
import { fetchEscalationLogsByStockInLines } from "@/app/api/escalation/actions";
@@ -70,10 +70,11 @@ import { EscalationCombo } from "@/app/api/user";
import { deleteDialog } from "../Swal/CustomAlerts";
import StockInLineRowActions from "./StockInLineRowActions";
import { StockQtyRoundMode, needsPoQcStockQtyRound } from "./stockQtyRound";
import { formatQtyWithPurchaseUom } from "./poPurchaseUom";

// 3 buttons after QC (view + print QR + delete): 176*3 + gap + cell padding
const ACTIONS_COLUMN_WIDTH = 580;
const PURCHASE_QTY_COLUMN_WIDTH = 72;
const PURCHASE_QTY_COLUMN_WIDTH = 96;
const UOM_COLUMN_WIDTH = 124;
const STOCK_QTY_COLUMN_WIDTH = 110;
const STOCK_IN_ROW_HEIGHT = 58;
@@ -154,7 +155,7 @@ class ProcessRowUpdateError extends Error {
}
}

/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.4 | 2026-09-10 */
/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18 */
function PoInputGrid({
// qc,
setRows,
@@ -719,7 +720,7 @@ function PoInputGrid({
type: "number",
renderCell: (params) => {
const qty = params.row.purchaseAcceptedQty ?? 0;
return integerFormatter.format(qty);
return formatQtyWithPurchaseUom(qty, itemDetail.uom);
},
},
{


+ 10
- 3
src/components/PoDetail/PutAwayForm.tsx Целия файл

@@ -55,6 +55,7 @@ import dayjs from "dayjs";
import arraySupport from "dayjs/plugin/arraySupport";
import { dummyPutAwayLine } from "../Qc/dummyQcTemplate";
import { GridRowModesModel } from "@mui/x-data-grid";
import { displayPutAwayLineQtyFromOriginSil } from "./originSilPutAwayQty";
dayjs.extend(arraySupport);

interface Props {
@@ -86,6 +87,7 @@ const style = {
width: "auto",
};

/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18 */
const PutAwayForm: React.FC<Props> = ({ itemDetail, warehouse=[], disabled, suggestedLocationCode, setRowModesModel, setRowSelectionModel }) => {
const { t } = useTranslation("purchaseOrder");
const apiRef = useGridApiRef();
@@ -241,8 +243,13 @@ const PutAwayForm: React.FC<Props> = ({ itemDetail, warehouse=[], disabled, sugg
headerAlign: "right",
align: "right",
renderCell(params) {
const displayQty = displayPutAwayLineQtyFromOriginSil(
itemDetail,
Number(params.value),
params.row._isNew,
);
return <span style={{fontSize:24}}>
{params.value}
{displayQty}
</span>
}
},
@@ -309,7 +316,7 @@ const PutAwayForm: React.FC<Props> = ({ itemDetail, warehouse=[], disabled, sugg
// return <>100</>
// },
// },
], [])
], [itemDetail, t])

const validation = useCallback(
(newRow: GridRowModel<PutAwayRow>): EntryError => {
@@ -395,7 +402,7 @@ const PutAwayForm: React.FC<Props> = ({ itemDetail, warehouse=[], disabled, sugg
<TextField
label={t("acceptedPutawayQty")} // TODO: fix it back to acceptedQty after db is fixed
fullWidth
value={itemDetail.qty ?? itemDetail.purchaseAcceptedQty ?? itemDetail.acceptedQty ?? itemDetail.demandQty}
value={itemDetail.purchaseAcceptedQty ?? itemDetail.acceptedQty ?? itemDetail.qty ?? itemDetail.demandQty}
disabled
/>
</Grid>


+ 3
- 2
src/components/PoDetail/QcStockInModal.tsx Целия файл

@@ -21,6 +21,7 @@ import { useTranslation } from "react-i18next";
import StockInForm from "../StockIn/StockInForm";
import QcComponent from "../Qc/QcComponent";
import PutAwayForm from "./PutAwayForm";
import { mapPutAwayLinesFromOriginSil } from "./originSilPutAwayQty";
import { GridRowModes, GridRowSelectionModel, useGridApiRef } from "@mui/x-data-grid";
import {msg, submitDialogWithWarning} from "../Swal/CustomAlerts";
import { INPUT_DATE_FORMAT, arrayToDateString, dayjsToDateTimeString } from "@/app/utils/formatUtil";
@@ -71,7 +72,7 @@ interface CommonProps extends Omit<ModalProps, "children"> {
interface Props extends CommonProps {
// itemDetail: StockInLine & { qcResult?: PurchaseQcResult[] } & { escResult?: EscalationResult[] };
}
/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.4 | 2026-09-10 */
/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18 */
const PoQcStockInModalVer2: React.FC<Props> = ({
open,
onClose,
@@ -205,7 +206,7 @@ const PoQcStockInModalVer2: React.FC<Props> = ({
// escResult: (d.escResult && d.escResult?.length > 0) ? d.escResult : [],
// qcResult: (d.qcResult && d.qcResult?.length > 0) ? d.qcResult : [],//[...dummyQCData],
warehouseId: d.defaultWarehouseId ?? 1,
putAwayLines: d.putAwayLines?.map((line) => ({...line, printQty: 1, _isNew: false, _disableDelete: true})) ?? [],
putAwayLines: mapPutAwayLinesFromOriginSil(d, d.putAwayLines),
} as ModalFormInput
)
} return undefined


+ 1
- 1
src/components/PoDetail/StockInLineRowActions.tsx Целия файл

@@ -26,7 +26,7 @@ type Props = {
onRound?: (mode: StockQtyRoundMode) => void;
};

/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.4 | 2026-09-10 */
/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18 */
export default function StockInLineRowActions({
btnSx,
onPrimaryClick,


+ 60
- 0
src/components/PoDetail/originSilPutAwayQty.ts Целия файл

@@ -0,0 +1,60 @@
import { PutAwayLine, StockInLine } from "@/app/api/stockIn";

type OriginSil = Pick<
StockInLine,
"jobOrderId" | "purchaseAcceptedQty" | "acceptedQty"
>;

/**
* FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18
* Path A: inventory_lot_line → inventory_lot → stock_in_line (the SIL that opened the lot).
* Never use inventory_lot_line.inQty — ADJ/TKE is added onto the same line later.
*
* PO: purchaseAcceptedQty (M18 / 採購單位)
* JO: acceptedQty (庫存/生產單位;JO 通常沒有 acceptedQtyM18)
*/
export function originSilPutAwayDisplayQty(origin: OriginSil): number {
if (origin.jobOrderId) {
const stock = Number(origin.acceptedQty);
return Number.isFinite(stock) && stock > 0 ? stock : 0;
}
const purchase = Number(origin.purchaseAcceptedQty);
if (Number.isFinite(purchase) && purchase > 0) return purchase;
const stock = Number(origin.acceptedQty);
return Number.isFinite(stock) && stock > 0 ? stock : 0;
}

/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18 */
export function originSilPutAwayStockQty(origin: OriginSil): number {
const stock = Number(origin.acceptedQty);
return Number.isFinite(stock) && stock > 0 ? stock : 0;
}

/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18 */
export function mapPutAwayLinesFromOriginSil(
origin: OriginSil,
lines: PutAwayLine[] | undefined,
): PutAwayLine[] {
const existing = lines ?? [];
const displayQty = originSilPutAwayDisplayQty(origin);
const stockQty = originSilPutAwayStockQty(origin);
return existing.map((line) => ({
...line,
printQty: 1,
_isNew: false,
_disableDelete: true,
...(displayQty > 0 ? { qty: displayQty } : {}),
...(stockQty > 0 ? { stockQty } : {}),
}));
}

/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18 */
export function displayPutAwayLineQtyFromOriginSil(
origin: OriginSil,
lineQty: number,
isNew: boolean | undefined,
): number {
if (isNew) return lineQty;
const originQty = originSilPutAwayDisplayQty(origin);
return originQty > 0 ? originQty : lineQty;
}

+ 96
- 0
src/components/PoDetail/poPurchaseUom.ts Целия файл

@@ -0,0 +1,96 @@
import { decimalFormatter, integerFormatter } from "@/app/utils/formatUtil";

type PurchaseUomLike = {
code?: string | null;
udfudesc?: string | null;
udfShortDesc?: string | null;
} | null | undefined;

type StockUomLike = {
stockUomCode?: string | null;
stockUomDesc?: string | null;
stockUomShortDesc?: string | null;
} | null | undefined;

function isCompactUnitLabel(value: string): boolean {
return value.length > 0 && value.length <= 6 && !/[x×]/i.test(value);
}

function compactUomLabel(
shortDesc?: string | null,
fullDesc?: string | null,
code?: string | null,
): string {
const short = shortDesc?.trim();
if (short) return short;
const full = fullDesc?.trim() ?? "";
if (isCompactUnitLabel(full)) return full;
const unitCode = code?.trim() ?? "";
if (isCompactUnitLabel(unitCode)) return unitCode;
return "";
}

function normUnitKey(...parts: Array<string | null | undefined>): string {
return parts.map((p) => p?.trim().toLowerCase()).find((p) => p) ?? "";
}

/** Prefer UoM short desc (箱). Do not return long packing strings like 150克X100包X1箱. */
export function purchaseUomShortDesc(uom: PurchaseUomLike): string {
return compactUomLabel(uom?.udfShortDesc, uom?.udfudesc, uom?.code);
}

export function stockUomShortLabel(stockUom: StockUomLike): string {
return compactUomLabel(
stockUom?.stockUomShortDesc,
stockUom?.stockUomDesc,
stockUom?.stockUomCode,
);
}

export function purchaseUnitDiffersFromStock(
uom: PurchaseUomLike,
stockUom: StockUomLike,
): boolean {
const purchaseKey = normUnitKey(uom?.code, uom?.udfShortDesc, uom?.udfudesc);
const stockKey = normUnitKey(
stockUom?.stockUomCode,
stockUom?.stockUomShortDesc,
stockUom?.stockUomDesc,
);
if (!purchaseKey || !stockKey) return false;
return purchaseKey !== stockKey;
}

export function poLineNeedsStockQtyConversion(
orderQty: number,
orderStockQty: number,
uom: PurchaseUomLike,
stockUom: StockUomLike,
): boolean {
if (purchaseUnitDiffersFromStock(uom, stockUom)) return true;
return (
Number.isFinite(orderQty) &&
Number.isFinite(orderStockQty) &&
orderQty > 0 &&
orderStockQty > 0 &&
Math.abs(orderStockQty - orderQty) > 1e-6
);
}

/** e.g. 384箱 */
export function formatQtyWithPurchaseUom(qty: number, uom: PurchaseUomLike): string {
const n = integerFormatter.format(qty);
const unit = purchaseUomShortDesc(uom);
return unit ? `${n}${unit}` : n;
}

/** e.g. 57,600克 */
export function formatQtyWithStockUom(qty: number, stockUom: StockUomLike): string {
const rounded = Math.round(qty);
const n =
Number.isFinite(qty) && Math.abs(qty - rounded) < 1e-9
? integerFormatter.format(rounded)
: decimalFormatter.format(qty);
const unit = stockUomShortLabel(stockUom) || stockUom?.stockUomDesc?.trim() || "";
return unit ? `${n}${unit}` : n;
}

+ 85
- 5
src/components/PoDetail/stockQtyRound.ts Целия файл

@@ -7,16 +7,96 @@ export type StockQtyRoundChoice = {
after: number;
};

/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.4 | 2026-09-10 */
/** Keep in sync with ItemUomService.isIntegerCountStockUom */
const INTEGER_COUNT_UNIT_TOKENS = new Set([
"包",
"箱",
"件",
"個",
"PCS",
"PC",
"CTN",
"EA",
"PK",
"PKT",
"BOX",
]);

export type PoStockQtyConvertHint = {
sourceRatioN?: number | null;
sourceRatioD?: number | null;
stockRatioN?: number | null;
stockRatioD?: number | null;
purchaseRatioN?: number | null;
purchaseRatioD?: number | null;
stockUomCode?: string | null;
stockUomShortDesc?: string | null;
stockQtyInteger?: boolean | null;
};

function toRatio(value: number | null | undefined): number | null {
const n = Number(value);
if (!Number.isFinite(n) || n === 0) return null;
return n;
}

function stockQtyMustBeInteger(hint?: PoStockQtyConvertHint): boolean {
if (hint?.stockQtyInteger === true) return true;
if (hint?.stockQtyInteger === false) return false;
const code = hint?.stockUomCode?.trim() ?? "";
if (code.toUpperCase().startsWith("PCS/CTN")) return true;
const short = hint?.stockUomShortDesc?.trim() ?? "";
return INTEGER_COUNT_UNIT_TOKENS.has(short) || INTEGER_COUNT_UNIT_TOKENS.has(code.toUpperCase());
}

/** Java BigDecimal HALF_UP for non-negative qty. */
function roundHalfUp(value: number, scale: number): number {
const factor = 10 ** scale;
return Math.round(value * factor) / factor;
}

function finalizePoStockQty(raw: number, hint?: PoStockQtyConvertHint): number {
if (!Number.isFinite(raw)) return 0;
return stockQtyMustBeInteger(hint) ? roundHalfUp(raw, 0) : roundHalfUp(raw, 2);
}

/**
* Same ratio path as backend convertQtyToStockQtyPrecise:
* base = qty * sourceRatioN / sourceRatioD
* stock = base * stockRatioD / stockRatioN
*/
function convertPoBatchToStockQty(
batchM18Qty: number,
hint?: PoStockQtyConvertHint,
): number | null {
if (!hint || !Number.isFinite(batchM18Qty)) return null;
const sourceN = toRatio(hint.sourceRatioN) ?? toRatio(hint.purchaseRatioN);
const sourceD = toRatio(hint.sourceRatioD) ?? toRatio(hint.purchaseRatioD);
const stockN = toRatio(hint.stockRatioN);
const stockD = toRatio(hint.stockRatioD);
if (sourceN == null || sourceD == null || stockN == null || stockD == null) return null;
const baseQty = (batchM18Qty * sourceN) / sourceD;
const stockQty = (baseQty * stockD) / stockN;
return finalizePoStockQty(stockQty, hint);
}

/**
* FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18
* Preview converted stock qty for a 來貨數 batch.
* Matches create-stock-in: ratio convert, then integer HALF_UP for 包/箱/PCS, else 2 decimals.
*/
export function previewPoBatchStockQty(
orderM18Qty: number,
orderStockQty: number,
batchM18Qty: number,
hint?: PoStockQtyConvertHint,
): number {
const fromRatios = convertPoBatchToStockQty(batchM18Qty, hint);
if (fromRatios != null) return fromRatios;
if (!Number.isFinite(orderM18Qty) || orderM18Qty === 0) {
return Number(batchM18Qty.toFixed(2));
return finalizePoStockQty(batchM18Qty, hint);
}
return Number(((batchM18Qty * orderStockQty) / orderM18Qty).toFixed(2));
return finalizePoStockQty((batchM18Qty * orderStockQty) / orderM18Qty, hint);
}

export function isNotIntegerQty(qty: number): boolean {
@@ -25,7 +105,7 @@ export function isNotIntegerQty(qty: number): boolean {
}

/**
* FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.4 | 2026-09-10
* FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18
* PO 收貨/品檢:pending 或 escalated 且庫存數量非整數時需選擇 CEILING / FLOOR
*/
export function needsPoQcStockQtyRound(
@@ -39,7 +119,7 @@ export function needsPoQcStockQtyRound(
return isNotIntegerQty(Number(acceptedQty ?? 0));
}

/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.4 | 2026-09-10 */
/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18 */
export function roundStockQty(before: number, mode: StockQtyRoundMode): number {
if (mode === "CEILING") return Math.ceil(before);
return Math.floor(before);


+ 37
- 75
src/components/PoSearch/PoSearch.tsx Целия файл

@@ -49,16 +49,25 @@ const PoSearch: React.FC<Props> = ({
const searchCriteria: Criterion<SearchParamNames>[] = [
{ label: t("Supplier"), paramName: "supplier", type: "text" },
{ label: t("PO No."), paramName: "code", type: "text" },
{ label: t("Item Code"), paramName: "itemCode", type: "text" },
{ label: t("Item Name"), paramName: "itemName", type: "text" },
{
label: t("Escalated"),
paramName: "escalated",
type: "select-labelled",
advanced: true,
options: [
{ label: t("Escalated"), value: "true" },
{ label: t("NotEscalated"), value: "false" },
],
},
{ label: t("Order Date"), label2: t("Order Date To"), paramName: "orderDate", type: "dateRange" },
{
label: t("Order Date"),
label2: t("Order Date To"),
paramName: "orderDate",
type: "dateRange",
advanced: true,
},
{
label: t("Status"),
paramName: "status",
@@ -294,98 +303,47 @@ const PoSearch: React.FC<Props> = ({
if (typeof v === "string" && (v as string).trim() === "") return;
cleanedQuery[k] = String(v);
});
try {
const baseListResp = await clientAuthFetch(
`${NEXT_PUBLIC_API_URL}/po/list?${new URLSearchParams(cleanedQuery).toString()}`,
{ method: "GET" },
);
if (!baseListResp.ok) {
throw new Error(`PO list fetch failed: ${baseListResp.status}`);
}
const res = await baseListResp.json();
if (!res) return;

if (res.records && res.records.length > 0) {
setFilteredPo(res.records);
setTotalCount(res.total);
return;
}

const searchedCodeRaw = (filterArgs as any)?.code;
const searchedCode =
typeof searchedCodeRaw === "string" ? searchedCodeRaw.trim() : "";

const shouldAutoSyncFromM18 =
const isM18PoCode =
searchedCode.length > 14 &&
(searchedCode.startsWith("PP") || searchedCode.startsWith("PF"));

if (!shouldAutoSyncFromM18 || autoSyncInProgressRef.current) {
setFilteredPo(res.records);
setTotalCount(res.total);
return;
if (isM18PoCode) {
cleanedQuery.refreshFromM18 = "true";
setIsM18LookupLoading(true);
setAutoSyncStatus("載入中...");
}

try {
autoSyncInProgressRef.current = true;
setIsM18LookupLoading(true);
setAutoSyncStatus("正在從M18找尋PO...");
const syncResp = await clientAuthFetch(
`${NEXT_PUBLIC_API_URL}/m18/test/po-by-code?code=${encodeURIComponent(
searchedCode,
)}`,
const baseListResp = await clientAuthFetch(
`${NEXT_PUBLIC_API_URL}/po/list?${new URLSearchParams(cleanedQuery).toString()}`,
{ method: "GET" },
);

if (!syncResp.ok) {
throw new Error(`M18 sync failed: ${syncResp.status}`);
}

let syncJson: any = null;
try {
syncJson = await syncResp.json();
} catch {
// Some endpoints may respond with plain text
const txt = await syncResp.text();
syncJson = { raw: txt };
if (!baseListResp.ok) {
throw new Error(`PO list fetch failed: ${baseListResp.status}`);
}
const res = await baseListResp.json();
if (!res) return;

const syncOk = Boolean(syncJson?.totalSuccess && syncJson.totalSuccess > 0);
if (syncOk) {
setAutoSyncStatus("成功找到PO");

const listResp = await clientAuthFetch(
`${NEXT_PUBLIC_API_URL}/po/list?${new URLSearchParams(
cleanedQuery,
).toString()}`,
{ method: "GET" },
);
if (listResp.ok) {
const listJson = await listResp.json();
setFilteredPo(listJson.records ?? []);
setTotalCount(listJson.total ?? 0);
setAutoSyncStatus("成功找到PO");
return;
const records: PoResult[] = res.records ?? [];
setFilteredPo(records);
setTotalCount(res.total ?? 0);
if (isM18PoCode) {
const refreshAction = baseListResp.headers.get("X-M18-Po-Refresh");
if (refreshAction === "synced") {
setAutoSyncStatus(records.length > 0 ? "已從M18同步PO" : "找不到PO");
} else {
setAutoSyncStatus(null);
}
setAutoSyncStatus("找不到PO");
} else {
setAutoSyncStatus("找不到PO");
}

// Ensure UI updates even if sync didn't change results
setFilteredPo(res.records);
setTotalCount(res.total ?? 0);
} catch (e) {
console.error("Auto sync error:", e);
setAutoSyncStatus("找不到PO");
setFilteredPo(res.records);
setTotalCount(res.total ?? 0);
console.error("PO list fetch error:", e);
if (isM18PoCode) setAutoSyncStatus("找不到PO");
} finally {
setIsM18LookupLoading(false);
autoSyncInProgressRef.current = false;
}
} catch (e) {
console.error("PO list fetch error:", e);
}
},
[],
);
@@ -425,6 +383,8 @@ const PoSearch: React.FC<Props> = ({
setFilterArgs({
code: query.code,
supplier: query.supplier,
itemCode: query.itemCode,
itemName: query.itemName,
status: query.status === "All" ? "" : query.status,
escalated:
query.escalated === "All"
@@ -481,7 +441,9 @@ const PoSearch: React.FC<Props> = ({
sx={{ color: "#fff", zIndex: (theme) => theme.zIndex.modal + 1, flexDirection: "column", gap: 1 }}
>
<CircularProgress color="inherit" />
<Typography variant="body1">正在從M18找尋PO...</Typography>
<Typography variant="body1">
{autoSyncStatus || "載入中..."}
</Typography>
</Backdrop>
</>
</>


+ 4
- 3
src/components/Qc/QcComponent.tsx Целия файл

@@ -544,9 +544,10 @@ useEffect(() => {
<RadioGroup
row
aria-labelledby="demo-radio-buttons-group-label"
{...field}
value={field.value}
// value={field.value?.toString() || "true"}
name={field.name}
ref={field.ref}
onBlur={field.onBlur}
value={field.value == null ? "" : String(field.value)}
onChange={(e) => {
const value = e.target.value.toString();// === 'true';



+ 51
- 4
src/components/Qc/QcStockInModal.tsx Целия файл

@@ -4,8 +4,10 @@ import {
Box,
Button,
Divider,
Fab,
Grid,
Modal,
Tooltip,
ModalProps,
Stack,
Tab,
@@ -24,6 +26,7 @@ import PutAwayForm from "../PoDetail/PutAwayForm";
import { GridRowModes, GridRowSelectionModel, useGridApiRef } from "@mui/x-data-grid";
import {msg, submitDialogWithWarning} from "../Swal/CustomAlerts";
import { needsPoQcStockQtyRound } from "../PoDetail/stockQtyRound";
import { mapPutAwayLinesFromOriginSil } from "../PoDetail/originSilPutAwayQty";
import { INPUT_DATE_FORMAT, arrayToDateString, dayjsToDateTimeString } from "@/app/utils/formatUtil";
import dayjs from "dayjs";
import { fetchPoQrcode } from "@/app/api/pdf/actions";
@@ -46,6 +49,7 @@ import LoadingComponent from "../General/LoadingComponent";
import { printFGStockInLabel, PrintFGStockInLabelRequest, fetchFGStockInLabel } from "@/app/api/jo/actions";
import { fetchItemForPutAway } from "@/app/api/stockIn/actions";
import { fetchWarehouseListClient } from "@/app/api/warehouse/client";
import Check from "@mui/icons-material/Check";
const style = {
position: "absolute",
top: "50%",
@@ -73,7 +77,7 @@ interface Props extends CommonProps {
// itemDetail: StockInLine & { qcResult?: PurchaseQcResult[] } & { escResult?: EscalationResult[] };
}

/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.4 | 2026-09-10 */
/** FP-MTMS Version Checklist | Functions Ref. No. 56 | v1.0.5 | 2026-09-18 */
const QcStockInModal: React.FC<Props> = ({
open,
onClose,
@@ -231,7 +235,7 @@ const QcStockInModal: React.FC<Props> = ({
// escResult: (d.escResult && d.escResult?.length > 0) ? d.escResult : [],
// qcResult: (d.qcResult && d.qcResult?.length > 0) ? d.qcResult : [],//[...dummyQCData],
warehouseId: d.defaultWarehouseId ?? 1141,
putAwayLines: d.putAwayLines?.map((line) => ({...line, printQty: 1, _isNew: false, _disableDelete: true})) ?? [],
putAwayLines: mapPutAwayLinesFromOriginSil(d, d.putAwayLines),
} as ModalFormInput
)
} return undefined
@@ -311,6 +315,37 @@ const QcStockInModal: React.FC<Props> = ({
return true;
}, [stockInLineInfo])

/** PO stock-in only: mark every editable QC row 合格 and select 接受來貨. */
const showMarkAllQcOk =
!viewOnly &&
!showPutaway &&
skipQc === false &&
stockInLineInfo?.jobOrderId == null;

const markAllQcOkAndAccept = useCallback(() => {
const current = formProps.getValues("qcResult") ?? [];
formProps.setValue(
"qcResult",
current.map((item) =>
item.escalationLogId != null
? item
: { ...item, qcPassed: true, failQty: 0 },
),
{ shouldDirty: true, shouldValidate: true },
);
formProps.setValue("qcAccept", true, { shouldDirty: true });
// RadioGroup compares with === against value="1" (接受來貨).
formProps.setValue("qcDecision", "1" as unknown as number, {
shouldDirty: true,
shouldValidate: true,
});
const acceptQty = formProps.getValues("acceptQty");
const input = document.getElementById("accQty") as HTMLInputElement | null;
if (input && acceptQty != null && !Number.isNaN(Number(acceptQty))) {
input.value = Number(acceptQty).toString();
}
}, [formProps]);

const [openPutaway, setOpenPutaway] = useState(false);
const onOpenPutaway = useCallback(() => {
@@ -842,13 +877,25 @@ const printQrcode = useCallback(
denseLayout={useDenseQcLayout}
/>)
}
<Stack direction="row" justifyContent="flex-end" gap={1} sx={{pt:2}}>
<Stack direction="row" justifyContent="flex-end" alignItems="center" gap={1} sx={{ pt: 2 }}>
{showMarkAllQcOk && (
<Tooltip title={t("Mark all QC OK and accept")}>
<Fab
color="success"
size="medium"
aria-label={t("Mark all QC OK and accept")}
onClick={markAllQcOkAndAccept}
disabled={isSubmitting || isLoading}
>
<Check />
</Fab>
</Tooltip>
)}
{(!viewOnly && !showPutaway) && (<Button
id="Submit"
type="button"
variant="contained"
color="primary"
sx={{ mt: 1 }}
onClick={formProps.handleSubmit(onSubmitQc, onSubmitErrorQc)}
disabled={isSubmitting || isLoading || roundChoiceRequired}
>


+ 19
- 2
src/components/SearchBox/SearchBox.tsx Целия файл

@@ -15,6 +15,8 @@ import CardActions from "@mui/material/CardActions";
import Button from "@mui/material/Button";
import RestartAlt from "@mui/icons-material/RestartAlt";
import Search from "@mui/icons-material/Search";
import ExpandMore from "@mui/icons-material/ExpandMore";
import ExpandLess from "@mui/icons-material/ExpandLess";
import dayjs, { Dayjs } from "dayjs";
import "dayjs/locale/zh-hk";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
@@ -45,6 +47,8 @@ interface BaseCriterion<T extends string> {
preFilledValue?: string | { from?: string; to?: string };
filterObj?: T;
handleSelectionChange?: (selectedOptions: T[]) => void;
/** Hidden until the user clicks more criteria. */
advanced?: boolean;
}

interface OptionWithLabel<T extends string> {
@@ -130,7 +134,7 @@ interface Props<T extends string> {
disabled?: boolean;
}

/** FP-MTMS Version Checklist | Functions Ref. No. 79 | v1.0.0 | 2026-09-10 */
/** FP-MTMS Version Checklist | Functions Ref. No. 79 | v1.0.1 | 2026-09-21 */
function SearchBox<T extends string>({
criteria,
onSearch,
@@ -204,6 +208,9 @@ function SearchBox<T extends string>({

const [inputs, setInputs] = useState(preFilledInputs);
const [isReset, setIsReset] = useState(false);
const [showAdvanced, setShowAdvanced] = useState(false);
const hasAdvanced = criteria.some((c) => c.advanced);
const visibleCriteria = showAdvanced ? criteria : criteria.filter((c) => !c.advanced);

const makeInputChangeHandler = useCallback(
(paramName: T): React.ChangeEventHandler<HTMLInputElement> => {
@@ -301,7 +308,7 @@ function SearchBox<T extends string>({
</Typography>
{extraCriteria}
<Grid container spacing={2} columns={{ xs: 6, sm: 12 }}>
{criteria.map((c) => {
{visibleCriteria.map((c) => {
return (
<Grid key={c.paramName} item xs={6}>
{c.type === "text" && (
@@ -619,6 +626,16 @@ function SearchBox<T extends string>({
>
{t("Search")}
</Button>
{hasAdvanced && (
<Button
variant="text"
startIcon={showAdvanced ? <ExpandLess /> : <ExpandMore />}
onClick={() => setShowAdvanced((open) => !open)}
disabled={disabled}
>
{showAdvanced ? t("Fewer criteria") : t("More criteria")}
</Button>
)}
{extraActions}
</CardActions>
</CardContent>


+ 265
- 184
src/components/StockLedgerFix/StockLedgerFixPageClient.tsx
Файловите разлики са ограничени, защото са твърде много
Целия файл


+ 42
- 5
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<ApproverStockTakeProps> = ({
onSnackbar,
}) => {
const { t } = useTranslation(["stockTake", "common"]);
const qtyGapWarnPercent = useStockTakeQtyGapWarnPercent();
const { data: session } = useSession() as { data: SessionWithTokens | null };

const [inventoryLotDetails, setInventoryLotDetails] = useState<InventoryLotDetailResponse[]>([]);
@@ -61,6 +66,7 @@ const ApproverStockTake: React.FC<ApproverStockTakeProps> = ({
// 每个记录的选择状态,key 为 detail.id
const [qtySelection, setQtySelection] = useState<Record<number, QtySelectionType>>({});
const [approverQty, setApproverQty] = useState<Record<number, string>>({});
const [gapCheckOpen, setGapCheckOpen] = useState<Record<string, boolean>>({});
const [approverBadQty, setApproverBadQty] = useState<Record<number, string>>({});
const [saving, setSaving] = useState(false);
const [batchSaving, setBatchSaving] = useState(false);
@@ -255,7 +261,19 @@ const ApproverStockTake: React.FC<ApproverStockTakeProps> = ({
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<ApproverStockTakeProps> = ({
} 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<ApproverStockTakeProps> = ({
)}
{hasSecond && (
<>
<Stack direction="row" spacing={1} alignItems="center">
<Radio
size="small"
@@ -598,17 +617,28 @@ const ApproverStockTake: React.FC<ApproverStockTakeProps> = ({
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"}
/>
<TextField
@@ -631,6 +661,13 @@ const ApproverStockTake: React.FC<ApproverStockTakeProps> = ({
= {formatNumber(parseFloat(approverQty[detail.id] || "0") - parseFloat(approverBadQty[detail.id] || "0"))}
</Typography>
</Stack>
<StockTakeQtyGapHint
open={!!gapCheckOpen[`${detail.id}:approver`]}
entered={approverQty[detail.id] || ""}
currentQty={stockTakeHiddenOnHand(detail)}
threshold={qtyGapWarnPercent}
/>
</>
)}
{(() => {


+ 65
- 21
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<ApproverStockTakeAllProps> = ({
onSnackbar,
}) => {
const { t } = useTranslation(["stockTake", "common"]);
const qtyGapWarnPercent = useStockTakeQtyGapWarnPercent();
const { data: session } = useSession() as { data: SessionWithTokens | null };

const [inventoryLotDetails, setInventoryLotDetails] = useState<InventoryLotDetailResponse[]>([]);
@@ -235,6 +240,7 @@ const ApproverStockTakeAll: React.FC<ApproverStockTakeAllProps> = ({
const [searchVarianceFilterStrict, setSearchVarianceFilterStrict] = useState(false);
const [qtySelection, setQtySelection] = useState<Record<number, QtySelectionType>>({});
const [approverQty, setApproverQty] = useState<Record<number, string>>({});
const [gapCheckOpen, setGapCheckOpen] = useState<Record<string, boolean>>({});
const [approverBadQty, setApproverBadQty] = useState<Record<number, string>>({});
const [saving, setSaving] = useState(false);
const [batchSaving, setBatchSaving] = useState(false);
@@ -654,7 +660,19 @@ const ApproverStockTakeAll: React.FC<ApproverStockTakeAllProps> = ({
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<ApproverStockTakeAllProps> = ({
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<ApproverStockTakeAllProps> = ({
flex: 1,
sortable: false,
renderCell: (params) => (
<Stack spacing={0.5} sx={{ lineHeight: 1.5 }}>
<Box>
<Stack spacing={0.5} sx={{ lineHeight: 1.5, py: 0.5 }}>
<Typography
component="div"
sx={{ fontWeight: 800, fontSize: "1.15rem", lineHeight: 1.3, color: "text.primary" }}
>
{params.row.itemCode || "-"} {params.row.itemName || "-"}
</Box>
</Typography>
<Box>{params.row.lotNo || "-"}</Box>
<Box>
{params.row.expiryDate
@@ -1052,12 +1073,12 @@ const ApproverStockTakeAll: React.FC<ApproverStockTakeAllProps> = ({
/>
<Typography variant="body2" component="span">
{t("First")}:{" "}
{formatNumber(
(detail.firstStockTakeQty ?? 0) + (detail.firstBadQty ?? 0)
)}{" "}
{/*
= {formatNumber(detail.firstStockTakeQty ?? 0)}
*/}
<StockTakeQtyWithUnit
qty={formatNumber(
(detail.firstStockTakeQty ?? 0) + (detail.firstBadQty ?? 0)
)}
uomShortDesc={detail.uomShortDesc}
/>
</Typography>
</Stack>
)}
@@ -1077,12 +1098,12 @@ const ApproverStockTakeAll: React.FC<ApproverStockTakeAllProps> = ({
/>
<Typography variant="body2" component="span">
{t("Second")}:{" "}
{formatNumber(
(detail.secondStockTakeQty ?? 0) + (detail.secondBadQty ?? 0)
)}{" "}
{/*
= {formatNumber(detail.secondStockTakeQty ?? 0)}
*/}
<StockTakeQtyWithUnit
qty={formatNumber(
(detail.secondStockTakeQty ?? 0) + (detail.secondBadQty ?? 0)
)}
uomShortDesc={detail.uomShortDesc}
/>
</Typography>
</Stack>
@@ -1108,6 +1129,18 @@ const ApproverStockTakeAll: React.FC<ApproverStockTakeAllProps> = ({
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<ApproverStockTakeAllProps> = ({
[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]*" }}
/>
<Box sx={{ flexBasis: "100%" }}>
<StockTakeQtyGapHint
open={selection === "approver" && !!gapCheckOpen[`${detail.id}:approver`]}
entered={approverQty[detail.id] || ""}
currentQty={stockTakeHiddenOnHand(detail)}
threshold={qtyGapWarnPercent}
/>
</Box>
{/*
<Typography variant="body2" component="span" sx={{ ml: 0.5 }}>
= {formatNumber(approverGoodQty)}
@@ -1152,7 +1196,7 @@ const ApproverStockTakeAll: React.FC<ApproverStockTakeAllProps> = ({
<Stack spacing={0.75}>
{summaryLine(
`${t("Selected Qty")}:`,
formatNumber(selectedQty)
[formatNumber(selectedQty), detail.uomShortDesc?.trim()].filter(Boolean).join(" ")
)}
{summaryLine(`${t("Book Qty")}:`, formatNumber(bookQty))}
{summaryLine(


+ 75
- 24
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<PickerReStockTakeProps> = ({
onSnackbar,
}) => {
const { t } = useTranslation(["stockTake", "common"]);
const qtyGapWarnPercent = useStockTakeQtyGapWarnPercent();
const { data: session } = useSession() as { data: SessionWithTokens | null };

const [inventoryLotDetails, setInventoryLotDetails] = useState<InventoryLotDetailResponse[]>([]);
@@ -65,6 +70,7 @@ const PickerReStockTake: React.FC<PickerReStockTakeProps> = ({
remark: string;
}>>({});
const [saving, setSaving] = useState(false);
const [gapCheckOpen, setGapCheckOpen] = useState<Record<string, boolean>>({});
const [batchSaving, setBatchSaving] = useState(false);
const [shortcutInput, setShortcutInput] = useState<string>("");
const [page, setPage] = useState(0);
@@ -246,7 +252,19 @@ const PickerReStockTake: React.FC<PickerReStockTakeProps> = ({
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<PickerReStockTakeProps> = ({
} 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<PickerReStockTakeProps> = ({
<TableCell>{t("Warehouse Location")}</TableCell>
<TableCell>{t("Item-lotNo-ExpiryDate")}</TableCell>
<TableCell>{t("UOM")}</TableCell>
<TableCell>{t("Stock Take Qty(include Bad Qty)= Available Qty")}</TableCell>
<TableCell sx={{ width: 250, minWidth: 250 }}>{t("Stock Take Qty(include Bad Qty)= Available Qty")}</TableCell>
<TableCell>{t("Action")}</TableCell>
{/*<TableCell>{t("Remark")}</TableCell>*/}
<TableCell>{t("Record Status")}</TableCell>
@@ -520,28 +538,40 @@ const PickerReStockTake: React.FC<PickerReStockTakeProps> = ({
<TableRow key={detail.id}>
<TableCell>{detail.warehouseArea || "-"}{detail.warehouseSlot || "-"}</TableCell>
<TableCell sx={{
maxWidth: 150,
maxWidth: 280,
wordBreak: 'break-word',
whiteSpace: 'normal',
lineHeight: 1.5
}}>
<Stack spacing={0.5}>
<Box>{detail.itemCode || "-"} {detail.itemName || "-"}</Box>
<Typography
component="div"
sx={{ fontWeight: 800, fontSize: "1.15rem", lineHeight: 1.3, color: "text.primary" }}
>
{detail.itemCode || "-"} {detail.itemName || "-"}
</Typography>
<Box>{detail.lotNo || "-"}</Box>
<Box>{detail.expiryDate ? dayjs(detail.expiryDate).format(OUTPUT_DATE_FORMAT) : "-"}</Box>
</Stack>
</TableCell>
<TableCell>{detail.uom || "-"}</TableCell>
<TableCell sx={{ minWidth: 300 }}>
<TableCell sx={{ width: 250, minWidth: 250 }}>
<Stack spacing={1}>
{/* First */}
{!submitDisabled && isFirstSubmit ? (
<Stack spacing={0.5} alignItems="flex-start">
<Stack direction="row" spacing={1} alignItems="center">
<Typography variant="body2">{t("First")}:</Typography>
<TextField
size="small"
type="number"
value={inputs.firstQty}
onFocus={() =>
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<PickerReStockTakeProps> = ({
[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<PickerReStockTakeProps> = ({
placeholder={t("Bad Qty")}
/>
*/}
<Typography variant="body2">
= {formatNumber(parseFloat(inputs.firstQty || "0") - parseFloat(inputs.firstBadQty || "0"))}
</Typography>
</Stack>
<StockTakeQtyGapHint
open={!!gapCheckOpen[`${detail.id}:first`]}
entered={inputs.firstQty}
currentQty={stockTakeHiddenOnHand(detail)}
threshold={qtyGapWarnPercent}
/>
</Stack>
) : detail.firstStockTakeQty != null ? (
<Typography variant="body2">
{t("First")}:{" "}
{formatNumber((detail.firstStockTakeQty ?? 0) + (detail.firstBadQty ?? 0))}{" "}
{/* ({formatNumber(detail.firstBadQty ?? 0)}) */}
={" "}
{formatNumber(detail.firstStockTakeQty ?? 0)}
<StockTakeQtyWithUnit
qty={formatNumber(detail.firstStockTakeQty ?? 0)}
uomShortDesc={detail.uomShortDesc}
/>
</Typography>
) : null}

{/* Second */}
{!submitDisabled && isSecondSubmit ? (
<Stack spacing={0.5} alignItems="flex-start">
<Stack direction="row" spacing={1} alignItems="center">
<Typography variant="body2">{t("Second")}:</Typography>
<TextField
size="small"
type="number"
value={inputs.secondQty}
onFocus={() =>
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<PickerReStockTakeProps> = ({
[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<PickerReStockTakeProps> = ({
placeholder={t("Bad Qty")}
/>
*/}
<Typography variant="body2">
= {formatNumber(parseFloat(inputs.secondQty || "0") - parseFloat(inputs.secondBadQty || "0"))}
</Typography>
</Stack>
<StockTakeQtyGapHint
open={!!gapCheckOpen[`${detail.id}:second`]}
entered={inputs.secondQty}
currentQty={stockTakeHiddenOnHand(detail)}
threshold={qtyGapWarnPercent}
/>
</Stack>
) : detail.secondStockTakeQty != null ? (
<Typography variant="body2">
{t("Second")}:{" "}
{formatNumber((detail.secondStockTakeQty ?? 0) + (detail.secondBadQty ?? 0))}{" "}
{/* ({formatNumber(detail.secondBadQty ?? 0)}) */}
={" "}
{formatNumber(detail.secondStockTakeQty ?? 0)}
<StockTakeQtyWithUnit
qty={formatNumber(detail.secondStockTakeQty ?? 0)}
uomShortDesc={detail.uomShortDesc}
/>
</Typography>
) : null}



+ 187
- 62
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<PickerStockTakeProps> = ({
onSnackbar,
}) => {
const { t } = useTranslation(["stockTake", "common"]);
const qtyGapWarnPercent = useStockTakeQtyGapWarnPercent();
const { data: session } = useSession() as { data: SessionWithTokens | null };

const [inventoryLotDetails, setInventoryLotDetails] = useState<InventoryLotDetailResponse[]>([]);
@@ -72,7 +77,11 @@ const PickerStockTake: React.FC<PickerStockTakeProps> = ({
const [savingRecordId, setSavingRecordId] = useState<number | null>(null);
const [remark, setRemark] = useState<string>("");
const [saving, setSaving] = useState(false);
/** Qty fields the user has left, or just saved. Warning stays hidden while typing. */
const [gapCheckOpen, setGapCheckOpen] = useState<Record<string, boolean>>({});
const [batchSaving, setBatchSaving] = useState(false);
/** 已盤點列:按「更改」後才打開數量欄,再按「保存」。 */
const [editingFirstIds, setEditingFirstIds] = useState<Record<number, boolean>>({});
const [shortcutInput, setShortcutInput] = useState<string>("");
const [page, setPage] = useState(0);
const [pageSize, setPageSize] = useState<number | string>("all");
@@ -83,6 +92,7 @@ const PickerStockTake: React.FC<PickerStockTakeProps> = ({
const currentUserId = session?.id ? parseInt(session.id) : undefined;
const handleBatchTestAllRef = useRef<() => Promise<void>>();
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<PickerStockTakeProps> = ({
});
};

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<PickerStockTakeProps> = ({
return;
}

saveInFlightRef.current = true;
setSaving(true);
try {
const request: SaveStockTakeRecordRequest = {
@@ -233,6 +271,7 @@ const PickerStockTake: React.FC<PickerStockTakeProps> = ({
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<PickerStockTakeProps> = ({

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<PickerStockTakeProps> = ({
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<PickerStockTakeProps> = ({
onSnackbar(errorMessage, "error");
} finally {
setSaving(false);
saveInFlightRef.current = false;
}
},
[
@@ -286,6 +342,8 @@ const PickerStockTake: React.FC<PickerStockTakeProps> = ({
t,
currentUserId,
onSnackbar,
qtyGapWarnPercent,
canReviseFirstCount,
]
);

@@ -540,7 +598,7 @@ const PickerStockTake: React.FC<PickerStockTakeProps> = ({
<TableCell>{t("Warehouse Location")}</TableCell>
<TableCell>{t("Item-lotNo-ExpiryDate")}</TableCell>
<TableCell>{t("UOM")}</TableCell>
<TableCell>{t("Stock Take Qty(include Bad Qty)= Available Qty")}</TableCell>
<TableCell sx={{ width: 250, minWidth: 250 }}>{t("Stock Take Qty(include Bad Qty)= Available Qty")}</TableCell>
<TableCell>{t("Action")}</TableCell>
{/*<TableCell>{t("Remark")}</TableCell>*/}
<TableCell>{t("Record Status")}</TableCell>
@@ -559,10 +617,28 @@ const PickerStockTake: React.FC<PickerStockTakeProps> = ({
) : (
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 (
<TableRow key={detail.id}>
@@ -572,16 +648,19 @@ const PickerStockTake: React.FC<PickerStockTakeProps> = ({
</TableCell>
<TableCell
sx={{
maxWidth: 150,
maxWidth: 280,
wordBreak: "break-word",
whiteSpace: "normal",
lineHeight: 1.5,
}}
>
<Stack spacing={0.5}>
<Box>
<Typography
component="div"
sx={{ fontWeight: 800, fontSize: "1.15rem", lineHeight: 1.3, color: "text.primary" }}
>
{detail.itemCode || "-"} {detail.itemName || "-"}
</Box>
</Typography>
<Box>{detail.lotNo || "-"}</Box>
<Box>
{detail.expiryDate
@@ -592,16 +671,23 @@ const PickerStockTake: React.FC<PickerStockTakeProps> = ({
</TableCell>
<TableCell>{detail.uom || "-"}</TableCell>
{/* Qty + Bad Qty 合并显示/输入 */}
<TableCell sx={{ minWidth: 300 }}>
<TableCell sx={{ width: 250, minWidth: 250 }}>
<Stack spacing={1}>
{/* First */}
{!submitDisabled && isFirstSubmit ? (
{showFirstInput ? (
<Stack spacing={0.5} alignItems="flex-start">
<Stack direction="row" spacing={1} alignItems="center">
<Typography variant="body2">{t("First")}:</Typography>
<TextField
size="small"
type="number"
value={recordInputs[detail.id]?.firstQty || ""}
onFocus={() =>
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<PickerStockTakeProps> = ({
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<PickerStockTakeProps> = ({
placeholder={t("Bad Qty")}
/>
*/}
</Stack>
<StockTakeQtyGapHint
open={!!gapCheckOpen[`${detail.id}:first`]}
entered={recordInputs[detail.id]?.firstQty || ""}
currentQty={stockTakeHiddenOnHand(detail)}
threshold={qtyGapWarnPercent}
/>
</Stack>
) : detail.firstStockTakeQty != null ? (
<Stack spacing={0.5} alignItems="flex-start">
<Typography variant="body2">
=
{formatNumber(
parseFloat(recordInputs[detail.id]?.firstQty || "0") -
parseFloat(recordInputs[detail.id]?.firstBadQty || "0")
)}
{t("First")}:{" "}
<StockTakeQtyWithUnit
qty={formatNumber(detail.firstStockTakeQty ?? 0)}
uomShortDesc={detail.uomShortDesc}
/>
</Typography>
<StockTakeQtyGapHint
open
entered={String(Math.trunc(Number(detail.firstStockTakeQty)))}
currentQty={stockTakeHiddenOnHand(detail)}
threshold={qtyGapWarnPercent}
/>
</Stack>
) : detail.firstStockTakeQty != null ? (
<Typography variant="body2">
{t("First")}:{" "}
{formatNumber(
(detail.firstStockTakeQty ?? 0) +
(detail.firstBadQty ?? 0)
)}{" "}
{/*
(
{formatNumber(
detail.firstBadQty ?? 0
)}
*/}
={" "}
{formatNumber(detail.firstStockTakeQty ?? 0)}
</Typography>
) : null}

{/* Second */}
{!submitDisabled && isSecondSubmit ? (
<Stack spacing={0.5} alignItems="flex-start">
<Stack direction="row" spacing={1} alignItems="center">
<Typography variant="body2">{t("Second")}:</Typography>
<TextField
size="small"
type="number"
value={recordInputs[detail.id]?.secondQty || ""}
onFocus={() =>
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<PickerStockTakeProps> = ({
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<PickerStockTakeProps> = ({
placeholder={t("Bad Qty")}
/>
*/}
</Stack>
<StockTakeQtyGapHint
open={!!gapCheckOpen[`${detail.id}:second`]}
entered={recordInputs[detail.id]?.secondQty || ""}
currentQty={stockTakeHiddenOnHand(detail)}
threshold={qtyGapWarnPercent}
/>
</Stack>
) : detail.secondStockTakeQty != null ? (
<Stack spacing={0.5} alignItems="flex-start">
<Typography variant="body2">
=
{formatNumber(
parseFloat(recordInputs[detail.id]?.secondQty || "0") -
parseFloat(recordInputs[detail.id]?.secondBadQty || "0")
)}
{t("Second")}:{" "}
<StockTakeQtyWithUnit
qty={formatNumber(detail.secondStockTakeQty ?? 0)}
uomShortDesc={detail.uomShortDesc}
/>
</Typography>
<StockTakeQtyGapHint
open
entered={String(Math.trunc(Number(detail.secondStockTakeQty)))}
currentQty={stockTakeHiddenOnHand(detail)}
threshold={qtyGapWarnPercent}
/>
</Stack>
) : detail.secondStockTakeQty != null ? (
<Typography variant="body2">
{t("Second")}:{" "}
{formatNumber(
(detail.secondStockTakeQty ?? 0) +
(detail.secondBadQty ?? 0)
)}{" "}
{/*
(
{formatNumber(
detail.secondBadQty ?? 0
)}
*/}
={" "}
{formatNumber(detail.secondStockTakeQty ?? 0)}
</Typography>
) : null}

{!detail.firstStockTakeQty &&
@@ -772,13 +871,39 @@ const PickerStockTake: React.FC<PickerStockTakeProps> = ({
<Button
size="small"
variant="contained"
onClick={() => handleSaveStockTake(detail)}
disabled={saving || submitDisabled}
color={showChangeButton ? "warning" : "primary"}
onClick={() => {
if (changeUsedUp) return;
if (revisingFirst && !editingFirst) {
if ((detail.pickerReviseCount ?? 0) === 1) {
onSnackbar(t("oneChangeLeft"), "warning");
}
setEditingFirstIds((prev) => ({ ...prev, [detail.id]: true }));
return;
}
handleSaveStockTake(detail);
}}
disabled={
saving ||
batchSaving ||
changeUsedUp ||
(submitDisabled && !revisingFirst) ||
(editingFirst && !firstQtyChanged)
}
>
{t("Save")}
{showChangeButton ? t("Change") : t("Save")}
</Button>
</Stack>
{oneChanceLeft && (
<Typography
variant="caption"
component="div"
role="status"
sx={{ color: "warning.dark", fontWeight: 700, mt: 0.5, maxWidth: 140, lineHeight: 1.35 }}
>
{t("oneChangeLeft")}
</Typography>
)}
</TableCell>
{/* Remark */}


+ 40
- 0
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 (
<Typography
variant="caption"
component="div"
role="status"
sx={{
color: "warning.dark",
fontWeight: 700,
lineHeight: 1.35,
maxWidth: 420,
}}
>
{text}
</Typography>
);
}

+ 100
- 6
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<AllPickedStockTakeListReponse | null>(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 = () => {
<Snackbar
open={snackbar.open}
autoHideDuration={6000}
onClose={() => setSnackbar({ ...snackbar, open: false })}
onClose={(_event, reason) => {
if (reason === "clickaway") return;
setSnackbar((prev) => ({ ...prev, open: false }));
}}
>
<Alert onClose={() => setSnackbar({ ...snackbar, open: false })} severity={snackbar.severity}>
<Alert
onClose={() => setSnackbar((prev) => ({ ...prev, open: false }))}
severity={snackbar.severity}
>
{snackbar.message}
</Alert>
</Snackbar>
@@ -115,6 +163,46 @@ const StockTakeTab: React.FC = () => {

return (
<Box>
{isAdmin && (
<Stack direction="row" spacing={1} alignItems="center" sx={{ mb: 1 }}>
<Typography
component="label"
htmlFor="stock-take-qty-gap-warn"
sx={{ m: 0, height: 40, fontSize: 18, fontWeight: 500, lineHeight: "40px" }}
>
{t("qtyGapWarnPercent")}
</Typography>
<TextField
id="stock-take-qty-gap-warn"
size="small"
type="number"
value={qtyGapDraft}
onChange={(e) => 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",
},
}}
/>
<Button
size="small"
variant="outlined"
disabled={qtyGapSaving}
onClick={saveQtyGapWarnPercent}
sx={{ height: 40 }}
>
{t("Save")}
</Button>
</Stack>
)}
<Tabs
value={tabValue}
onChange={(e, newValue) => {
@@ -186,9 +274,15 @@ const StockTakeTab: React.FC = () => {
<Snackbar
open={snackbar.open}
autoHideDuration={6000}
onClose={() => setSnackbar({ ...snackbar, open: false })}
onClose={(_event, reason) => {
if (reason === "clickaway") return;
setSnackbar((prev) => ({ ...prev, open: false }));
}}
>
<Alert onClose={() => setSnackbar({ ...snackbar, open: false })} severity={snackbar.severity}>
<Alert
onClose={() => setSnackbar((prev) => ({ ...prev, open: false }))}
severity={snackbar.severity}
>
{snackbar.message}
</Alert>
</Snackbar>


+ 49
- 0
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<number> {
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<void> {
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 }));
}

+ 55
- 0
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 (
<InputAdornment position="end" sx={{ ml: 0.25, mr: 0.25, maxHeight: "none" }}>
<Typography
component="span"
sx={{
fontWeight: 800,
fontSize: "1.05rem",
color: "primary.main",
lineHeight: 1,
}}
>
{label}
</Typography>
</InputAdornment>
);
}

/** 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 ? (
<Typography
component="span"
sx={{
fontWeight: 800,
fontSize: "1.05rem",
color: "primary.main",
lineHeight: 1,
ml: 0.5,
}}
>
{unit}
</Typography>
) : null}
</>
);
}

+ 62
- 0
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, unknown>) => 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,
});
}

+ 33
- 0
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<number>).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;
}

+ 59
- 32
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<object>();
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<HTMLDivElement>(null);
@@ -162,18 +190,11 @@ export default function SafeApexCharts(props: SafeApexChartsProps) {
sanitized = alignSeriesToCategoryCount(sanitized, cats.length);
}

if (shouldShowPlaceholder(type, options, sanitized, allowZeroSeries)) {
return (
<Typography color="text.secondary" sx={{ py: 3 }}>
{EMPTY_MESSAGE}
</Typography>
);
}

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 (
<Typography color="text.secondary" sx={{ py: 3 }}>
{EMPTY_MESSAGE}
</Typography>
);
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 (
<Typography color="text.secondary" sx={{ py: 3 }}>
{EMPTY_MESSAGE}
</Typography>
);
}

return (
<Box
ref={containerRef}


+ 3
- 2
src/config/api.ts Целия файл

@@ -1,3 +1,4 @@
export const BASE_API_URL = `${process.env.API_URL}`;
export const BASE_API_URL = `${process.env.API_URL || process.env.NEXT_PUBLIC_API_URL || ""}`;
export const LOGIN_API_PATH = `${BASE_API_URL}/login`;
export const NEXT_PUBLIC_API_URL = `${process.env.NEXT_PUBLIC_API_URL}`;
export const REFRESH_TOKEN_API_PATH = `${BASE_API_URL}/refresh-token`;
export const NEXT_PUBLIC_API_URL = `${process.env.NEXT_PUBLIC_API_URL || process.env.API_URL || ""}`;

+ 113
- 8
src/config/authConfig.ts Целия файл

@@ -1,8 +1,80 @@
// config/authConfig.ts (or wherever your authOptions live)
import { AuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { LOGIN_API_PATH } from "./api";
import { LOGIN_API_PATH, REFRESH_TOKEN_API_PATH } from "./api";
import { Session } from "next-auth";
import { JWT } from "next-auth/jwt";

/** Refresh access token this many ms before backend JWT `exp`. */
const ACCESS_TOKEN_REFRESH_SKEW_MS = 5 * 60 * 1000;
/** After a failed refresh, wait this long before trying again (avoids spam on session polls). */
const REFRESH_FAILURE_COOLDOWN_MS = 60 * 1000;

function backendAccessTokenExpiresAtMs(accessToken: string | null | undefined): number | null {
if (!accessToken) return null;
try {
const parts = accessToken.split(".");
if (parts.length < 2) return null;
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
const json = Buffer.from(padded, "base64").toString("utf8");
const payload = JSON.parse(json) as { exp?: number };
return typeof payload.exp === "number" ? payload.exp * 1000 : null;
} catch {
return null;
}
}

async function refreshAccessToken(token: JWT): Promise<JWT> {
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) {


+ 22
- 0
src/config/reportConfig.ts Целия файл

@@ -25,6 +25,10 @@ export interface ReportField {
minDate?: 'today';
/** Disable the input (e.g. date locked to today) */
disabled?: boolean;
/** Render a multiline text area (for pasting many values) */
multiline?: boolean;
/** Rows for multiline text areas. Default 4. */
minRows?: number;
}

export type ReportResponseType = 'pdf' | 'excel';
@@ -53,6 +57,15 @@ const asyncItemCodeField = (
placeholder: "e.g. FA0591",
});

const pasteItemCodeField = (): ReportField => ({
label: "貼上貨品編號 Paste Item Codes",
name: "itemCodePaste",
type: "text",
required: false,
multiline: true,
minRows: 4,
});

export const REPORTS: ReportDefinition[] = [
//{
// id: "rep-001",
@@ -105,6 +118,7 @@ export const REPORTS: ReportDefinition[] = [
{ label: "入倉日期:由 Last In Date Start", name: "lastInDateStart", type: "date", required: false },
{ label: "入倉日期:至 Last In Date End", name: "lastInDateEnd", type: "date", required: false },
asyncItemCodeField(),
pasteItemCodeField(),
{
label: "樓層 Store ID",
name: "storeId",
@@ -144,6 +158,7 @@ export const REPORTS: ReportDefinition[] = [
{ label: "出貨日期:至 Last Out Date End", name: "lastOutDateEnd", type: "date", required: false },
{ label: "年份 Year", name: "year", type: "text", required: false, placeholder: "e.g. 2026" },
asyncItemCodeField(),
pasteItemCodeField(),
]
},
/*
@@ -298,6 +313,7 @@ export const REPORTS: ReportDefinition[] = [
{ label: "庫存日期:由 Last In Date Start", name: "lastInDateStart", type: "date", required: false },
{ label: "庫存日期:至 Last In Date End", name: "lastInDateEnd", type: "date", required: false },
asyncItemCodeField(),
pasteItemCodeField(),
]
},
{
@@ -338,6 +354,7 @@ export const REPORTS: ReportDefinition[] = [
fields: [
{ label: "庫存日期: Stock Date", name: "stockDate", type: "date", required: true },
asyncItemCodeField(),
pasteItemCodeField(),
]
},
@@ -351,6 +368,7 @@ export const REPORTS: ReportDefinition[] = [
{ label: "收貨日期:由 Receipt Date Start", name: "receiptDateStart", type: "date", required: false },
{ label: "收貨日期:至 Receipt Date End", name: "receiptDateEnd", type: "date", required: false },
asyncItemCodeField(),
pasteItemCodeField(),
],
},
@@ -403,6 +421,7 @@ export const REPORTS: ReportDefinition[] = [
{ label: "出倉日期:由 Last Out Date Start", name: "lastOutDateStart", type: "date", required: false },
{ label: "出倉日期:至 Last Out Date End", name: "lastOutDateEnd", type: "date", required: false },
asyncItemCodeField(),
pasteItemCodeField(),
{ label: "提料人 Handler", name: "handler", type: "select", required: false,
multiple: true,
dynamicOptions: true,
@@ -435,6 +454,7 @@ export const REPORTS: ReportDefinition[] = [
dynamicOptionsEndpoint: `${NEXT_PUBLIC_API_URL}/report/stock-item-code-prefixes`,
dynamicOptionsParam: "stockCategory",
options: [] },
pasteItemCodeField(),
]
},

@@ -461,6 +481,7 @@ export const REPORTS: ReportDefinition[] = [
dynamicOptionsEndpoint: `${NEXT_PUBLIC_API_URL}/report/semi-fg-item-codes`,
dynamicOptionsParam: "stockCategory",
options: [] },
pasteItemCodeField(),
]
},
{
@@ -472,6 +493,7 @@ export const REPORTS: ReportDefinition[] = [
{ label: "同步日期:由 Sync Date Start", name: "syncDateStart", type: "date", required: false },
{ label: "同步日期:至 Sync Date End", name: "syncDateEnd", type: "date", required: false },
asyncItemCodeField("成品貨號 Finished Item Code", "finishedItemCode"),
pasteItemCodeField(),
{
label: "同步狀態 Sync Status",
name: "syncStatus",


+ 112
- 110
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"
}

+ 43
- 1
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."
}

+ 2
- 0
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",


+ 103
- 9
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"
}

+ 3
- 0
src/i18n/en/purchaseOrder.json Целия файл

@@ -126,6 +126,8 @@
"Please scan warehouse qr code.": "Please scan warehouse QR code.",
"receivedQty": "Received Qty",
"dnQty": "Delivery Qty (This Batch)",
"dnQtyOrderUnitHint": "in order unit",
"stockQtyRef": "Stock",
"Accept submit": "Accept Delivery",
"qc processing": "Delivery & QC Processing",
"putaway processing": "Delivery & Put Away Processing",
@@ -143,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",


+ 48
- 6
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",
@@ -52,6 +58,7 @@
"lastInDateStart": "Last In Date Start",
"lastInDateEnd": "Last In Date End",
"itemCode": "Item Code",
"itemCodePaste": "Paste Item Codes",
"storeId": "Floor",
"warehouse": "Warehouse",
"area": "Area",
@@ -68,6 +75,9 @@
"PP": "PP",
"PF": "PF"
}
},
"fieldHints": {
"itemCodePaste": "Paste item codes from Excel. Separate with spaces, commas, or new lines"
}
},
"rep-008": {
@@ -76,7 +86,11 @@
"lastOutDateStart": "Last Out Date Start",
"lastOutDateEnd": "Last Out Date End",
"year": "Year",
"itemCode": "Item Code"
"itemCode": "Item Code",
"itemCodePaste": "Paste Item Codes"
},
"fieldHints": {
"itemCodePaste": "Paste item codes from Excel. Separate with spaces, commas, or new lines"
}
},
"rep-012": {
@@ -115,7 +129,11 @@
"fields": {
"lastInDateStart": "Stock Date Start",
"lastInDateEnd": "Stock Date End",
"itemCode": "Item Code"
"itemCode": "Item Code",
"itemCodePaste": "Paste Item Codes"
},
"fieldHints": {
"itemCodePaste": "Paste item codes from Excel. Separate with spaces, commas, or new lines"
}
},
"rep-020": {
@@ -130,7 +148,11 @@
"title": "Stock Balance Report",
"fields": {
"stockDate": "Stock Date",
"itemCode": "Item Code"
"itemCode": "Item Code",
"itemCodePaste": "Paste Item Codes"
},
"fieldHints": {
"itemCodePaste": "Paste item codes from Excel. Separate with spaces, commas, or new lines"
}
},
"rep-014": {
@@ -138,7 +160,11 @@
"fields": {
"receiptDateStart": "Receipt Date Start",
"receiptDateEnd": "Receipt Date End",
"itemCode": "Item Code"
"itemCode": "Item Code",
"itemCodePaste": "Paste Item Codes"
},
"fieldHints": {
"itemCodePaste": "Paste item codes from Excel. Separate with spaces, commas, or new lines"
}
},
"rep-009": {
@@ -177,7 +203,11 @@
"lastOutDateStart": "Last Out Date Start",
"lastOutDateEnd": "Last Out Date End",
"itemCode": "Item Code",
"itemCodePaste": "Paste Item Codes",
"handler": "Handler"
},
"fieldHints": {
"itemCodePaste": "Paste item codes from Excel. Separate with spaces, commas, or new lines"
}
},
"rep-006": {
@@ -187,7 +217,11 @@
"lastOutDateEnd": "Consumption Date End",
"year": "Year",
"stockCategory": "Category",
"itemCode": "Item Code"
"itemCode": "Item Code",
"itemCodePaste": "Paste Item Codes"
},
"fieldHints": {
"itemCodePaste": "Paste item codes from Excel. Separate with spaces, commas, or new lines"
}
},
"rep-005": {
@@ -197,7 +231,11 @@
"lastOutDateEnd": "Production Complete Date End",
"year": "Year",
"stockCategory": "Category",
"itemCode": "Item Code"
"itemCode": "Item Code",
"itemCodePaste": "Paste Item Codes"
},
"fieldHints": {
"itemCodePaste": "Paste item codes from Excel. Separate with spaces, commas, or new lines"
}
},
"rep-015": {
@@ -206,8 +244,12 @@
"syncDateStart": "Sync Date Start",
"syncDateEnd": "Sync Date End",
"finishedItemCode": "Finished Item Code",
"itemCodePaste": "Paste Item Codes",
"syncStatus": "Sync Status"
},
"fieldHints": {
"itemCodePaste": "Paste item codes from Excel. Separate with spaces, commas, or new lines"
},
"options": {
"syncStatus": {
"all": "All",


+ 155
- 0
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}}, 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)"
}
}

+ 8
- 1
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"


+ 3
- 3
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",


+ 2
- 0
src/i18n/zh/common.json Целия файл

@@ -86,6 +86,8 @@
"Save": "儲存",
"Saving": "儲存中",
"Search": "搜索",
"More criteria": "更多條件",
"Fewer criteria": "收起條件",
"Search Criteria": "搜索條件",
"Select Date": "選擇日期",
"Session expired or unauthorized.": "工作階段已過期或未經授權。",


+ 38
- 1
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 送貨路線摘要失敗,請稍後再試。"
}

+ 2
- 0
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 品檢模板",


+ 99
- 2
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 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": "全部"
}

+ 3
- 0
src/i18n/zh/purchaseOrder.json Целия файл

@@ -126,6 +126,8 @@
"Please scan warehouse qr code.": "請掃描倉庫 QR 碼。",
"receivedQty": "已來貨數量",
"dnQty": "本批來貨數量",
"dnQtyOrderUnitHint": "以訂單單位計算",
"stockQtyRef": "庫存",
"Accept submit": "接受來貨",
"qc processing": "處理來貨及品檢",
"putaway processing": "處理來貨及上架",
@@ -143,6 +145,7 @@
"email supplier": "電郵供應商",
"confirm putaway": "確定及完成上架",
"confirm qc result": "確定品檢結果",
"Mark all QC OK and accept": "全部合格並接受",
"warehouse": "倉庫",
"qcItem": "品檢項目",
"passed": "接受",


+ 48
- 6
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": "物料編號及名稱",
@@ -52,6 +58,7 @@
"lastInDateStart": "入倉日期:由",
"lastInDateEnd": "入倉日期:至",
"itemCode": "貨品編號",
"itemCodePaste": "貼上貨品編號",
"storeId": "樓層",
"warehouse": "倉庫",
"area": "區域",
@@ -68,6 +75,9 @@
"PP": "PP",
"PF": "PF"
}
},
"fieldHints": {
"itemCodePaste": "可從 Excel 貼上多個貨品編號,以空格、逗號或換行分隔"
}
},
"rep-008": {
@@ -76,7 +86,11 @@
"lastOutDateStart": "出貨日期:由",
"lastOutDateEnd": "出貨日期:至",
"year": "年份",
"itemCode": "貨品編號"
"itemCode": "貨品編號",
"itemCodePaste": "貼上貨品編號"
},
"fieldHints": {
"itemCodePaste": "可從 Excel 貼上多個貨品編號,以空格、逗號或換行分隔"
}
},
"rep-012": {
@@ -115,7 +129,11 @@
"fields": {
"lastInDateStart": "庫存日期:由",
"lastInDateEnd": "庫存日期:至",
"itemCode": "貨品編號"
"itemCode": "貨品編號",
"itemCodePaste": "貼上貨品編號"
},
"fieldHints": {
"itemCodePaste": "可從 Excel 貼上多個貨品編號,以空格、逗號或換行分隔"
}
},
"rep-020": {
@@ -130,7 +148,11 @@
"title": "庫存結餘報告",
"fields": {
"stockDate": "庫存日期",
"itemCode": "貨品編號"
"itemCode": "貨品編號",
"itemCodePaste": "貼上貨品編號"
},
"fieldHints": {
"itemCodePaste": "可從 Excel 貼上多個貨品編號,以空格、逗號或換行分隔"
}
},
"rep-014": {
@@ -138,7 +160,11 @@
"fields": {
"receiptDateStart": "收貨日期:由",
"receiptDateEnd": "收貨日期:至",
"itemCode": "貨品編號"
"itemCode": "貨品編號",
"itemCodePaste": "貼上貨品編號"
},
"fieldHints": {
"itemCodePaste": "可從 Excel 貼上多個貨品編號,以空格、逗號或換行分隔"
}
},
"rep-009": {
@@ -177,7 +203,11 @@
"lastOutDateStart": "出倉日期:由",
"lastOutDateEnd": "出倉日期:至",
"itemCode": "貨品編號",
"itemCodePaste": "貼上貨品編號",
"handler": "提料人"
},
"fieldHints": {
"itemCodePaste": "可從 Excel 貼上多個貨品編號,以空格、逗號或換行分隔"
}
},
"rep-006": {
@@ -187,7 +217,11 @@
"lastOutDateEnd": "材料消耗日期:至",
"year": "年份",
"stockCategory": "類別",
"itemCode": "貨品編號"
"itemCode": "貨品編號",
"itemCodePaste": "貼上貨品編號"
},
"fieldHints": {
"itemCodePaste": "可從 Excel 貼上多個貨品編號,以空格、逗號或換行分隔"
}
},
"rep-005": {
@@ -197,7 +231,11 @@
"lastOutDateEnd": "完成生產日期:至",
"year": "年份",
"stockCategory": "類別",
"itemCode": "貨品編號"
"itemCode": "貨品編號",
"itemCodePaste": "貼上貨品編號"
},
"fieldHints": {
"itemCodePaste": "可從 Excel 貼上多個貨品編號,以空格、逗號或換行分隔"
}
},
"rep-015": {
@@ -206,8 +244,12 @@
"syncDateStart": "同步日期:由",
"syncDateEnd": "同步日期:至",
"finishedItemCode": "成品貨號",
"itemCodePaste": "貼上貨品編號",
"syncStatus": "同步狀態"
},
"fieldHints": {
"itemCodePaste": "可從 Excel 貼上多個貨品編號,以空格、逗號或換行分隔"
},
"options": {
"syncStatus": {
"all": "全部",


+ 155
- 0
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}}、重算 {{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(真超發/帳不一致)"
}
}

+ 8
- 1
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": "帳面庫存",


+ 28
- 10
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") };
}

Зареждане…
Отказ
Запис