Router.register('/shipments/query', async () => {
// 获取当前用户信息
let userRole = null;
try {
const userRes = await fetch('/api/auth/me', { credentials: 'include' });
const userData = await userRes.json();
userRole = userData.role;
} catch (e) {
console.error('Failed to get user info:', e);
}
setTimeout(async () => {
const queryBtn = document.getElementById('sn-query-btn');
const snInput = document.getElementById('sn-input');
const resultDiv = document.getElementById('query-result');
const statsDiv = document.getElementById('redis-stats');
const clearBtn = document.getElementById('clear-redis-btn');
// 加载统计信息
const loadStats = async () => {
try {
const res = await fetch('/api/shipments/redis-stats', {
credentials: 'include'
});
const data = await res.json();
if (data.count !== undefined) {
statsDiv.innerHTML = `
数据库出货数量:
${data.count}
`;
}
} catch (e) {
statsDiv.innerHTML = '无法获取统计信息
';
}
};
// 初始加载统计
await loadStats();
// 根据用户角色控制清空按钮的显示
if (clearBtn) {
if (userRole !== 'superadmin') {
clearBtn.style.display = 'none';
}
}
const performQuery = async () => {
const sn = snInput?.value?.trim();
if (!sn) {
resultDiv.innerHTML = '请输入 SN/MAC 号
';
return;
}
try {
resultDiv.innerHTML = '查询中...
';
const res = await fetch(`/api/shipments/query-by-sn?sn=${encodeURIComponent(sn)}`, {
credentials: 'include'
});
const data = await res.json();
if (data.found) {
resultDiv.innerHTML = `
✓ 找到出货记录
SN/MAC: ${data.sn}
机种: ${data.platform_name || '未知'}
出货日期: ${data.date}
箱号: ${data.box}
记录时间: ${data.ts}
`;
} else {
resultDiv.innerHTML = `
✗ 未找到记录
SN/MAC: ${data.sn}
${data.message || '该 SN 没有出货记录'}
`;
}
} catch (e) {
resultDiv.innerHTML = `查询失败:${e.message}
`;
}
};
const clearRedis = async () => {
if (!confirm('确定要清空所有发货记录吗?此操作不可恢复!')) {
return;
}
try {
const res = await fetch('/api/shipments/clear-redis', {
method: 'POST',
credentials: 'include'
});
const data = await res.json();
if (data.ok) {
alert(data.message || '清空成功');
await loadStats();
resultDiv.innerHTML = '';
} else {
alert('清空失败:' + (data.error || '未知错误'));
}
} catch (e) {
alert('清空失败:' + e.message);
}
};
queryBtn?.addEventListener('click', performQuery);
// 只有超级管理员才绑定清空按钮事件
if (clearBtn && userRole === 'superadmin') {
clearBtn.addEventListener('click', clearRedis);
}
snInput?.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
performQuery();
}
});
}, 0);
// 根据用户角色决定是否显示清空按钮
const showClearButton = userRole === 'superadmin';
return ``;
});