feat: add material trace page for bidirectional LOT/material query
Some checks failed
full-modernization-gates / frontend-route-governance (push) Has been cancelled
full-modernization-gates / backend-modernization-gates (push) Has been cancelled
released-pages-hardening-gates / released-pages-hardening (push) Has been cancelled

Implement full-stack material trace feature enabling forward (LOT/工單 → 原物料)
and reverse (原物料 → LOT) queries with wildcard support, safeguards (memory guard,
IN-clause batching, Oracle slow-query channel), CSV export, and portal-shell integration.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
egg
2026-03-03 17:32:41 +08:00
parent a275c30c0e
commit 777751311c
27 changed files with 2899 additions and 1 deletions

View File

@@ -0,0 +1,438 @@
<script setup>
import { computed, onMounted, ref } from 'vue';
import { apiGet, apiPost } from '../core/api.js';
import { parseMultiLineInput } from '../core/reject-history-filters.js';
const API_TIMEOUT = 60000;
const DEFAULT_PER_PAGE = 50;
const FORWARD_INPUT_LIMIT = 200;
const REVERSE_INPUT_LIMIT = 50;
// ---- Query mode state ----
const queryMode = ref('forward'); // 'forward' | 'reverse'
const forwardInputType = ref('lot'); // 'lot' | 'workorder'
const inputText = ref('');
// ---- Filter state ----
const workcenterGroupOptions = ref([]);
const selectedWorkcenterGroups = ref([]);
const workcenterDropdownOpen = ref(false);
const workcenterSearch = ref('');
// ---- Result state ----
const rows = ref([]);
const pagination = ref({ page: 1, per_page: DEFAULT_PER_PAGE, total: 0, total_pages: 0 });
const loading = ref(false);
const errorMessage = ref('');
const warningMessage = ref('');
const unresolvedWarning = ref('');
// ---- Computed ----
const parsedValues = computed(() => parseMultiLineInput(inputText.value));
const inputCount = computed(() => parsedValues.value.length);
const currentInputLimit = computed(() =>
queryMode.value === 'forward' ? FORWARD_INPUT_LIMIT : REVERSE_INPUT_LIMIT,
);
const isOverLimit = computed(() => inputCount.value > currentInputLimit.value);
const hasResults = computed(() => rows.value.length > 0);
const canQuery = computed(() => inputCount.value > 0 && !isOverLimit.value && !loading.value);
const canExport = computed(() => hasResults.value && !loading.value);
const queryModeForApi = computed(() => {
if (queryMode.value === 'reverse') return 'material_lot';
return forwardInputType.value; // 'lot' or 'workorder'
});
const filteredWorkcenterOptions = computed(() => {
const q = workcenterSearch.value.toLowerCase().trim();
if (!q) return workcenterGroupOptions.value;
return workcenterGroupOptions.value.filter((g) => g.toLowerCase().includes(q));
});
const workcenterTriggerText = computed(() => {
if (selectedWorkcenterGroups.value.length === 0) return '全部站點';
if (selectedWorkcenterGroups.value.length === 1) return selectedWorkcenterGroups.value[0];
return `已選 ${selectedWorkcenterGroups.value.length} 個站群組`;
});
// ---- Table columns ----
const TABLE_COLUMNS = [
{ key: 'CONTAINERNAME', label: 'LOT ID' },
{ key: 'PJ_WORKORDER', label: '工單' },
{ key: 'WORKCENTER_GROUP', label: '站群組' },
{ key: 'WORKCENTERNAME', label: '站點' },
{ key: 'MATERIALPARTNAME', label: '料號' },
{ key: 'MATERIALLOTNAME', label: '物料批號' },
{ key: 'VENDORLOTNUMBER', label: '供應商批號' },
{ key: 'QTYREQUIRED', label: '應領量' },
{ key: 'QTYCONSUMED', label: '實際消耗' },
{ key: 'EQUIPMENTNAME', label: '機台' },
{ key: 'TXNDATE', label: '交易日期' },
{ key: 'PRIMARY_CATEGORY', label: '主分類' },
{ key: 'SECONDARY_CATEGORY', label: '副分類' },
];
// ---- Mode switching ----
function switchQueryMode(mode) {
if (queryMode.value === mode) return;
queryMode.value = mode;
clearAll();
}
function switchForwardInputType(type) {
if (forwardInputType.value === type) return;
forwardInputType.value = type;
inputText.value = '';
clearResults();
}
function clearAll() {
inputText.value = '';
clearResults();
}
function clearResults() {
rows.value = [];
pagination.value = { page: 1, per_page: DEFAULT_PER_PAGE, total: 0, total_pages: 0 };
errorMessage.value = '';
warningMessage.value = '';
unresolvedWarning.value = '';
}
// ---- Workcenter multi-select ----
function toggleWorkcenterGroup(group) {
const idx = selectedWorkcenterGroups.value.indexOf(group);
if (idx >= 0) {
selectedWorkcenterGroups.value.splice(idx, 1);
} else {
selectedWorkcenterGroups.value.push(group);
}
}
function selectAllWorkcenterGroups() {
selectedWorkcenterGroups.value = [...workcenterGroupOptions.value];
}
function clearWorkcenterGroups() {
selectedWorkcenterGroups.value = [];
}
// ---- API calls ----
async function loadFilterOptions() {
try {
const res = await apiGet('/api/material-trace/filter-options', { timeout: API_TIMEOUT });
if (res.success && res.data?.workcenter_groups) {
workcenterGroupOptions.value = res.data.workcenter_groups;
}
} catch {
// Silently ignore — filter options will be empty
}
}
async function executePrimaryQuery(page = 1) {
if (!canQuery.value) return;
errorMessage.value = '';
warningMessage.value = '';
unresolvedWarning.value = '';
loading.value = true;
const body = {
mode: queryModeForApi.value,
values: parsedValues.value,
page,
per_page: DEFAULT_PER_PAGE,
};
if (selectedWorkcenterGroups.value.length > 0) {
body.workcenter_groups = selectedWorkcenterGroups.value;
}
try {
const result = await apiPost('/api/material-trace/query', body, { timeout: API_TIMEOUT });
if (!result.success) {
errorMessage.value = result.error || '查詢失敗';
rows.value = [];
pagination.value = { page: 1, per_page: DEFAULT_PER_PAGE, total: 0, total_pages: 0 };
return;
}
rows.value = result.rows || [];
pagination.value = result.pagination || {
page: 1,
per_page: DEFAULT_PER_PAGE,
total: 0,
total_pages: 0,
};
// Handle meta warnings
if (result.meta?.unresolved?.length > 0) {
unresolvedWarning.value = `以下 LOT ID 無法解析:${result.meta.unresolved.join('、')}`;
}
if (result.meta?.truncated) {
warningMessage.value = `查詢結果超過 ${result.meta.max_rows?.toLocaleString() || '10,000'} 筆上限,請縮小查詢範圍`;
}
} catch (err) {
errorMessage.value = err.message || '查詢失敗,請稍後再試';
rows.value = [];
} finally {
loading.value = false;
}
}
function goToPage(page) {
executePrimaryQuery(page);
}
async function exportCsv() {
if (!canExport.value) return;
const body = {
mode: queryModeForApi.value,
values: parsedValues.value,
};
if (selectedWorkcenterGroups.value.length > 0) {
body.workcenter_groups = selectedWorkcenterGroups.value;
}
try {
const response = await fetch('/api/material-trace/export', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
errorMessage.value = data.error || '匯出失敗';
return;
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'material_trace.csv';
a.click();
URL.revokeObjectURL(url);
} catch (err) {
errorMessage.value = err.message || '匯出失敗,請稍後再試';
}
}
// ---- Lifecycle ----
onMounted(() => {
loadFilterOptions();
});
// Close dropdown on click outside
function onDocumentClick(e) {
if (!e.target.closest('.multi-select')) {
workcenterDropdownOpen.value = false;
}
}
</script>
<template>
<div class="dashboard" @click="onDocumentClick">
<!-- Header -->
<div class="header material-trace-header">
<div class="header-left">
<h1>原物料追溯查詢</h1>
</div>
</div>
<!-- Error / Warning Banners -->
<div v-if="errorMessage" class="error-banner">{{ errorMessage }}</div>
<div v-if="unresolvedWarning" class="warning-banner">{{ unresolvedWarning }}</div>
<div v-if="warningMessage" class="warning-banner">{{ warningMessage }}</div>
<!-- Query Card -->
<div class="card">
<div class="card-header">
<span class="card-title">查詢條件</span>
</div>
<div class="card-body">
<!-- Mode tabs -->
<div class="mode-tab-row" style="margin-bottom: 14px">
<button
class="mode-tab"
:class="{ active: queryMode === 'forward' }"
@click="switchQueryMode('forward')"
>
正向查詢LOT/工單 原物料
</button>
<button
class="mode-tab"
:class="{ active: queryMode === 'reverse' }"
@click="switchQueryMode('reverse')"
>
反向查詢原物料 LOT
</button>
</div>
<div class="filter-panel">
<!-- Forward: input type selector -->
<div v-if="queryMode === 'forward'" class="filter-group">
<label class="filter-label">輸入類型</label>
<div class="input-type-row">
<select
class="filter-input input-type-select"
:value="forwardInputType"
@change="switchForwardInputType($event.target.value)"
>
<option value="lot">LOT ID</option>
<option value="workorder">工單</option>
</select>
</div>
</div>
<!-- Workcenter group filter -->
<div class="filter-group">
<label class="filter-label">站群組篩選</label>
<div class="multi-select" @click.stop>
<button
class="multi-select-trigger"
@click="workcenterDropdownOpen = !workcenterDropdownOpen"
>
<span class="multi-select-text">{{ workcenterTriggerText }}</span>
<span class="multi-select-arrow">&#9662;</span>
</button>
<div v-if="workcenterDropdownOpen" class="multi-select-dropdown">
<input
v-model="workcenterSearch"
class="multi-select-search"
placeholder="搜尋站群組..."
/>
<div class="multi-select-options">
<button
v-for="group in filteredWorkcenterOptions"
:key="group"
class="multi-select-option"
@click="toggleWorkcenterGroup(group)"
>
<input
type="checkbox"
:checked="selectedWorkcenterGroups.includes(group)"
tabindex="-1"
/>
{{ group }}
</button>
<div v-if="filteredWorkcenterOptions.length === 0" class="multi-select-empty">
無符合的站群組
</div>
</div>
<div class="multi-select-actions">
<button class="btn-sm" @click="selectAllWorkcenterGroups">全選</button>
<button class="btn-sm" @click="clearWorkcenterGroups">清除</button>
</div>
</div>
</div>
</div>
<!-- Textarea input -->
<div class="filter-group filter-group-full">
<label class="filter-label">
{{
queryMode === 'forward'
? forwardInputType === 'lot'
? 'LOT ID每行一筆或逗號分隔支援萬用字元 * '
: '工單號碼(每行一筆或逗號分隔,支援萬用字元 * '
: '原物料批號(每行一筆或逗號分隔,支援萬用字元 * '
}}
</label>
<textarea
v-model="inputText"
class="filter-input filter-textarea"
rows="5"
:placeholder="
queryMode === 'forward'
? forwardInputType === 'lot'
? 'GA25060001-A01\nGA250605*\n...'
: 'WO-2025-001\nWO-2025*\n...'
: 'WIRE-LOT-20250101-A\nSLD-LOT-2025*\n...'
"
></textarea>
<div class="input-count" :class="{ 'over-limit': isOverLimit }">
已輸入 {{ inputCount }}
<template v-if="isOverLimit">
超過上限 {{ currentInputLimit }}
</template>
</div>
</div>
<!-- Buttons -->
<div class="filter-toolbar">
<div class="filter-actions">
<button class="btn btn-primary" :disabled="!canQuery" @click="executePrimaryQuery()">
<span v-if="loading" class="btn-spinner"></span>
查詢
</button>
<button class="btn btn-secondary" @click="clearAll">清除</button>
<button class="btn btn-export" :disabled="!canExport" @click="exportCsv">
匯出 CSV
</button>
</div>
</div>
</div>
</div>
</div>
<!-- Result Card -->
<div v-if="hasResults || loading" class="card">
<div class="card-header">
<span class="card-title">
查詢結果
<template v-if="pagination.total > 0">
{{ pagination.total.toLocaleString() }}
</template>
</span>
</div>
<div class="card-body">
<!-- Loading overlay -->
<div class="detail-table-wrap" :class="{ 'is-loading': loading }">
<div v-if="loading" class="table-loading-overlay">
<span class="table-spinner"></span>
</div>
<table class="detail-table">
<thead>
<tr>
<th v-for="col in TABLE_COLUMNS" :key="col.key">{{ col.label }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, idx) in rows" :key="idx">
<td v-for="col in TABLE_COLUMNS" :key="col.key">{{ row[col.key] ?? '' }}</td>
</tr>
</tbody>
</table>
</div>
<!-- Empty message -->
<div v-if="!loading && rows.length === 0 && pagination.total === 0" class="empty-message">
查無資料
</div>
<!-- Pagination -->
<div v-if="pagination.total_pages > 1" class="pagination-bar">
<div class="pagination-info">
{{ pagination.page }} / {{ pagination.total_pages }}
{{ pagination.total.toLocaleString() }}
</div>
<div class="pagination-actions">
<button :disabled="pagination.page <= 1" @click="goToPage(pagination.page - 1)">
上一頁
</button>
<button
:disabled="pagination.page >= pagination.total_pages"
@click="goToPage(pagination.page + 1)"
>
下一頁
</button>
</div>
</div>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,12 @@
<!doctype html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>原物料追溯查詢</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="./main.js"></script>
</body>
</html>

View File

@@ -0,0 +1,7 @@
import { createApp } from 'vue';
import App from './App.vue';
import '../wip-shared/styles.css';
import './style.css';
createApp(App).mount('#app');

View File

@@ -0,0 +1,444 @@
.material-trace-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.mode-tab-row {
display: flex;
gap: 0;
border: 1px solid var(--border);
border-radius: 8px;
overflow: hidden;
width: fit-content;
}
.mode-tab {
padding: 7px 16px;
border: none;
background: #f8fafc;
font-size: 13px;
font-weight: 600;
color: #475569;
cursor: pointer;
transition: background 0.15s, color 0.15s;
}
.mode-tab:not(:last-child) {
border-right: 1px solid var(--border);
}
.mode-tab.active {
background: #667eea;
color: #fff;
}
.mode-tab:hover:not(.active) {
background: #eef2f7;
}
.input-type-row {
display: flex;
align-items: center;
gap: 8px;
}
.input-type-select {
width: auto;
min-width: 120px;
max-width: 180px;
padding: 6px 10px;
border: 1px solid var(--border);
border-radius: 8px;
font-size: 13px;
background: #fff;
}
.filter-textarea {
resize: vertical;
font-family: monospace;
line-height: 1.5;
}
.input-count {
font-size: 12px;
color: #64748b;
margin-top: 4px;
}
.input-count.over-limit {
color: #dc2626;
font-weight: 600;
}
.card {
background: var(--card-bg);
border-radius: 10px;
box-shadow: var(--shadow);
overflow: visible;
margin-bottom: 14px;
}
.card-header {
padding: 14px 18px;
border-bottom: 1px solid var(--border);
background: #f8fafc;
border-radius: 10px 10px 0 0;
}
.card-title {
font-size: 15px;
font-weight: 700;
color: #0f172a;
}
.card-body {
padding: 14px 16px;
}
.error-banner {
margin-bottom: 14px;
padding: 10px 12px;
border-radius: 6px;
background: #fef2f2;
color: #991b1b;
font-size: 13px;
}
.warning-banner {
margin-bottom: 14px;
padding: 10px 12px;
border-radius: 6px;
background: #fffbeb;
color: #b45309;
font-size: 13px;
}
.filter-panel {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 14px;
align-items: end;
}
.filter-group {
display: flex;
flex-direction: column;
gap: 8px;
}
.filter-group-full {
grid-column: 1 / -1;
}
.filter-label {
font-size: 12px;
font-weight: 700;
color: #475569;
}
.filter-input {
width: 100%;
padding: 8px 10px;
border: 1px solid var(--border);
border-radius: 8px;
font-size: 13px;
background: #fff;
}
.filter-input:focus {
outline: none;
border-color: #0ea5e9;
box-shadow: 0 0 0 2px rgba(14, 165, 233, 0.18);
}
.filter-toolbar {
grid-column: 1 / -1;
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.filter-actions {
display: flex;
gap: 10px;
flex-shrink: 0;
}
.detail-table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
.detail-table th,
.detail-table td {
border-bottom: 1px solid var(--border);
padding: 8px 10px;
text-align: left;
vertical-align: middle;
white-space: nowrap;
}
.detail-table thead th {
position: sticky;
top: 0;
background: #f8fafc;
z-index: 1;
}
.detail-table tbody tr:hover {
background: #f8fbff;
}
.detail-table-wrap {
position: relative;
overflow: auto;
max-height: 70vh;
}
.detail-table-wrap.is-loading table {
opacity: 0.4;
pointer-events: none;
transition: opacity 0.15s ease;
}
.table-loading-overlay {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
z-index: 2;
}
.table-spinner {
display: block;
width: 28px;
height: 28px;
border: 3px solid #d1d5db;
border-top-color: #667eea;
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
.btn-spinner {
display: inline-block;
width: 12px;
height: 12px;
border: 2px solid rgba(255, 255, 255, 0.4);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.6s linear infinite;
margin-right: 6px;
vertical-align: middle;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.pagination-bar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 0;
font-size: 13px;
color: #475569;
}
.pagination-info {
display: flex;
align-items: center;
gap: 8px;
}
.pagination-actions {
display: flex;
align-items: center;
gap: 8px;
}
.pagination-actions button {
padding: 5px 12px;
border: 1px solid var(--border);
border-radius: 6px;
background: #fff;
color: #334155;
font-size: 13px;
cursor: pointer;
}
.pagination-actions button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.pagination-actions button:hover:not(:disabled) {
background: #f1f5f9;
}
.btn.btn-export {
background: #667eea;
color: #fff;
}
.btn.btn-export:hover {
background: #5568d3;
color: #fff;
}
.btn.btn-export:disabled {
opacity: 0.7;
cursor: not-allowed;
}
.empty-message {
text-align: center;
padding: 40px 20px;
color: #94a3b8;
font-size: 14px;
}
/* Multi-select (copied from reject-history for standalone use) */
.multi-select {
position: relative;
min-width: 160px;
}
.multi-select-trigger {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
border: 1px solid var(--border);
border-radius: 8px;
padding: 8px 10px;
font-size: 13px;
color: #1f2937;
background: #ffffff;
cursor: pointer;
}
.multi-select-trigger:disabled {
cursor: not-allowed;
opacity: 0.7;
}
.multi-select-text {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
text-align: left;
}
.multi-select-arrow {
color: #64748b;
font-size: 11px;
}
.multi-select-dropdown {
position: absolute;
top: calc(100% + 4px);
left: 0;
right: 0;
z-index: 20;
border: 1px solid var(--border);
border-radius: 8px;
background: #ffffff;
box-shadow: 0 12px 24px rgba(15, 23, 42, 0.14);
overflow: hidden;
}
.multi-select-search {
display: block;
width: 100%;
border: none;
border-bottom: 1px solid var(--border);
padding: 8px 12px;
font-size: 13px;
color: #1f2937;
outline: none;
background: #f8fafc;
}
.multi-select-search::placeholder {
color: #94a3b8;
}
.multi-select-options {
max-height: 250px;
overflow-y: auto;
padding: 8px 0;
}
.multi-select-option {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 6px 12px;
border: none;
background: transparent;
font-size: 13px;
color: #334155;
cursor: pointer;
text-align: left;
}
.multi-select-option:hover {
background: #f8fafc;
}
.multi-select-option input[type='checkbox'] {
margin: 0;
width: 14px;
height: 14px;
accent-color: #667eea;
}
.multi-select-empty {
padding: 12px;
text-align: center;
color: #94a3b8;
font-size: 13px;
}
.multi-select-actions {
display: flex;
gap: 8px;
padding: 8px 10px;
border-top: 1px solid var(--border);
background: #f8fafc;
}
.btn-sm {
padding: 4px 10px;
border: 1px solid var(--border);
border-radius: 6px;
background: #f8fafc;
color: var(--text);
cursor: pointer;
font-size: 12px;
}
.btn-sm:hover {
border-color: #c2d0e0;
background: #eef4fb;
}
@media (max-width: 768px) {
.filter-panel {
grid-template-columns: 1fr;
}
.filter-group-full {
grid-column: span 1;
}
.filter-toolbar {
flex-direction: column;
align-items: flex-start;
}
}

View File

@@ -70,6 +70,10 @@ const NATIVE_MODULE_LOADERS = Object.freeze({
() => import('../mid-section-defect/App.vue'),
[() => import('../mid-section-defect/style.css')],
),
'/material-trace': createNativeLoader(
() => import('../material-trace/App.vue'),
[() => import('../wip-shared/styles.css'), () => import('../material-trace/style.css')],
),
'/admin/performance': createNativeLoader(
() => import('../admin-performance/App.vue'),
[() => import('../admin-performance/style.css')],

View File

@@ -13,6 +13,7 @@ const IN_SCOPE_REPORT_ROUTES = Object.freeze([
'/excel-query',
'/query-tool',
'/mid-section-defect',
'/material-trace',
]);
const IN_SCOPE_ADMIN_ROUTES = Object.freeze([
@@ -230,6 +231,17 @@ const ROUTE_CONTRACTS = Object.freeze({
scope: 'in-scope',
compatibilityPolicy: 'redirect_to_shell_when_spa_enabled',
}),
'/material-trace': buildContract({
route: '/material-trace',
routeId: 'material-trace',
renderMode: 'native',
owner: 'frontend-mes-reporting',
title: '原物料追溯查詢',
rollbackStrategy: 'fallback_to_legacy_route',
visibilityPolicy: 'released_or_admin',
scope: 'in-scope',
compatibilityPolicy: 'redirect_to_shell_when_spa_enabled',
}),
});
const REQUIRED_FIELDS = Object.freeze([

View File

@@ -28,7 +28,8 @@ export default defineConfig(({ mode }) => ({
'query-tool': resolve(__dirname, 'src/query-tool/main.js'),
'qc-gate': resolve(__dirname, 'src/qc-gate/index.html'),
'mid-section-defect': resolve(__dirname, 'src/mid-section-defect/index.html'),
'admin-performance': resolve(__dirname, 'src/admin-performance/index.html')
'admin-performance': resolve(__dirname, 'src/admin-performance/index.html'),
'material-trace': resolve(__dirname, 'src/material-trace/index.html')
},
output: {
entryFileNames: '[name].js',