124 lines
5.1 KiB
Python
124 lines
5.1 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""账户列表读写(对应影刀自定义指令 mjqywawyv「读取账户列表」与 m8k8hi9j8「按门店+列名写单元格」)。
|
||
|
||
账户列表.xlsx 约定(与影刀版一致):
|
||
A列=门店 B列=税号 C列=密码 E列=执行标记(0=待执行,1=已完成/跳过)
|
||
只处理 E 列为 "0" 的行;E 列既非 0 也非 1(含空)→ 跳过。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
from typing import List
|
||
|
||
import pandas as pd
|
||
|
||
from ..config import (
|
||
COL_FLAG, COL_PASSWORD, COL_STORE, COL_TAX_NO, FLAG_DONE, FLAG_PENDING, logger,
|
||
)
|
||
|
||
|
||
def _is_empty(val) -> bool:
|
||
if pd.isna(val):
|
||
return True
|
||
return str(val).strip() == ""
|
||
|
||
|
||
def load_accounts(file_path: str) -> List[dict]:
|
||
"""读取账户列表,返回待执行账户 [{"store","tax_no","password","row"}]。
|
||
|
||
数据不一致(E列=0 但门店/税号/密码为空)直接报错,避免跑错账户。
|
||
"""
|
||
if not os.path.isfile(file_path):
|
||
raise RuntimeError(f"未找到账户列表:{file_path}")
|
||
try:
|
||
df = pd.read_excel(file_path, engine="openpyxl", dtype=str)
|
||
except PermissionError as e:
|
||
raise RuntimeError(f"账户列表被占用,请先关闭 Excel:{file_path}") from e
|
||
except Exception as e: # noqa: BLE001
|
||
raise RuntimeError(f"读取账户列表失败:{file_path}({e})") from e
|
||
|
||
if len(df.columns) <= COL_FLAG:
|
||
raise RuntimeError(
|
||
f"账户列表列数不完整:需要至少 {COL_FLAG + 1} 列(A门店/B税号/C密码/E执行标记),"
|
||
f"当前 {len(df.columns)} 列")
|
||
|
||
out: List[dict] = []
|
||
for idx, row in df.iterrows():
|
||
flag = "" if pd.isna(row.iloc[COL_FLAG]) else str(row.iloc[COL_FLAG]).strip()
|
||
if flag == FLAG_DONE:
|
||
continue
|
||
if flag != FLAG_PENDING:
|
||
continue # 非 0/1 一律跳过(含空值与历史脏数据)
|
||
store = str(row.iloc[COL_STORE]).strip() if not _is_empty(row.iloc[COL_STORE]) else ""
|
||
tax_no = str(row.iloc[COL_TAX_NO]).strip() if not _is_empty(row.iloc[COL_TAX_NO]) else ""
|
||
password = str(row.iloc[COL_PASSWORD]).strip() if not _is_empty(row.iloc[COL_PASSWORD]) else ""
|
||
excel_row = idx + 2 # 表头占 1 行
|
||
if not (store and tax_no and password):
|
||
raise RuntimeError(
|
||
f"账户列表第 {excel_row} 行 E 列标记为待执行,但门店/税号/密码存在空值")
|
||
out.append({"store": store, "tax_no": tax_no, "password": password, "row": excel_row})
|
||
|
||
if not out:
|
||
raise RuntimeError(f"账户列表筛选后没有待执行账户(E 列没有值为 {FLAG_PENDING} 的行):{file_path}")
|
||
logger.info("账户列表读取完成:待执行 %d 家门店", len(out))
|
||
return out
|
||
|
||
|
||
def update_cell(file_path: str, store: str, column_name: str, content) -> None:
|
||
"""按门店(A列)与列名(表头)写入单元格;列或行不存在则自动新增(影刀同款行为)。"""
|
||
from openpyxl import Workbook, load_workbook # 延迟导入,减少不用时的开销
|
||
|
||
if not column_name or not store:
|
||
raise ValueError("门店名称与列名不能为空")
|
||
if not str(file_path).lower().endswith(".xlsx"):
|
||
raise ValueError(f"账户列表必须是 .xlsx:{file_path}")
|
||
|
||
parent = os.path.dirname(os.path.abspath(file_path))
|
||
if parent:
|
||
os.makedirs(parent, exist_ok=True)
|
||
|
||
if os.path.exists(file_path):
|
||
wb = load_workbook(file_path)
|
||
ws = wb.active
|
||
else:
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.cell(row=1, column=1).value = "门店"
|
||
|
||
# 定位列
|
||
target_col = None
|
||
for col in range(1, ws.max_column + 1):
|
||
if ws.cell(row=1, column=col).value == column_name:
|
||
target_col = col
|
||
break
|
||
if target_col is None:
|
||
target_col = ws.max_column + 1
|
||
ws.cell(row=1, column=target_col).value = column_name
|
||
|
||
# 定位行
|
||
target_row = None
|
||
for row in range(2, ws.max_row + 1):
|
||
if str(ws.cell(row=row, column=1).value) == str(store):
|
||
target_row = row
|
||
break
|
||
if target_row is None:
|
||
target_row = ws.max_row + 1
|
||
ws.cell(row=target_row, column=1).value = store
|
||
|
||
ws.cell(row=target_row, column=target_col).value = content
|
||
try:
|
||
wb.save(file_path)
|
||
except PermissionError as e:
|
||
raise RuntimeError(f"账户列表被占用,无法写入,请先关闭 Excel:{file_path}") from e
|
||
logger.info("已回写账户列表:%s | %s = %s", store, column_name, content)
|
||
|
||
|
||
def mark_done(file_path: str, store: str, column_name: str = "执行状态") -> None:
|
||
"""标记门店执行完成(默认写「执行状态」列=1)。"""
|
||
update_cell(file_path, store, column_name, FLAG_DONE)
|
||
|
||
|
||
def mark_failed(file_path: str, store: str, reason: str, column_name: str = "失败原因") -> None:
|
||
"""记录失败原因(不写执行状态,便于人工重跑)。"""
|
||
update_cell(file_path, store, column_name, reason)
|