style: normalize code formatting across the codebase
- Standardize quote style (single to double quotes) - Improve code formatting consistency - Apply formatting to utilities, GUI components, and tools - Update imports and docstrings for consistency Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
"""
|
||||
工具组件包
|
||||
"""
|
||||
|
||||
from .excel_converter import ExcelConverter
|
||||
from .离散备料计划维护数据提取 import DiscreteMaterialPlanExtractor
|
||||
|
||||
__all__ = ['ExcelConverter', 'DiscreteMaterialPlanExtractor']
|
||||
__all__ = ["ExcelConverter", "DiscreteMaterialPlanExtractor"]
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
认证模块 - 负责用友BIP系统的登录和退出操作
|
||||
"""
|
||||
|
||||
from playwright.sync_api import Playwright, Browser, BrowserContext, Page, Frame
|
||||
|
||||
|
||||
@@ -11,7 +12,7 @@ def login(
|
||||
url: str = "https://68.11.34.30:8082/yonbip/resources/uap/rbac/login/main/index.html",
|
||||
headless: bool = False,
|
||||
ignore_https_errors: bool = True,
|
||||
verbose: bool = True
|
||||
verbose: bool = True,
|
||||
) -> tuple[Browser, BrowserContext, Page, Frame]:
|
||||
"""
|
||||
登录用友BIP系统
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
Excel 报表数据转换工具组件
|
||||
将 Excel 报表数据转换为数据库记录形式
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
import openpyxl
|
||||
from typing import List, Dict, Optional
|
||||
@@ -12,10 +13,7 @@ class ExcelConverter:
|
||||
"""Excel 报表数据转换器"""
|
||||
|
||||
# 字段名称映射(解决字段名冲突)
|
||||
FIELD_NAME_MAPPING = {
|
||||
'计划数量': '产品计划数量',
|
||||
'单位': '产品单位'
|
||||
}
|
||||
FIELD_NAME_MAPPING = {"计划数量": "产品计划数量", "单位": "产品单位"}
|
||||
|
||||
def __init__(self, verbose: bool = True):
|
||||
"""
|
||||
@@ -115,7 +113,7 @@ class ExcelConverter:
|
||||
row = all_rows[i]
|
||||
|
||||
# 检查是否是订单标题行
|
||||
if row and '离散备料计划' in str(row[0]):
|
||||
if row and "离散备料计划" in str(row[0]):
|
||||
# 解析订单头信息(接下来的4行)
|
||||
order_info = {}
|
||||
for j in range(1, 5):
|
||||
@@ -124,16 +122,27 @@ class ExcelConverter:
|
||||
|
||||
# 跳过空行,找到表格标题行
|
||||
table_row = i + 5
|
||||
while table_row < len(all_rows) and (not all_rows[table_row] or not all_rows[table_row][0]):
|
||||
while table_row < len(all_rows) and (
|
||||
not all_rows[table_row] or not all_rows[table_row][0]
|
||||
):
|
||||
table_row += 1
|
||||
|
||||
# 检查是否是表格标题行
|
||||
if table_row < len(all_rows) and all_rows[table_row] and all_rows[table_row][0] == '序号':
|
||||
if (
|
||||
table_row < len(all_rows)
|
||||
and all_rows[table_row]
|
||||
and all_rows[table_row][0] == "序号"
|
||||
):
|
||||
# 检查表头下一行是否为空,判断是否存在数据
|
||||
next_row = table_row + 1
|
||||
is_empty_row = (next_row < len(all_rows) and
|
||||
all_rows[next_row] and
|
||||
all(cell is None or str(cell).strip() == "" for cell in all_rows[next_row]))
|
||||
is_empty_row = (
|
||||
next_row < len(all_rows)
|
||||
and all_rows[next_row]
|
||||
and all(
|
||||
cell is None or str(cell).strip() == ""
|
||||
for cell in all_rows[next_row]
|
||||
)
|
||||
)
|
||||
|
||||
if is_empty_row:
|
||||
# 没有数据,查找页脚信息
|
||||
@@ -141,17 +150,27 @@ class ExcelConverter:
|
||||
footer_info = {}
|
||||
data_row = next_row + 1
|
||||
while data_row < len(all_rows) and all_rows[data_row]:
|
||||
if all_rows[data_row][0] and ('制单人' in str(all_rows[data_row][0]) or '打印人' in str(all_rows[data_row][0])):
|
||||
if all_rows[data_row][0] and (
|
||||
"制单人" in str(all_rows[data_row][0])
|
||||
or "打印人" in str(all_rows[data_row][0])
|
||||
):
|
||||
self._parse_header_row(all_rows[data_row], footer_info)
|
||||
if data_row + 1 < len(all_rows) and all_rows[data_row + 1]:
|
||||
self._parse_header_row(all_rows[data_row + 1], footer_info)
|
||||
if (
|
||||
data_row + 1 < len(all_rows)
|
||||
and all_rows[data_row + 1]
|
||||
):
|
||||
self._parse_header_row(
|
||||
all_rows[data_row + 1], footer_info
|
||||
)
|
||||
break
|
||||
data_row += 1
|
||||
|
||||
orders.append({
|
||||
'order_info': {**order_info, **footer_info},
|
||||
'materials': materials
|
||||
})
|
||||
orders.append(
|
||||
{
|
||||
"order_info": {**order_info, **footer_info},
|
||||
"materials": materials,
|
||||
}
|
||||
)
|
||||
else:
|
||||
# 有数据,开始提取物料
|
||||
materials = []
|
||||
@@ -159,39 +178,48 @@ class ExcelConverter:
|
||||
data_row = table_row + 1
|
||||
while data_row < len(all_rows) and all_rows[data_row]:
|
||||
# 检查是否是页脚信息(制单人、打印人)
|
||||
if all_rows[data_row+1][0] and '制单人' in str(all_rows[data_row+1][0]) :
|
||||
if all_rows[data_row + 1][0] and "制单人" in str(
|
||||
all_rows[data_row + 1][0]
|
||||
):
|
||||
# 解析页脚信息
|
||||
self._parse_header_row(all_rows[data_row], footer_info)
|
||||
# 检查下一行是否也是页脚信息
|
||||
if data_row + 1 < len(all_rows) and all_rows[data_row + 1]:
|
||||
self._parse_header_row(all_rows[data_row + 1], footer_info)
|
||||
if (
|
||||
data_row + 1 < len(all_rows)
|
||||
and all_rows[data_row + 1]
|
||||
):
|
||||
self._parse_header_row(
|
||||
all_rows[data_row + 1], footer_info
|
||||
)
|
||||
break
|
||||
|
||||
# 提取物料数据
|
||||
material_row = all_rows[data_row]
|
||||
material = {
|
||||
'序号': material_row[0],
|
||||
'材料编码': material_row[1],
|
||||
'材料名称': material_row[2],
|
||||
'规格': material_row[3],
|
||||
'型号': material_row[4],
|
||||
'图号': material_row[5],
|
||||
'物料材质': material_row[6],
|
||||
'计划数量': material_row[7],
|
||||
'单位': material_row[8],
|
||||
'需用日期': material_row[9],
|
||||
'发料仓库': material_row[10],
|
||||
'单位用量': material_row[11],
|
||||
'累计出库数量': material_row[12],
|
||||
"序号": material_row[0],
|
||||
"材料编码": material_row[1],
|
||||
"材料名称": material_row[2],
|
||||
"规格": material_row[3],
|
||||
"型号": material_row[4],
|
||||
"图号": material_row[5],
|
||||
"物料材质": material_row[6],
|
||||
"计划数量": material_row[7],
|
||||
"单位": material_row[8],
|
||||
"需用日期": material_row[9],
|
||||
"发料仓库": material_row[10],
|
||||
"单位用量": material_row[11],
|
||||
"累计出库数量": material_row[12],
|
||||
}
|
||||
materials.append(material)
|
||||
|
||||
data_row += 1
|
||||
|
||||
orders.append({
|
||||
'order_info': {**order_info, **footer_info},
|
||||
'materials': materials
|
||||
})
|
||||
orders.append(
|
||||
{
|
||||
"order_info": {**order_info, **footer_info},
|
||||
"materials": materials,
|
||||
}
|
||||
)
|
||||
|
||||
i += 1
|
||||
|
||||
@@ -208,9 +236,9 @@ class ExcelConverter:
|
||||
i = 0
|
||||
while i < len(row):
|
||||
cell = row[i]
|
||||
if cell and str(cell).strip() and ':' in str(cell):
|
||||
if cell and str(cell).strip() and ":" in str(cell):
|
||||
# 找到字段名
|
||||
field_name = str(cell).replace(':', '').strip()
|
||||
field_name = str(cell).replace(":", "").strip()
|
||||
|
||||
# 应用字段名映射
|
||||
if field_name in self.FIELD_NAME_MAPPING:
|
||||
@@ -218,9 +246,11 @@ class ExcelConverter:
|
||||
|
||||
# 跳过空单元格,找到第一个非字段名的值
|
||||
j = i + 1
|
||||
while j < len(row) and (not row[j] or not str(row[j]).strip() or ':' in str(row[j])):
|
||||
while j < len(row) and (
|
||||
not row[j] or not str(row[j]).strip() or ":" in str(row[j])
|
||||
):
|
||||
j += 1
|
||||
if j < len(row) and row[j] and not ':' in str(row[j]):
|
||||
if j < len(row) and row[j] and not ":" in str(row[j]):
|
||||
info[field_name] = str(row[j]).strip()
|
||||
# 跳过已处理的值,继续找下一个字段名
|
||||
i = j + 1
|
||||
@@ -240,14 +270,11 @@ class ExcelConverter:
|
||||
all_records = []
|
||||
|
||||
for order in orders:
|
||||
order_info = order['order_info']
|
||||
materials = order['materials']
|
||||
order_info = order["order_info"]
|
||||
materials = order["materials"]
|
||||
|
||||
for material in materials:
|
||||
record = {
|
||||
**order_info,
|
||||
**material
|
||||
}
|
||||
record = {**order_info, **material}
|
||||
all_records.append(record)
|
||||
|
||||
return pd.DataFrame(all_records)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
物料状态校验工具
|
||||
校验订单中的物料状态,匹配待删除物料
|
||||
"""
|
||||
|
||||
import os
|
||||
import pandas as pd
|
||||
from typing import List, Dict, Any
|
||||
@@ -49,8 +50,9 @@ class MaterialStatusValidator:
|
||||
material_names = [str(name) for name in material_names]
|
||||
return material_names
|
||||
|
||||
def match_materials(self, material_names: List[str],
|
||||
db_materials: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
def match_materials(
|
||||
self, material_names: List[str], db_materials: List[Dict[str, Any]]
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
匹配材料名称
|
||||
|
||||
@@ -66,22 +68,27 @@ class MaterialStatusValidator:
|
||||
matched = None
|
||||
for db_record in db_materials:
|
||||
# 如果数据库的MaterialName出现在Excel的材料名称中
|
||||
if db_record['MaterialName'] in material_name:
|
||||
if db_record["MaterialName"] in material_name:
|
||||
matched = db_record
|
||||
break
|
||||
|
||||
results.append({
|
||||
'材料名称': material_name,
|
||||
'匹配的MaterialName': matched['MaterialName'] if matched else None,
|
||||
'负责人': matched['ManagerName'] if matched else None,
|
||||
'匹配状态': '匹配成功' if matched else '未匹配'
|
||||
})
|
||||
results.append(
|
||||
{
|
||||
"材料名称": material_name,
|
||||
"匹配的MaterialName": matched["MaterialName"] if matched else None,
|
||||
"负责人": matched["ManagerName"] if matched else None,
|
||||
"匹配状态": "匹配成功" if matched else "未匹配",
|
||||
}
|
||||
)
|
||||
|
||||
return results
|
||||
|
||||
def validate(self, production_id_file: str,
|
||||
merged_excel_file: str = None,
|
||||
output_file: str = None) -> str:
|
||||
def validate(
|
||||
self,
|
||||
production_id_file: str,
|
||||
merged_excel_file: str = None,
|
||||
output_file: str = None,
|
||||
) -> str:
|
||||
"""
|
||||
执行完整的校验流程
|
||||
|
||||
@@ -106,7 +113,7 @@ class MaterialStatusValidator:
|
||||
username=self.username,
|
||||
password=self.password,
|
||||
headless=self.headless,
|
||||
verbose=self.verbose
|
||||
verbose=self.verbose,
|
||||
)
|
||||
extractor.extract(production_id_file, output_file=merged_excel_file)
|
||||
self._print(f"数据提取完成: {merged_excel_file}")
|
||||
@@ -132,7 +139,7 @@ class MaterialStatusValidator:
|
||||
self._print(f"结果已保存: {output_file}")
|
||||
|
||||
# 打印统计信息
|
||||
matched_count = sum(1 for r in results if r['匹配状态'] == '匹配成功')
|
||||
matched_count = sum(1 for r in results if r["匹配状态"] == "匹配成功")
|
||||
self._print(f"\n统计信息:")
|
||||
self._print(f" 总材料数: {len(results)}")
|
||||
self._print(f" 匹配成功: {matched_count}")
|
||||
@@ -140,7 +147,9 @@ class MaterialStatusValidator:
|
||||
|
||||
return output_file
|
||||
|
||||
def validate_from_existing_excel(self, excel_file: str, output_file: str = None) -> str:
|
||||
def validate_from_existing_excel(
|
||||
self, excel_file: str, output_file: str = None
|
||||
) -> str:
|
||||
"""
|
||||
从已存在的Excel文件执行校验(不需要重新提取数据)
|
||||
|
||||
@@ -179,7 +188,7 @@ class MaterialStatusValidator:
|
||||
self._print(f"结果已保存: {output_file}")
|
||||
|
||||
# 打印统计信息
|
||||
matched_count = sum(1 for r in results if r['匹配状态'] == '匹配成功')
|
||||
matched_count = sum(1 for r in results if r["匹配状态"] == "匹配成功")
|
||||
self._print(f"\n统计信息:")
|
||||
self._print(f" 总材料数: {len(results)}")
|
||||
self._print(f" 匹配成功: {matched_count}")
|
||||
|
||||
@@ -2,19 +2,25 @@
|
||||
离散备料计划维护数据提取工具
|
||||
负责登录、批量下载、转换数据
|
||||
"""
|
||||
|
||||
import os
|
||||
import pandas as pd
|
||||
from playwright.sync_api import sync_playwright
|
||||
from utils.excel_converter import ExcelConverter
|
||||
from utils.auth import login, logout
|
||||
from db.production_order_query import read_production_ids, query_production_order_numbers
|
||||
from db.production_order_query import (
|
||||
read_production_ids,
|
||||
query_production_order_numbers,
|
||||
)
|
||||
from typing import Callable, Optional
|
||||
|
||||
|
||||
class DiscreteMaterialPlanExtractor:
|
||||
"""离散备料计划维护数据提取器"""
|
||||
|
||||
def __init__(self, username, password, headless=False, verbose=True, batch_size=100):
|
||||
def __init__(
|
||||
self, username, password, headless=False, verbose=True, batch_size=100
|
||||
):
|
||||
"""
|
||||
初始化提取器
|
||||
|
||||
@@ -38,7 +44,9 @@ class DiscreteMaterialPlanExtractor:
|
||||
if self.verbose:
|
||||
print(*args, **kwargs)
|
||||
|
||||
def _report_progress(self, stage: str, current: int, total: int, message: str, **detail):
|
||||
def _report_progress(
|
||||
self, stage: str, current: int, total: int, message: str, **detail
|
||||
):
|
||||
"""
|
||||
报告进度
|
||||
|
||||
@@ -52,12 +60,13 @@ class DiscreteMaterialPlanExtractor:
|
||||
if self.progress_callback:
|
||||
try:
|
||||
from gui.progress import ProgressInfo
|
||||
|
||||
progress_info = ProgressInfo(
|
||||
stage=stage,
|
||||
current=current,
|
||||
total=total,
|
||||
message=message,
|
||||
detail=detail
|
||||
detail=detail,
|
||||
)
|
||||
self.progress_callback(progress_info)
|
||||
except Exception:
|
||||
@@ -84,16 +93,31 @@ class DiscreteMaterialPlanExtractor:
|
||||
self._print(f"查询到 {len(order_ids)} 个生产订单号")
|
||||
|
||||
if report_progress:
|
||||
self._report_progress('query', 1, 1, f"查询到 {len(order_ids)} 个生产订单号", count=len(order_ids))
|
||||
self._report_progress(
|
||||
"query",
|
||||
1,
|
||||
1,
|
||||
f"查询到 {len(order_ids)} 个生产订单号",
|
||||
count=len(order_ids),
|
||||
)
|
||||
|
||||
return order_ids
|
||||
|
||||
def group_order_ids(self, order_ids, group_size=100):
|
||||
"""将订单号分组"""
|
||||
for i in range(0, len(order_ids), group_size):
|
||||
yield order_ids[i:i + group_size]
|
||||
yield order_ids[i : i + group_size]
|
||||
|
||||
def download_batch(self, inner_frame, order_ids, batch_index, total_batches, page1, debug_mode=False, debug_batch=None):
|
||||
def download_batch(
|
||||
self,
|
||||
inner_frame,
|
||||
order_ids,
|
||||
batch_index,
|
||||
total_batches,
|
||||
page1,
|
||||
debug_mode=False,
|
||||
debug_batch=None,
|
||||
):
|
||||
"""下载一批订单号的数据"""
|
||||
from playwright.sync_api import TimeoutError
|
||||
import re
|
||||
@@ -133,7 +157,11 @@ class DiscreteMaterialPlanExtractor:
|
||||
inner_frame.get_by_text("输出", exact=True).click()
|
||||
|
||||
# 设置行数阈值
|
||||
input_box = inner_frame.locator("div").filter(has_text=re.compile(r"^行数阈值$")).locator("input[type='text']")
|
||||
input_box = (
|
||||
inner_frame.locator("div")
|
||||
.filter(has_text=re.compile(r"^行数阈值$"))
|
||||
.locator("input[type='text']")
|
||||
)
|
||||
input_box.fill("300000")
|
||||
|
||||
# 下载文件
|
||||
@@ -147,11 +175,11 @@ class DiscreteMaterialPlanExtractor:
|
||||
|
||||
# 报告进度
|
||||
self._report_progress(
|
||||
'download',
|
||||
"download",
|
||||
batch_index + 1,
|
||||
total_batches,
|
||||
f"第 {batch_index + 1}/{total_batches} 批下载完成",
|
||||
batch_index=batch_index + 1
|
||||
batch_index=batch_index + 1,
|
||||
)
|
||||
|
||||
# 关闭输出对话框(如果有的话)
|
||||
@@ -188,12 +216,12 @@ class DiscreteMaterialPlanExtractor:
|
||||
|
||||
# 报告进度
|
||||
self._report_progress(
|
||||
'convert',
|
||||
"convert",
|
||||
i,
|
||||
len(file_paths),
|
||||
f"转换第 {i}/{len(file_paths)} 个文件",
|
||||
file_index=i,
|
||||
file_path=file_path
|
||||
file_path=file_path,
|
||||
)
|
||||
|
||||
df = self.converter.convert(file_path, output_file=None) # 只转换,不保存
|
||||
@@ -235,13 +263,23 @@ class DiscreteMaterialPlanExtractor:
|
||||
self._print(f"文本框填充成功: {expected_value}")
|
||||
break
|
||||
else:
|
||||
self._print(f"第 {attempt + 1} 次填充失败,实际值: {actual_value},重试...")
|
||||
self._print(
|
||||
f"第 {attempt + 1} 次填充失败,实际值: {actual_value},重试..."
|
||||
)
|
||||
if attempt == max_retries - 1:
|
||||
self._print(f"警告: {max_retries} 次尝试后仍未成功填充,继续执行...")
|
||||
self._print(
|
||||
f"警告: {max_retries} 次尝试后仍未成功填充,继续执行..."
|
||||
)
|
||||
|
||||
def extract(self, production_id_file, data_dir="D:/python/playwrite/data",
|
||||
output_file="D:/python/playwrite/data/离散备料计划维护_合并.xlsx",
|
||||
debug_mode=False, debug_batch=None, progress_callback=None):
|
||||
def extract(
|
||||
self,
|
||||
production_id_file,
|
||||
data_dir="D:/python/playwrite/data",
|
||||
output_file="D:/python/playwrite/data/离散备料计划维护_合并.xlsx",
|
||||
debug_mode=False,
|
||||
debug_batch=None,
|
||||
progress_callback=None,
|
||||
):
|
||||
"""
|
||||
执行完整的数据提取流程
|
||||
|
||||
@@ -269,11 +307,11 @@ class DiscreteMaterialPlanExtractor:
|
||||
username=self.username,
|
||||
password=self.password,
|
||||
headless=self.headless,
|
||||
ignore_https_errors=True
|
||||
ignore_https_errors=True,
|
||||
)
|
||||
|
||||
# 登录完成
|
||||
self._report_progress('login', 1, 1, "登录成功")
|
||||
self._report_progress("login", 1, 1, "登录成功")
|
||||
|
||||
self._print("=" * 80)
|
||||
self._print("开始执行离散备料计划维护数据提取")
|
||||
@@ -285,7 +323,9 @@ class DiscreteMaterialPlanExtractor:
|
||||
|
||||
# 点击打开"离散备料计划维护"
|
||||
with page.expect_popup() as page1_info:
|
||||
main_frame.get_by_title("离散备料计划维护", exact=True).first.click()
|
||||
main_frame.get_by_title(
|
||||
"离散备料计划维护", exact=True
|
||||
).first.click()
|
||||
page1 = page1_info.value
|
||||
|
||||
# 获取 nested iframe
|
||||
@@ -298,47 +338,62 @@ class DiscreteMaterialPlanExtractor:
|
||||
self.setup_query_interface(inner_frame)
|
||||
|
||||
# 读取总排号并查询生产订单号
|
||||
order_ids = self.get_production_order_numbers(production_id_file, report_progress=True)
|
||||
order_ids = self.get_production_order_numbers(
|
||||
production_id_file, report_progress=True
|
||||
)
|
||||
|
||||
# 按批次下载
|
||||
downloaded_files = []
|
||||
# 计算总批次数
|
||||
total_batches = sum(1 for _ in self.group_order_ids(order_ids, self.batch_size))
|
||||
total_batches = sum(
|
||||
1 for _ in self.group_order_ids(order_ids, self.batch_size)
|
||||
)
|
||||
|
||||
for batch_index, order_ids_batch in enumerate(self.group_order_ids(order_ids, self.batch_size)):
|
||||
self._print(f"\n=== 开始处理第 {batch_index + 1} 批,共 {len(order_ids_batch)} 个订单号 ===")
|
||||
for batch_index, order_ids_batch in enumerate(
|
||||
self.group_order_ids(order_ids, self.batch_size)
|
||||
):
|
||||
self._print(
|
||||
f"\n=== 开始处理第 {batch_index + 1} 批,共 {len(order_ids_batch)} 个订单号 ==="
|
||||
)
|
||||
|
||||
# 报告开始下载批次
|
||||
self._report_progress(
|
||||
'download',
|
||||
"download",
|
||||
batch_index,
|
||||
total_batches,
|
||||
f"正在下载第 {batch_index + 1}/{total_batches} 批...",
|
||||
batch_index=batch_index + 1,
|
||||
batch_size=len(order_ids_batch)
|
||||
batch_size=len(order_ids_batch),
|
||||
)
|
||||
|
||||
downloaded_file = self.download_batch(
|
||||
inner_frame, order_ids_batch, batch_index, total_batches, page1,
|
||||
debug_mode=debug_mode, debug_batch=debug_batch
|
||||
inner_frame,
|
||||
order_ids_batch,
|
||||
batch_index,
|
||||
total_batches,
|
||||
page1,
|
||||
debug_mode=debug_mode,
|
||||
debug_batch=debug_batch,
|
||||
)
|
||||
downloaded_files.append(downloaded_file)
|
||||
|
||||
# 执行账号注销
|
||||
self._print("\n开始执行账号注销...")
|
||||
self._report_progress('logout', 1, 1, "正在注销账号...")
|
||||
self._report_progress("logout", 1, 1, "正在注销账号...")
|
||||
logout(main_frame, verbose=self.verbose)
|
||||
|
||||
# 转换并合并文件
|
||||
if downloaded_files:
|
||||
self._report_progress(
|
||||
'convert',
|
||||
"convert",
|
||||
0,
|
||||
len(downloaded_files),
|
||||
f"开始转换并合并 {len(downloaded_files)} 个文件",
|
||||
file_count=len(downloaded_files)
|
||||
file_count=len(downloaded_files),
|
||||
)
|
||||
self._print(
|
||||
f"\n=== 开始转换并合并 {len(downloaded_files)} 个文件 ==="
|
||||
)
|
||||
self._print(f"\n=== 开始转换并合并 {len(downloaded_files)} 个文件 ===")
|
||||
self.convert_and_merge_files(downloaded_files, output_file)
|
||||
else:
|
||||
self._print("\n没有下载到任何文件")
|
||||
@@ -347,7 +402,9 @@ class DiscreteMaterialPlanExtractor:
|
||||
self._print(f"最终文件: {output_file}")
|
||||
|
||||
# 报告完成
|
||||
self._report_progress('complete', 1, 1, "提取完成", output_file=output_file)
|
||||
self._report_progress(
|
||||
"complete", 1, 1, "提取完成", output_file=output_file
|
||||
)
|
||||
|
||||
# 关闭浏览器
|
||||
context.close()
|
||||
@@ -359,13 +416,14 @@ class DiscreteMaterialPlanExtractor:
|
||||
# 恢复原始回调
|
||||
self.progress_callback = original_callback
|
||||
|
||||
|
||||
def main():
|
||||
"""测试函数"""
|
||||
extractor = DiscreteMaterialPlanExtractor(
|
||||
username="BLDpengqiangqiang",
|
||||
password="Cqbld123456.",
|
||||
headless=False,
|
||||
verbose=True
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
production_id_file = os.path.join(os.path.dirname(__file__), "productionID.txt")
|
||||
|
||||
@@ -2,10 +2,14 @@
|
||||
离散备料计划维护数据清理工具
|
||||
负责登录、逐个清理订单数据
|
||||
"""
|
||||
|
||||
import os
|
||||
from playwright.sync_api import sync_playwright
|
||||
from utils.auth import login, logout
|
||||
from db.production_order_query import read_production_ids, query_production_order_numbers
|
||||
from db.production_order_query import (
|
||||
read_production_ids,
|
||||
query_production_order_numbers,
|
||||
)
|
||||
from db.materials_to_delete import get_materials_to_delete
|
||||
|
||||
|
||||
@@ -54,7 +58,16 @@ class DiscreteMaterialPlanCleaner:
|
||||
|
||||
return order_ids
|
||||
|
||||
def process_order(self, inner_frame, order_id, order_index, page1, materials_to_delete=None, debug_mode=False, debug_order=None):
|
||||
def process_order(
|
||||
self,
|
||||
inner_frame,
|
||||
order_id,
|
||||
order_index,
|
||||
page1,
|
||||
materials_to_delete=None,
|
||||
debug_mode=False,
|
||||
debug_order=None,
|
||||
):
|
||||
"""清理单个订单的数据
|
||||
|
||||
Args:
|
||||
@@ -97,9 +110,8 @@ class DiscreteMaterialPlanCleaner:
|
||||
if debug_mode and (debug_order is None or order_index == debug_order):
|
||||
self._print(f"=== 调试暂停:第 {order_index + 1} 个订单 ===")
|
||||
page1.pause()
|
||||
|
||||
|
||||
inner_frame.locator("#hot-key-head_list").get_by_text("更多").click()
|
||||
|
||||
|
||||
with page1.expect_popup() as page2_info:
|
||||
inner_frame.get_by_text("备料计划").click()
|
||||
@@ -153,9 +165,7 @@ class DiscreteMaterialPlanCleaner:
|
||||
detail_status = match.group(1)
|
||||
self._print(f"备料状态: {detail_status}")
|
||||
|
||||
|
||||
|
||||
#page2.pause()
|
||||
# page2.pause()
|
||||
if detail_count > 0 and detail_status == "审批通过":
|
||||
inner_frame.get_by_role("button", name="修改").click()
|
||||
save_button_locator = inner_frame.get_by_role("button", name="保存")
|
||||
@@ -163,7 +173,6 @@ class DiscreteMaterialPlanCleaner:
|
||||
|
||||
inner_frame.get_by_text("展开").first.click()
|
||||
|
||||
|
||||
# 获取展开后的父容器,基于它定位子元素更加精确
|
||||
# 父元素 class="card-table-side-box undefined"
|
||||
child_form = inner_frame.locator(".card-table-side-box")
|
||||
@@ -171,7 +180,6 @@ class DiscreteMaterialPlanCleaner:
|
||||
child_form.wait_for(state="visible", timeout=5000)
|
||||
self._print(f"父容器 .card-table-side-box 已找到")
|
||||
|
||||
|
||||
page2.pause()
|
||||
for id in range(detail_count):
|
||||
id_lable_locator = child_form.get_by_text("序号 " + str(id + 1))
|
||||
@@ -179,20 +187,37 @@ class DiscreteMaterialPlanCleaner:
|
||||
self._print(f"处理 {id_lable_locator.inner_text()} ")
|
||||
|
||||
# 获取材料编码(通过文本定位,取第一个input)
|
||||
input_box = child_form.locator("div").filter(has_text=re.compile(r"^材料编码\d{11}$", re.MULTILINE)).locator("input").first
|
||||
input_box = (
|
||||
child_form.locator("div")
|
||||
.filter(has_text=re.compile(r"^材料编码\d{11}$", re.MULTILINE))
|
||||
.locator("input")
|
||||
.first
|
||||
)
|
||||
self._print(f"材料编码:{input_box.input_value()}")
|
||||
|
||||
# 获取材料名称
|
||||
input_box = child_form.locator("div").filter(has_text=re.compile(r"^材料名称$")).locator("input[type='text']")
|
||||
input_box = (
|
||||
child_form.locator("div")
|
||||
.filter(has_text=re.compile(r"^材料名称$"))
|
||||
.locator("input[type='text']")
|
||||
)
|
||||
material_name = input_box.input_value()
|
||||
self._print(f"材料名称:{material_name}")
|
||||
|
||||
# 获取累计待发数量
|
||||
input_box = child_form.locator("div").filter(has_text=re.compile(r"^累计待发数量$")).locator("input[type='text']")
|
||||
input_box = (
|
||||
child_form.locator("div")
|
||||
.filter(has_text=re.compile(r"^累计待发数量$"))
|
||||
.locator("input[type='text']")
|
||||
)
|
||||
self._print(f"累计待发数量:{input_box.input_value()}")
|
||||
|
||||
# 获取累计出库数量
|
||||
input_box = child_form.locator("div").filter(has_text=re.compile(r"^累计出库数量$")).locator("input[type='text']")
|
||||
input_box = (
|
||||
child_form.locator("div")
|
||||
.filter(has_text=re.compile(r"^累计出库数量$"))
|
||||
.locator("input[type='text']")
|
||||
)
|
||||
self._print(f"累计出库数量:{input_box.input_value()}")
|
||||
|
||||
# 检查是否需要清理该物料
|
||||
@@ -205,16 +230,22 @@ class DiscreteMaterialPlanCleaner:
|
||||
break
|
||||
|
||||
if should_delete:
|
||||
self._print(f">>> 需要清理:材料名称【{material_name}】匹配关键字【{matched_keyword}】")
|
||||
self._print(
|
||||
f">>> 需要清理:材料名称【{material_name}】匹配关键字【{matched_keyword}】"
|
||||
)
|
||||
# TODO: 执行删除操作
|
||||
else:
|
||||
self._print(f"保留:材料名称【{material_name}】无需清理")
|
||||
|
||||
if id != detail_count - 1:
|
||||
child_form.get_by_role("button").filter(has_text=re.compile(r"^$")).nth(2).click()
|
||||
child_form.get_by_role("button").filter(
|
||||
has_text=re.compile(r"^$")
|
||||
).nth(2).click()
|
||||
else:
|
||||
child_form.get_by_role("button").filter(has_text=re.compile(r"^$")).nth(4).click()
|
||||
#page2.pause()
|
||||
child_form.get_by_role("button").filter(
|
||||
has_text=re.compile(r"^$")
|
||||
).nth(4).click()
|
||||
# page2.pause()
|
||||
|
||||
elif detail_count == 0:
|
||||
self._print(f"第 {order_index + 1} 个订单无数据需要清理,跳过...")
|
||||
@@ -225,11 +256,6 @@ class DiscreteMaterialPlanCleaner:
|
||||
page2.close()
|
||||
return
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
page2.close()
|
||||
time.sleep(1)
|
||||
pass
|
||||
@@ -255,9 +281,13 @@ class DiscreteMaterialPlanCleaner:
|
||||
self._print(f"文本框填充成功: {expected_value}")
|
||||
break
|
||||
else:
|
||||
self._print(f"第 {attempt + 1} 次填充失败,实际值: {actual_value},重试...")
|
||||
self._print(
|
||||
f"第 {attempt + 1} 次填充失败,实际值: {actual_value},重试..."
|
||||
)
|
||||
if attempt == max_retries - 1:
|
||||
self._print(f"警告: {max_retries} 次尝试后仍未成功填充,继续执行...")
|
||||
self._print(
|
||||
f"警告: {max_retries} 次尝试后仍未成功填充,继续执行..."
|
||||
)
|
||||
|
||||
def clean(self, production_id_file, debug_mode=False, debug_order=None):
|
||||
"""
|
||||
@@ -280,7 +310,7 @@ class DiscreteMaterialPlanCleaner:
|
||||
username=self.username,
|
||||
password=self.password,
|
||||
headless=self.headless,
|
||||
ignore_https_errors=True
|
||||
ignore_https_errors=True,
|
||||
)
|
||||
|
||||
self._print("=" * 80)
|
||||
@@ -310,10 +340,17 @@ class DiscreteMaterialPlanCleaner:
|
||||
|
||||
# 按订单清理
|
||||
for order_index, order_id in enumerate(order_ids):
|
||||
self._print(f"\n=== 开始处理第 {order_index + 1} 个订单,订单号: {order_id} ===")
|
||||
self._print(
|
||||
f"\n=== 开始处理第 {order_index + 1} 个订单,订单号: {order_id} ==="
|
||||
)
|
||||
self.process_order(
|
||||
inner_frame, order_id, order_index, page1, materials_to_delete,
|
||||
debug_mode=debug_mode, debug_order=debug_order
|
||||
inner_frame,
|
||||
order_id,
|
||||
order_index,
|
||||
page1,
|
||||
materials_to_delete,
|
||||
debug_mode=debug_mode,
|
||||
debug_order=debug_order,
|
||||
)
|
||||
|
||||
# 执行账号注销
|
||||
@@ -334,7 +371,7 @@ def main():
|
||||
password="Cqbld123456.",
|
||||
manager_name="彭羽",
|
||||
headless=False,
|
||||
verbose=True
|
||||
verbose=True,
|
||||
)
|
||||
|
||||
production_id_file = os.path.join(os.path.dirname(__file__), "productionID.txt")
|
||||
|
||||
Reference in New Issue
Block a user