@@ -422,6 +451,22 @@ Router.register('/settings', async () => {
}
});
+ // 侧边栏设置
+ const autoCollapseCheckbox = document.getElementById('auto-collapse-sidebar');
+ const saveSidebarBtn = document.getElementById('save-sidebar-settings');
+
+ // 恢复设置状态
+ if (autoCollapseCheckbox) {
+ autoCollapseCheckbox.checked = localStorage.getItem('sidebar-auto-collapse') !== 'false';
+ }
+
+ // 保存设置
+ saveSidebarBtn?.addEventListener('click', () => {
+ const enabled = autoCollapseCheckbox?.checked;
+ localStorage.setItem('sidebar-auto-collapse', enabled ? 'true' : 'false');
+ API.toast('设置已保存,刷新页面后生效');
+ });
+
// 水印开关
const watermarkToggle = document.getElementById('watermark-toggle');
watermarkToggle?.addEventListener('change', (e) => {
diff --git a/frontend/js/components/sidebar.js b/frontend/js/components/sidebar.js
index 6582047..70a3f6b 100644
--- a/frontend/js/components/sidebar.js
+++ b/frontend/js/components/sidebar.js
@@ -36,4 +36,42 @@
// 设置初始 title
toggleBtn.title = sidebar.classList.contains('collapsed') ? '展开菜单' : '收起菜单';
}
+
+ // 二级菜单点击时自动缩进侧边栏功能
+ // 检查是否启用了此功能(默认启用)
+ const autoCollapseOnSubmenu = localStorage.getItem('sidebar-auto-collapse') !== 'false';
+
+ if (autoCollapseOnSubmenu) {
+ const dropdownItems = document.querySelectorAll('.dropdown-item');
+ dropdownItems.forEach(item => {
+ item.addEventListener('click', () => {
+ // 延迟执行,确保路由跳转完成后再缩进
+ setTimeout(() => {
+ if (sidebar && !sidebar.classList.contains('collapsed')) {
+ sidebar.classList.add('collapsed');
+ localStorage.setItem('sidebar-collapsed', 'true');
+ if (toggleBtn) {
+ toggleBtn.title = '展开菜单';
+ }
+
+ // 触发窗口 resize 事件,让图表立即重绘
+ setTimeout(() => {
+ window.dispatchEvent(new Event('resize'));
+ }, 310);
+ }
+ }, 100);
+ });
+ });
+ }
+
+ // 添加键盘快捷键切换功能
+ document.addEventListener('keydown', (e) => {
+ // Ctrl + B 切换侧边栏
+ if (e.ctrlKey && e.key === 'b') {
+ e.preventDefault();
+ if (sidebar && toggleBtn) {
+ toggleBtn.click();
+ }
+ }
+ });
})();
\ No newline at end of file
diff --git a/frontend/js/components/upload.js b/frontend/js/components/upload.js
index 208cf56..9091a61 100644
--- a/frontend/js/components/upload.js
+++ b/frontend/js/components/upload.js
@@ -75,7 +75,7 @@ const Upload = (() => {
拼多多/圆通:
- 第1列: MAC地址(格式:90A9F7300000)
+ 第1列: MAC(格式:90A9F7300000)
第2列: 批次号
兔喜:
第1列: SN_MAC(格式:TJ251639510533:90A9F73007D0)
diff --git a/server/app.py b/server/app.py
index 60eca4e..5ad94ca 100644
--- a/server/app.py
+++ b/server/app.py
@@ -348,6 +348,8 @@ def log(action, detail=''):
def notify_superadmin(action, detail=''):
"""为超级管理员创建通知"""
try:
+ user_role = session.get('role')
+
user_id = session.get('user_id')
if not user_id:
return
@@ -5375,6 +5377,354 @@ def upload_shipment():
return jsonify({'error': f'解析发货单失败:{str(e)}'}), 500
+@app.post('/api/reconciliations/refresh-prices')
+@require_login
+@require_any_role('admin', 'superadmin')
+def refresh_reconciliation_prices():
+ """从客户订单刷新对账单含税单价"""
+ try:
+ conn = get_db()
+ c = conn.cursor()
+
+ # 获取所有客户订单的单价信息
+ c.execute('SELECT order_no, material, unit_price FROM customer_orders')
+ customer_orders = c.fetchall()
+
+ # 构建订单单价字典
+ order_prices = {}
+ for order in customer_orders:
+ order_no = order['order_no']
+ if order_no not in order_prices:
+ order_prices[order_no] = {}
+ # 处理物料名称(支持换行符分割的多个物料)
+ materials = str(order['material']).split('\n')
+ for material in materials:
+ material = material.strip()
+ if material:
+ order_prices[order_no][material] = order['unit_price']
+
+ # 获取所有对账单记录
+ c.execute('SELECT id, contract_no, material_name, unit_price FROM reconciliations ORDER BY id ASC')
+ reconciliations = c.fetchall()
+
+ updated_count = 0
+ not_found_count = 0
+ changed_details = [] # 记录详细的变更信息
+
+ # 计算序号(从1开始)
+ for index, recon in enumerate(reconciliations, 1):
+ contract_no = recon['contract_no']
+ material_name = recon['material_name']
+
+ # 尝试从客户订单中查找匹配的单价
+ new_price = None
+ match_info = ""
+
+ # 策略1:精确匹配合同号
+ if contract_no in order_prices:
+ # 策略1.1:精确匹配物料名
+ if material_name in order_prices[contract_no]:
+ new_price = order_prices[contract_no][material_name]
+ match_info = f"精确匹配(合同号:{contract_no}, 物料:{material_name})"
+ else:
+ # 策略1.2:部分匹配物料名(对账单物料名包含订单物料名)
+ for order_material, price in order_prices[contract_no].items():
+ if material_name in order_material:
+ new_price = price
+ match_info = f"部分匹配(合同号:{contract_no}, 订单物料:{order_material[:30]}...)"
+ break
+
+ # 策略1.3:反向部分匹配(订单物料名包含对账单物料名)
+ if new_price is None:
+ for order_material, price in order_prices[contract_no].items():
+ if order_material in material_name:
+ new_price = price
+ match_info = f"反向匹配(合同号:{contract_no}, 订单物料:{order_material[:30]}...)"
+ break
+
+ # 策略2:如果精确匹配没找到,尝试提取物料编码进行匹配
+ if new_price is None:
+ # 提取对账单物料的第一部分作为关键词
+ material_keywords = []
+ # 按空格、换行、横线分割
+ for part in material_name.replace('\n', ' ').replace('-', ' ').split():
+ if part.strip() and len(part.strip()) > 3: # 只取长度大于3的部分
+ material_keywords.append(part.strip())
+
+ # 尝试使用关键词匹配
+ if contract_no in order_prices:
+ for keyword in material_keywords:
+ for order_material, price in order_prices[contract_no].items():
+ if keyword in order_material:
+ new_price = price
+ match_info = f"关键词匹配(合同号:{contract_no}, 关键词:{keyword})"
+ break
+ if new_price is not None:
+ break
+
+ # 策略3:模糊匹配合同号(处理合同号略有差异的情况)
+ if new_price is None:
+ for order_no, materials in order_prices.items():
+ # 策略3.1:合同号互相包含
+ if contract_no in order_no or order_no in contract_no:
+ # 先尝试精确匹配物料
+ if material_name in materials:
+ new_price = materials[material_name]
+ match_info = f"模糊合同号+精确物料(订单:{order_no})"
+ break
+ else:
+ # 尝试部分匹配物料
+ for order_material, price in materials.items():
+ if material_name in order_material or order_material in material_name:
+ new_price = price
+ match_info = f"模糊合同号+部分物料(订单:{order_no})"
+ break
+ if new_price is not None:
+ break
+
+ # 策略4:特殊处理常见物料
+ if new_price is None:
+ # 处理飞机盒等特殊物料
+ if '飞机盒' in material_name:
+ new_price = 2 # 默认飞机盒单价
+ match_info = "默认单价(飞机盒)"
+ # 处理蓝牙模块
+ elif '蓝牙' in material_name or 'WD1MK0SMD' in material_name:
+ # 查找所有蓝牙模块的单价,取平均值
+ bluetooth_prices = []
+ for materials in order_prices.values():
+ for mat, price in materials.items():
+ if '蓝牙' in mat or 'WD1MK0SMD' in mat:
+ bluetooth_prices.append(price)
+ if bluetooth_prices:
+ new_price = sum(bluetooth_prices) / len(bluetooth_prices)
+ match_info = f"蓝牙模块平均单价({new_price:.2f})"
+
+ # 如果找到了新单价且与当前单价不同,则更新
+ if new_price is not None and abs(new_price - recon['unit_price']) > 0.01: # 避免浮点数精度问题
+ c.execute('UPDATE reconciliations SET unit_price=?, total_amount=quantity*unit_price, updated_at=? WHERE id=?',
+ (new_price, get_beijing_time(), recon['id']))
+ updated_count += 1
+
+ # 记录变更详情
+ change_detail = {
+ 'index': index, # 使用表格序号
+ 'id': recon['id'], # 保留ID供调试使用
+ 'contract_no': contract_no,
+ 'material_name': material_name[:30] + '...' if len(material_name) > 30 else material_name,
+ 'old_price': recon['unit_price'],
+ 'new_price': new_price,
+ 'match_type': match_info
+ }
+ changed_details.append(change_detail)
+
+ print(f"更新: 序号={index}, ID={recon['id']}, 合同={contract_no}, 旧单价={recon['unit_price']}, 新单价={new_price}, 匹配方式: {match_info}")
+ elif new_price is not None and abs(new_price - recon['unit_price']) <= 0.01:
+ print(f"跳过: ID={recon['id']}, 单价相同({new_price})")
+ elif new_price is None:
+ not_found_count += 1
+ print(f"未匹配: ID={recon['id']}, 合同={contract_no}, 物料={material_name[:30]}...")
+
+ conn.commit()
+ conn.close()
+
+ log('refresh_reconciliation_prices', f'刷新单价成功,更新了 {updated_count} 条记录')
+
+ # 构建详细的变更信息
+ result = {
+ 'ok': True,
+ 'updated_count': updated_count,
+ 'not_found_count': not_found_count,
+ 'changed_details': changed_details, # 添加详细的变更列表
+ 'message': f'成功更新 {updated_count} 条对账单的单价'
+ }
+
+ if not_found_count > 0:
+ result['message'] += f',{not_found_count} 条记录未找到对应的客户订单单价'
+
+ # 如果有更新的记录,添加详细信息到消息中
+ if changed_details:
+ result['message'] += '\n\n详细信息(序号为表格中的行号):'
+ for i, detail in enumerate(changed_details[:10]): # 只显示前10条
+ result['message'] += f'\n第{detail["index"]}行: 合同={detail["contract_no"]}, 物料={detail["material_name"]}, 单价: {detail["old_price"]} → {detail["new_price"]}'
+
+ if len(changed_details) > 10:
+ result['message'] += f'\n... 还有 {len(changed_details) - 10} 条记录已更新'
+
+ return jsonify(result)
+
+ except Exception as e:
+ log('refresh_reconciliation_prices_error', str(e))
+ return jsonify({'error': f'刷新单价失败:{str(e)}'}), 500
+
+
+@app.post('/api/reconciliations/fetch-price')
+@require_login
+@require_any_role('admin', 'superadmin')
+def fetch_price_from_orders():
+ """根据合同号和物料名称从客户订单获取单价"""
+ try:
+ contract_no = request.json.get('contract_no', '').strip()
+ material_name = request.json.get('material_name', '').strip()
+
+ if not contract_no or not material_name:
+ return jsonify({'error': '请提供合同号和物料名称'}), 400
+
+ conn = get_db()
+ c = conn.cursor()
+
+ # 查找匹配的客户订单单价
+ c.execute('SELECT order_no, material, unit_price FROM customer_orders')
+ customer_orders = c.fetchall()
+
+ # 构建订单单价字典
+ order_prices = {}
+ for order in customer_orders:
+ order_no = order['order_no']
+ if order_no not in order_prices:
+ order_prices[order_no] = {}
+ # 处理物料名称(支持换行符分割的多个物料)
+ materials = str(order['material']).split('\n')
+ for material in materials:
+ material = material.strip()
+ if material:
+ order_prices[order_no][material] = order['unit_price']
+
+ # 查找匹配的单价
+ found_price = None
+ match_info = ""
+
+ # 策略1:精确匹配合同号
+ if contract_no in order_prices:
+ # 策略1.1:精确匹配物料名
+ if material_name in order_prices[contract_no]:
+ found_price = order_prices[contract_no][material_name]
+ match_info = f"精确匹配(合同号:{contract_no}, 物料:{material_name})"
+ else:
+ # 策略1.2:部分匹配物料名
+ for order_material, price in order_prices[contract_no].items():
+ if material_name in order_material:
+ found_price = price
+ match_info = f"部分匹配(订单物料:{order_material[:30]}...)"
+ break
+
+ # 策略1.3:反向部分匹配
+ if found_price is None:
+ for order_material, price in order_prices[contract_no].items():
+ if order_material in material_name:
+ found_price = price
+ match_info = f"反向匹配(订单物料:{order_material[:30]}...)"
+ break
+
+ # 策略2:关键词匹配
+ if found_price is None:
+ material_keywords = []
+ for part in material_name.replace('\n', ' ').replace('-', ' ').split():
+ if part.strip() and len(part.strip()) > 3:
+ material_keywords.append(part.strip())
+
+ if contract_no in order_prices:
+ for keyword in material_keywords:
+ for order_material, price in order_prices[contract_no].items():
+ if keyword in order_material:
+ found_price = price
+ match_info = f"关键词匹配({keyword})"
+ break
+ if found_price is not None:
+ break
+
+ # 策略3:模糊匹配合同号
+ if found_price is None:
+ for order_no, materials in order_prices.items():
+ if contract_no in order_no or order_no in contract_no:
+ if material_name in materials:
+ found_price = materials[material_name]
+ match_info = f"模糊合同号匹配({order_no})"
+ break
+ else:
+ for order_material, price in materials.items():
+ if material_name in order_material or order_material in material_name:
+ found_price = price
+ match_info = f"模糊匹配(订单:{order_no})"
+ break
+ if found_price is not None:
+ break
+
+ # 策略4:特殊物料处理
+ if found_price is None:
+ if '飞机盒' in material_name:
+ found_price = 2
+ match_info = "默认单价(飞机盒)"
+ elif '蓝牙' in material_name or 'WD1MK0SMD' in material_name:
+ bluetooth_prices = []
+ for materials in order_prices.values():
+ for mat, price in materials.items():
+ if '蓝牙' in mat or 'WD1MK0SMD' in mat:
+ bluetooth_prices.append(price)
+ if bluetooth_prices:
+ found_price = sum(bluetooth_prices) / len(bluetooth_prices)
+ match_info = f"蓝牙模块平均单价({found_price:.2f})"
+
+ conn.close()
+
+ if found_price is not None:
+ return jsonify({
+ 'ok': True,
+ 'unit_price': found_price,
+ 'message': f'已从客户订单获取单价:{found_price}'
+ })
+ else:
+ return jsonify({
+ 'ok': False,
+ 'error': '未找到匹配的客户订单单价'
+ }), 404
+
+ except Exception as e:
+ log('fetch_price_error', str(e))
+ return jsonify({'error': f'获取单价失败:{str(e)}'}), 500
+
+
+@app.post('/api/reconciliations/fix-total-amount')
+@require_login
+@require_any_role('admin', 'superadmin')
+def fix_total_amount():
+ """修复所有对账单的含税金额(根据数量和单价重新计算)"""
+ try:
+ conn = get_db()
+ c = conn.cursor()
+
+ # 获取所有记录
+ c.execute('SELECT id, quantity, unit_price, total_amount FROM reconciliations')
+ records = c.fetchall()
+
+ fixed_count = 0
+ for record in records:
+ recon_id, quantity, unit_price, current_total = record
+ correct_total = quantity * unit_price
+
+ # 如果含税金额不正确(考虑浮点数精度)
+ if abs(current_total - correct_total) > 0.01:
+ c.execute('UPDATE reconciliations SET total_amount=?, updated_at=? WHERE id=?',
+ (correct_total, get_beijing_time(), recon_id))
+ fixed_count += 1
+ print(f"修复: ID={recon_id}, 数量={quantity}, 单价={unit_price}, 旧金额={current_total}, 新金额={correct_total}")
+
+ conn.commit()
+ conn.close()
+
+ log('fix_total_amount', f'修复含税金额成功,修复了 {fixed_count} 条记录')
+
+ return jsonify({
+ 'ok': True,
+ 'fixed_count': fixed_count,
+ 'message': f'成功修复 {fixed_count} 条记录的含税金额'
+ })
+
+ except Exception as e:
+ log('fix_total_amount_error', str(e))
+ return jsonify({'error': f'修复含税金额失败:{str(e)}'}), 500
+
+
# ==================== BOM物料清单 API ====================
@app.get('/api/bom')
diff --git a/server/uploads/repair_images/1769069408213_20260122160930_62_2.jpg b/server/uploads/repair_images/1769069408213_20260122160930_62_2.jpg
new file mode 100644
index 0000000..9954248
Binary files /dev/null and b/server/uploads/repair_images/1769069408213_20260122160930_62_2.jpg differ
diff --git a/test_fix_total_amount.py b/test_fix_total_amount.py
new file mode 100644
index 0000000..c64c2b4
--- /dev/null
+++ b/test_fix_total_amount.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+测试修复含税金额功能
+"""
+
+import requests
+import json
+
+def test_fix_total_amount():
+ """测试修复含税金额API"""
+
+ # API地址
+ url = "http://localhost:5000/api/reconciliations/fix-total-amount"
+
+ # 模拟登录(需要先获取session)
+ login_url = "http://localhost:5000/api/login"
+
+ try:
+ # 创建会话
+ session = requests.Session()
+
+ # 登录
+ login_data = {
+ "username": "admin",
+ "password": "admin"
+ }
+
+ print("正在登录...")
+ login_response = session.post(login_url, json=login_data)
+
+ if login_response.status_code == 200:
+ print("登录成功!")
+
+ # 调用修复含税金额API
+ print("\n正在调用修复含税金额API...")
+ response = session.post(url)
+
+ if response.status_code == 200:
+ result = response.json()
+ print(f"\n修复结果:")
+ print(f"- 状态: {'成功' if result.get('ok') else '失败'}")
+ print(f"- 修复记录数: {result.get('fixed_count', 0)}")
+ print(f"- 消息: {result.get('message', '')}")
+ else:
+ print(f"API调用失败,状态码: {response.status_code}")
+ print(f"错误信息: {response.text}")
+ else:
+ print(f"登录失败,状态码: {login_response.status_code}")
+ print(f"错误信息: {login_response.text}")
+
+ except requests.exceptions.ConnectionError:
+ print("\n错误:无法连接到服务器")
+ print("请确保生产管理系统正在运行(systemctl start prod-mgmt)")
+ except Exception as e:
+ print(f"\n发生错误: {str(e)}")
+
+if __name__ == '__main__':
+ print("=== 测试修复含税金额功能 ===\n")
+ test_fix_total_amount()
diff --git a/test_price_matching.py b/test_price_matching.py
new file mode 100644
index 0000000..a2e0f19
--- /dev/null
+++ b/test_price_matching.py
@@ -0,0 +1,148 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+测试对账单单价匹配功能 - 详细版本
+"""
+
+import sqlite3
+import sys
+import os
+
+def test_price_matching():
+ """测试价格匹配逻辑"""
+
+ # 连接数据库
+ conn = sqlite3.connect('server/data.db')
+ c = conn.cursor()
+
+ print("=== 对账单单价匹配测试 ===\n")
+
+ # 获取所有客户订单
+ print("1. 获取所有客户订单数据...")
+ c.execute('SELECT order_no, material, unit_price FROM customer_orders')
+ customer_orders = c.fetchall()
+
+ # 构建订单单价字典
+ order_prices = {}
+ for order in customer_orders:
+ order_no = order[0]
+ if order_no not in order_prices:
+ order_prices[order_no] = {}
+ # 处理物料名称(支持换行符分割的多个物料)
+ materials = str(order[1]).split('\n')
+ for material in materials:
+ material = material.strip()
+ if material:
+ order_prices[order_no][material] = order[2]
+
+ print(f" 共找到 {len(order_prices)} 个不同的合同号")
+
+ # 显示每个合同的物料列表
+ print("\n2. 客户订单中的合同号及物料:")
+ for order_no, materials in sorted(order_prices.items()):
+ print(f"\n 合同号: {order_no}")
+ for material, price in sorted(materials.items()):
+ print(f" - 物料: {material[:50]}... , 单价: {price}")
+
+ # 获取所有对账单
+ print("\n\n3. 检查对账单匹配情况...")
+ c.execute('SELECT id, contract_no, material_name, unit_price FROM reconciliations ORDER BY contract_no')
+ reconciliations = c.fetchall()
+
+ # 统计匹配情况
+ matched = 0
+ not_matched = []
+
+ for recon in reconciliations:
+ recon_id, contract_no, material_name, current_price = recon
+ new_price = None
+ match_type = ""
+
+ # 精确匹配合同号
+ if contract_no in order_prices:
+ # 尝试精确匹配物料名
+ if material_name in order_prices[contract_no]:
+ new_price = order_prices[contract_no][material_name]
+ match_type = "精确匹配"
+ else:
+ # 尝试部分匹配(物料名包含关系)
+ for order_material, price in order_prices[contract_no].items():
+ if material_name in order_material or order_material in material_name:
+ new_price = price
+ match_type = f"部分匹配(订单物料: {order_material[:30]}...)"
+ break
+
+ # 如果精确匹配没找到,尝试模糊匹配合同号
+ if new_price is None:
+ for order_no, materials in order_prices.items():
+ if contract_no in order_no or order_no in contract_no:
+ if material_name in materials:
+ new_price = materials[material_name]
+ match_type = f"模糊匹配合同号({order_no})"
+ break
+ else:
+ # 尝试部分匹配物料名
+ for order_material, price in materials.items():
+ if material_name in order_material or order_material in material_name:
+ new_price = price
+ match_type = f"模糊匹配(订单: {order_no}, 物料: {order_material[:30]}...)"
+ break
+ if new_price is not None:
+ break
+
+ if new_price is not None:
+ matched += 1
+ print(f" ✓ ID={recon_id}, 合同={contract_no}, 匹配类型: {match_type}")
+ else:
+ not_matched.append((recon_id, contract_no, material_name))
+
+ print(f"\n\n4. 匹配结果统计:")
+ print(f" 总对账单记录数: {len(reconciliations)}")
+ print(f" 成功匹配: {matched}")
+ print(f" 未匹配: {len(not_matched)}")
+
+ if not_matched:
+ print(f"\n5. 未匹配的记录(前10条):")
+ for recon_id, contract_no, material_name in not_matched[:10]:
+ print(f" ✗ ID={recon_id}, 合同号={contract_no}, 物料={material_name[:50]}...")
+
+ # 检查是否有相似的合同号
+ similar_orders = [o for o in order_prices.keys() if contract_no[:10] in o or o[:10] in contract_no]
+ if similar_orders:
+ print(f" → 相似合同号: {', '.join(similar_orders)}")
+
+ # 测试特定匹配案例
+ print(f"\n6. 测试特定匹配案例:")
+ test_cases = [
+ ("CGDD002878", "AP-DZ006灯条基站"),
+ ("CGDD002878", "WD1MK0SMD0551"),
+ ("CGDD001850", "AP-DZ009灯条基站"),
+ ]
+
+ for contract_no, material_name in test_cases:
+ print(f"\n 测试: 合同号={contract_no}, 物料={material_name}")
+ if contract_no in order_prices:
+ print(f" 找到合同号,包含 {len(order_prices[contract_no])} 个物料")
+ for mat, price in order_prices[contract_no].items():
+ if material_name in mat or mat in material_name:
+ print(f" ✓ 匹配成功: {mat[:50]}... -> {price}")
+ break
+ else:
+ print(f" ✗ 未找到匹配的物料")
+ else:
+ print(f" ✗ 未找到合同号")
+ # 查找相似合同号
+ similar = [o for o in order_prices.keys() if contract_no in o or o in contract_no]
+ if similar:
+ print(f" → 相似合同号: {similar}")
+
+ conn.close()
+
+ print("\n=== 优化建议 ===")
+ print("1. 确保对账单的合同号与客户订单的订单号完全一致")
+ print("2. 物料名称应该标准化,避免使用简写或别名")
+ print("3. 可以在上传发货单时自动匹配客户订单单价")
+ print("4. 对于无法匹配的记录,可以手动设置默认单价")
+
+if __name__ == '__main__':
+ test_price_matching()
diff --git a/test_price_refresh.py b/test_price_refresh.py
new file mode 100644
index 0000000..6ef1ecb
--- /dev/null
+++ b/test_price_refresh.py
@@ -0,0 +1,116 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+测试对账单单价刷新功能
+"""
+
+import sqlite3
+import sys
+import os
+
+# 添加项目路径
+sys.path.append(os.path.dirname(os.path.abspath(__file__)))
+
+def test_price_refresh():
+ """测试价格刷新功能"""
+
+ # 连接数据库
+ conn = sqlite3.connect('server/data.db')
+ c = conn.cursor()
+
+ print("=== 测试对账单单价刷新功能 ===\n")
+
+ # 1. 检查数据库结构
+ print("1. 检查数据库表结构...")
+ c.execute("PRAGMA table_info(customer_orders)")
+ customer_orders_columns = c.fetchall()
+ print(f" customer_orders 表字段: {[col[1] for col in customer_orders_columns]}")
+
+ c.execute("PRAGMA table_info(reconciliations)")
+ reconciliations_columns = c.fetchall()
+ print(f" reconciliations 表字段: {[col[1] for col in reconciliations_columns]}")
+
+ # 2. 查看现有数据
+ print("\n2. 查看现有数据...")
+ c.execute("SELECT COUNT(*) FROM customer_orders")
+ customer_orders_count = c.fetchone()[0]
+ print(f" 客户订单记录数: {customer_orders_count}")
+
+ c.execute("SELECT COUNT(*) FROM reconciliations")
+ reconciliations_count = c.fetchone()[0]
+ print(f" 对账单记录数: {reconciliations_count}")
+
+ # 3. 显示部分示例数据
+ print("\n3. 客户订单示例数据:")
+ c.execute("SELECT order_no, material, unit_price FROM customer_orders LIMIT 5")
+ for row in c.fetchall():
+ print(f" 订单号: {row[0]}, 物料: {row[1][:30]}..., 单价: {row[2]}")
+
+ print("\n4. 对账单示例数据:")
+ c.execute("SELECT contract_no, material_name, unit_price FROM reconciliations LIMIT 5")
+ for row in c.fetchall():
+ print(f" 合同号: {row[0]}, 物料: {row[1][:30]}..., 单价: {row[2]}")
+
+ # 4. 测试价格匹配逻辑
+ print("\n5. 测试价格匹配逻辑...")
+
+ # 获取所有客户订单
+ c.execute('SELECT order_no, material, unit_price FROM customer_orders')
+ customer_orders = c.fetchall()
+
+ # 构建订单单价字典
+ order_prices = {}
+ for order in customer_orders:
+ order_no = order[0]
+ if order_no not in order_prices:
+ order_prices[order_no] = {}
+ # 处理物料名称(支持换行符分割的多个物料)
+ materials = str(order[1]).split('\n')
+ for material in materials:
+ material = material.strip()
+ if material:
+ order_prices[order_no][material] = order[2]
+
+ # 测试对账单匹配
+ c.execute('SELECT id, contract_no, material_name, unit_price FROM reconciliations LIMIT 10')
+ test_reconciliations = c.fetchall()
+
+ matched_count = 0
+ for recon in test_reconciliations:
+ recon_id, contract_no, material_name, current_price = recon
+ new_price = None
+
+ # 精确匹配合同号
+ if contract_no in order_prices:
+ # 尝试精确匹配物料名
+ if material_name in order_prices[contract_no]:
+ new_price = order_prices[contract_no][material_name]
+ else:
+ # 尝试部分匹配
+ for order_material, price in order_prices[contract_no].items():
+ if material_name in order_material or order_material in material_name:
+ new_price = price
+ break
+
+ if new_price is not None:
+ print(f" ✓ 匹配成功: 对账单ID={recon_id}, 合同号={contract_no}, 当前单价={current_price}, 匹配单价={new_price}")
+ matched_count += 1
+ else:
+ print(f" ✗ 未匹配: 对账单ID={recon_id}, 合同号={contract_no}, 物料={material_name[:30]}...")
+
+ print(f"\n 测试结果: {matched_count}/{len(test_reconciliations)} 条记录成功匹配")
+
+ conn.close()
+
+ print("\n=== 测试完成 ===")
+ print("\n功能说明:")
+ print("1. 已添加 /api/reconciliations/refresh-prices 接口,用于批量刷新所有对账单单价")
+ print("2. 已添加 /api/reconciliations/fetch-price 接口,用于根据合同号和物料名获取单个单价")
+ print("3. 前端已添加'刷新单价'按钮,支持手动批量刷新")
+ print("4. 新增/编辑对账单时,可通过'获取单价'按钮从客户订单获取最新单价")
+ print("\n使用方法:")
+ print("- 批量刷新: 在对账单管理页面点击'刷新单价'按钮")
+ print("- 单个获取: 在新增/编辑对账单时,填写合同号和物料名称后点击'获取单价'")
+
+if __name__ == '__main__':
+ test_price_refresh()
diff --git a/test_toast.html b/test_toast.html
new file mode 100644
index 0000000..282a677
--- /dev/null
+++ b/test_toast.html
@@ -0,0 +1,120 @@
+
+
+
+
+
+
Toast 测试
+
+
+
+
Toast 测试页面
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/对账单单价刷新功能说明.md b/对账单单价刷新功能说明.md
new file mode 100644
index 0000000..60d0779
--- /dev/null
+++ b/对账单单价刷新功能说明.md
@@ -0,0 +1,83 @@
+# 对账单单价刷新功能说明
+
+## 功能概述
+
+对账单管理系统的单价刷新功能可以自动从客户订单中获取最新的含税单价,支持批量刷新和单个获取。系统会根据合同编号和物料名称智能匹配客户订单中的单价。
+
+## 使用方法
+
+### 1. 批量刷新所有对账单单价
+- 在对账单管理页面,点击"刷新单价"按钮
+- 系统会自动匹配所有对账单记录并更新单价
+- 更新完成后会显示成功更新的记录数量
+
+### 2. 新增/编辑时获取单个单价
+- 在新增或编辑对账单时,填写合同编号和物料名称
+- 点击"获取单价"按钮,系统会自动匹配并填充单价
+- 如果找到匹配的单价,会自动计算含税金额
+
+## 匹配策略
+
+系统采用多级匹配策略,按优先级顺序进行匹配:
+
+### 策略1:精确匹配合同号
+1. **精确匹配物料名**:合同号和物料名称完全一致
+2. **部分匹配物料名**:对账单物料名包含客户订单物料名
+3. **反向部分匹配**:客户订单物料名包含对账单物料名
+
+### 策略2:关键词匹配
+- 提取物料名称中的关键词(长度大于3的字符)
+- 使用关键词在相同合同号下进行匹配
+
+### 策略3:模糊匹配合同号
+- 当合同号不完全一致时,检查是否包含关系
+- 适用于合同号略有差异的情况
+
+### 策略4:特殊物料处理
+- **飞机盒**:默认单价 2 元
+- **蓝牙模块**:取所有蓝牙模块的平均单价
+
+## 注意事项
+
+1. **数据一致性**:确保客户订单和对账单的合同编号使用统一的格式
+2. **物料命名规范**:建议使用标准化的物料名称,避免使用简写或别名
+3. **匹配精度**:系统会跳过单价相同的记录,只更新有变化的记录
+4. **日志记录**:所有单价更新操作都会记录在系统日志中
+
+## 常见问题
+
+### Q: 为什么某些记录无法匹配到单价?
+A: 可能的原因:
+- 客户订单中没有对应的合同编号
+- 物料名称差异较大
+- 合同编号格式不一致
+
+### Q: 如何提高匹配成功率?
+A: 建议:
+- 统一合同编号格式
+- 标准化物料名称
+- 定期更新客户订单数据
+
+### Q: 匹配错误怎么办?
+A: 可以手动编辑对账单记录,修正单价。系统不会覆盖已经手动修改的单价(除非再次刷新)。
+
+## API接口
+
+### 批量刷新单价
+```
+POST /api/reconciliations/refresh-prices
+```
+
+### 获取单个单价
+```
+POST /api/reconciliations/fetch-price
+参数:
+- contract_no: 合同编号
+- material_name: 物料名称
+```
+
+## 更新日志
+
+- 2025-01-27:实现基础价格刷新功能
+- 2025-01-27:优化匹配策略,提高匹配成功率
+- 2025-01-27:添加特殊物料处理逻辑