上传历史记录问题修复

This commit is contained in:
zzh 2025-11-21 22:45:00 +08:00
parent 76067d3c67
commit 3736a4dc9c
3 changed files with 94 additions and 55 deletions

View File

@ -88,8 +88,7 @@ if inserted_count > 0:
'mac': sn_mac,
'batch': batch_no
})
if len(success_records) >= 10: # 只显示前10条
break
# 移除数量限制,输出所有成功导入的记录
print(json.dumps(success_records, ensure_ascii=False))
print("=== 数据输出结束 ===")

View File

@ -61,7 +61,7 @@ const Upload = (() => {
function textarea(id,label,placeholder=''){return `<div class="field"><label>${label}</label><textarea id="${id}" class="input" rows="4" placeholder="${placeholder}"></textarea></div>`}
async function renderMac(){
return section('MAC与批次',`
return section('MAC与批次MAC与批次对应关系表',`
<div class="field">
<label>上传类型</label>
<select id="mac-type" class="input">
@ -160,14 +160,18 @@ const Upload = (() => {
Router.register('/upload/mac', async () => {
const html = await renderMac();
setTimeout(bindMacEvents,0);
setTimeout(()=>{
// 显示历史记录中的最新10条
const history = getHistory();
setTimeout(async ()=>{
// 从服务器获取最新10条记录
const listEl=document.getElementById('mac-list');
if(listEl && history.length > 0){
listEl.innerHTML = history.slice(0, 10).map(r=>`<li><span>${r.mac}</span><span class="badge">${r.batch}</span></li>`).join('');
} else if(listEl) {
listEl.innerHTML = '<li>暂无数据</li>';
try {
const data = await API.listMac();
if(listEl && data.list && data.list.length > 0){
listEl.innerHTML = data.list.slice(0, 10).map(r=>`<li><span>${r.mac}</span><span class="badge">${r.batch}</span></li>`).join('');
} else if(listEl) {
listEl.innerHTML = '<li>暂无数据</li>';
}
} catch(e) {
if(listEl) listEl.innerHTML = '<li>加载失败</li>';
}
},0);
return html;
@ -176,20 +180,16 @@ const Upload = (() => {
Router.register('/upload/stats', async () => {
const html = await renderStats();
setTimeout(bindStatsEvents,0);
setTimeout(()=>{
// 显示历史记录中的最新10条
const STATS_STORAGE_KEY = 'stats_upload_history';
setTimeout(async ()=>{
// 从服务器获取最新10条记录
const listEl=document.getElementById('stats-list');
try {
const history = JSON.parse(localStorage.getItem(STATS_STORAGE_KEY) || '[]');
const listEl=document.getElementById('stats-list');
if(listEl && history.length > 0){
listEl.innerHTML = history.slice(0, 10).map(r=>{
const data = await API.listStats();
if(listEl && data.list && data.list.length > 0){
listEl.innerHTML = data.list.slice(0, 10).map(r=>{
const platformName = {pdd: '拼多多', yt: '圆通', tx: '兔喜'}[r.platform] || '';
const platformText = platformName ? `${platformName} - ` : '';
let html = `<li><span>${platformText}直通良:${r.fpy_good||0} 良:${r.good} 不良:${r.bad}</span>`;
if(r.details && r.details.length > 0){
html += `<span class="badge">${r.details.length}条明细</span>`;
}
html += '</li>';
return html;
}).join('');
@ -198,6 +198,7 @@ const Upload = (() => {
}
} catch(e) {
console.error('加载历史记录失败:', e);
if(listEl) listEl.innerHTML = '<li>加载失败</li>';
}
},0);
return html;
@ -270,17 +271,22 @@ const Upload = (() => {
}
});
// 查看历史按钮
addListener(showHistoryBtn, 'click', ()=>{
const history = getHistory();
// 查看历史按钮 - 从服务器获取所有用户的上传记录
addListener(showHistoryBtn, 'click', async ()=>{
const listEl = document.getElementById('mac-list');
if(listEl){
if(history.length > 0){
listEl.innerHTML = history.map(r=>`<li><span>${r.mac}</span><span class="badge">${r.batch}</span><span style="font-size:11px;color:var(--text-2);margin-left:8px">${new Date(r.timestamp).toLocaleString('zh-CN')}</span></li>`).join('');
API.toast(`显示全部 ${history.length} 条历史记录`);
} else {
listEl.innerHTML = '<li>暂无历史记录</li>';
try {
const data = await API.listMac();
if(listEl){
if(data.list && data.list.length > 0){
listEl.innerHTML = data.list.map(r=>`<li><span>${r.mac}</span><span class="badge">${r.batch}</span><span style="font-size:11px;color:var(--text-2);margin-left:8px">${new Date(r.ts).toLocaleString('zh-CN')}</span></li>`).join('');
API.toast(`显示全部 ${data.list.length} 条历史记录`);
} else {
listEl.innerHTML = '<li>暂无历史记录</li>';
}
}
} catch(e) {
API.toast('加载历史记录失败');
if(listEl) listEl.innerHTML = '<li>加载失败</li>';
}
});
@ -391,26 +397,28 @@ const Upload = (() => {
const showHistoryBtn = document.getElementById('stats-show-history');
const clearDisplayBtn = document.getElementById('stats-clear-display');
// 查看历史按钮
addListener(showHistoryBtn, 'click', ()=>{
const history = getStatsHistory();
// 查看历史按钮 - 从服务器获取所有用户的上传记录
addListener(showHistoryBtn, 'click', async ()=>{
const listEl = document.getElementById('stats-list');
if(listEl){
if(history.length > 0){
listEl.innerHTML = history.map(r=>{
const platformName = {pdd: '拼多多', yt: '圆通', tx: '兔喜'}[r.platform] || '';
const platformText = platformName ? `${platformName} - ` : '';
let html = `<li><span>${platformText}直通良:${r.fpy_good||0} 良:${r.good} 不良:${r.bad}</span>`;
if(r.details && r.details.length > 0){
html += `<span class="badge">${r.details.length}条明细</span>`;
}
html += `<span style="font-size:11px;color:var(--text-2);margin-left:8px">${new Date(r.timestamp).toLocaleString('zh-CN')}</span></li>`;
return html;
}).join('');
API.toast(`显示全部 ${history.length} 条历史记录`);
} else {
listEl.innerHTML = '<li>暂无历史记录</li>';
try {
const data = await API.listStats();
if(listEl){
if(data.list && data.list.length > 0){
listEl.innerHTML = data.list.map(r=>{
const platformName = {pdd: '拼多多', yt: '圆通', tx: '兔喜'}[r.platform] || '';
const platformText = platformName ? `${platformName} - ` : '';
let html = `<li><span>${platformText}直通良:${r.fpy_good||0} 良:${r.good} 不良:${r.bad}</span>`;
html += `<span style="font-size:11px;color:var(--text-2);margin-left:8px">${new Date(r.ts).toLocaleString('zh-CN')}</span></li>`;
return html;
}).join('');
API.toast(`显示全部 ${data.list.length} 条历史记录`);
} else {
listEl.innerHTML = '<li>暂无历史记录</li>';
}
}
} catch(e) {
API.toast('加载历史记录失败');
if(listEl) listEl.innerHTML = '<li>加载失败</li>';
}
});

View File

@ -156,7 +156,7 @@ def log(action, detail=''):
conn = get_db()
c = conn.cursor()
c.execute('INSERT INTO operations_log(user_id, action, detail, ts) VALUES(?,?,?,?)', (
session.get('user_id'), action, detail, datetime.utcnow().isoformat()
session.get('user_id'), action, detail, get_beijing_time()
))
conn.commit()
conn.close()
@ -219,6 +219,12 @@ def get_redis():
_redis_client = redis.Redis(host=host, port=port, password=password, db=db, decode_responses=True, socket_timeout=0.5, socket_connect_timeout=0.5)
return _redis_client
def get_beijing_time():
"""获取北京时间UTC+8的ISO格式字符串"""
from datetime import timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
return datetime.now(beijing_tz).isoformat()
def parse_audit_line(s):
if not s:
return {'ts_cn': None, 'batch': None, 'mac': None, 'note': None}
@ -854,7 +860,7 @@ def upload_mac():
return jsonify({'error': 'invalid rows'}), 400
conn = get_db()
c = conn.cursor()
now = datetime.utcnow().isoformat()
now = get_beijing_time()
for r in rows:
mac = (r or {}).get('mac')
batch = (r or {}).get('batch')
@ -887,7 +893,7 @@ def upload_stats():
conn = get_db()
c = conn.cursor()
now = datetime.utcnow().isoformat()
now = get_beijing_time()
# 保存统计数据
c.execute('INSERT INTO stats(good,bad,fpy_good,platform,ts) VALUES(?,?,?,?,?)', (good, bad, fpy_good, platform, now))
@ -922,7 +928,7 @@ def upload_repairs():
conn = get_db()
c = conn.cursor()
now = datetime.utcnow().isoformat()
now = get_beijing_time()
c.execute('INSERT INTO repairs(qty, note, ts) VALUES(?,?,?)', (qty, note, now))
conn.commit()
@ -941,7 +947,7 @@ def upload_defects():
rows = data.get('rows') or []
conn = get_db()
c = conn.cursor()
now = datetime.utcnow().isoformat()
now = get_beijing_time()
for r in rows:
mac = (r or {}).get('mac')
batch = (r or {}).get('batch')
@ -983,7 +989,7 @@ def upload_shipments():
c.execute(
'INSERT INTO shipments(date, qty, receiver, platform, box_no, ts) VALUES(?,?,?,?,?,?)',
(date, qty, to, platform, box_no, datetime.utcnow().isoformat())
(date, qty, to, platform, box_no, get_beijing_time())
)
conn.commit()
conn.close()
@ -1043,7 +1049,7 @@ def add_personnel():
return jsonify({'error': 'invalid payload'}), 400
conn = get_db()
c = conn.cursor()
c.execute('INSERT INTO personnel(name, role, ts) VALUES(?,?,?)', (name, role, datetime.utcnow().isoformat()))
c.execute('INSERT INTO personnel(name, role, ts) VALUES(?,?,?)', (name, role, get_beijing_time()))
conn.commit()
conn.close()
log('add_personnel', name)
@ -1779,6 +1785,32 @@ def upload_mac_file():
output = result.stdout + result.stderr
success = result.returncode == 0
# 解析输出中的成功导入数据同时保存到SQLite数据库
if success:
import re
json_match = re.search(r'=== 成功导入的数据 ===\n([\s\S]*?)\n=== 数据输出结束 ===', output)
if json_match:
try:
import json as json_lib
records = json_lib.loads(json_match.group(1).strip())
if records and isinstance(records, list):
# 保存到SQLite数据库使用北京时间UTC+8
conn = get_db()
c = conn.cursor()
from datetime import timezone, timedelta
beijing_tz = timezone(timedelta(hours=8))
now = datetime.now(beijing_tz).isoformat()
for record in records:
mac = record.get('mac')
batch = record.get('batch')
if mac and batch:
c.execute('INSERT INTO mac_batches(mac, batch, ts) VALUES(?,?,?)', (mac, batch, now))
conn.commit()
conn.close()
log('upload_mac_file_db', f"saved {len(records)} records to database")
except Exception as e:
log('upload_mac_file_db_error', str(e))
log('upload_mac_file', f"type={upload_type}, success={success}")
if success:
notify_superadmin('批量上传MAC文件', f"类型: {upload_type}")
@ -1823,7 +1855,7 @@ def upload_defects_file():
return jsonify({'error': 'parse error'}), 400
conn = get_db()
c = conn.cursor()
now = datetime.utcnow().isoformat()
now = get_beijing_time()
for r in rows:
c.execute('INSERT INTO defects(mac, batch, ts) VALUES(?,?,?)', (r['mac'], r['batch'], now))
conn.commit()