Files
37duAutomation/plugins/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/logic/target_file.py
T

156 lines
7.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""XQ0033 插件 - 积分工作簿目标文件选择。
文件名 = 前缀 + 积分日期段(如 1009 单日 / 1011-12 跨日)。
优先复用文件名含 T-2 的文件(续用追加);否则复制「积分日期最大」的文件另存为
「前缀{T-2 MMDD}.xlsx」作为新批(积分导入/删除表由调用方清空重写;不按 mtime 选,
批次文件被 WPS 另存后 mtime 会变新,容易拿错上轮文件)。
另提供 pick_prev_file:按文件名日期段找含 T-3 的上轮文件,其「今日导出」作为本批前一日快照。
"""
import os
import re
import shutil
from datetime import date, datetime, timedelta
from .. import config
def parse_name_dates(filename, year=None):
"""从文件名解析积分日期段集合 → {date}(跨日按起止展开为逐日)。"""
stem = os.path.splitext(filename)[0]
if stem.startswith(config.FILE_PREFIX):
stem = stem[len(config.FILE_PREFIX):]
year = year or date.today().year
dates = set()
first_month = None
for seg in stem.split("-"):
seg = seg.strip()
if re.fullmatch(r"\d{4}", seg):
m, d = int(seg[:2]), int(seg[2:])
if 1 <= m <= 12 and 1 <= d <= 31:
first_month = m
dates.add(date(year, m, d))
elif re.fullmatch(r"\d{2}", seg) and first_month is not None:
d = int(seg)
if 1 <= d <= 31:
dates.add(date(year, first_month, d))
if len(dates) > 1:
lo, hi = min(dates), max(dates)
span, cur = set(), lo
while cur <= hi:
span.add(cur)
cur += timedelta(days=1)
dates = span
return dates
def pick_latest_file(save_dir, force_file=None):
"""仅推送时使用:取目录内积分日期最大的批次文件(同日再比 mtime,不新建批次)。
按日期而非 mtime:批次文件被 WPS 打开另存后 mtime 会变新,按 mtime 会推错文件。
"""
if force_file:
if not os.path.isfile(force_file):
raise FileNotFoundError(f"指定的工作簿不存在:{force_file}")
return os.path.abspath(force_file)
if not os.path.isdir(save_dir):
raise FileNotFoundError(f"工作簿目录不存在:{save_dir}")
files = [f for f in os.listdir(save_dir)
if f.startswith(config.FILE_PREFIX) and f.endswith(".xlsx")
and not f.startswith("~$")]
if not files:
raise FileNotFoundError(f"目录 {save_dir} 未找到「{config.FILE_PREFIX}*.xlsx」文件")
def _key(f):
ds = parse_name_dates(f)
return (max(ds) if ds else date.min, os.path.getmtime(os.path.join(save_dir, f)))
return os.path.join(save_dir, max(files, key=_key))
def pick_target_file(today, save_dir, force_file=None):
"""选择本轮写入的积分工作簿 → (绝对路径, 是否新建批次文件, 上轮已处理的积分日期)。
第三个返回值取「被复制批次文件名里的最大日期」,用于识别两次运行之间漏处理的日期;
指定工作簿时来源不可信,返回 None(不做补漏推断)。
"""
if force_file:
if not os.path.isfile(force_file):
raise FileNotFoundError(f"指定的工作簿不存在:{force_file}")
return os.path.abspath(force_file), False, None
if not os.path.isdir(save_dir):
raise FileNotFoundError(f"工作簿目录不存在:{save_dir}")
locks = [f for f in os.listdir(save_dir)
if f.startswith("~$") and f.endswith(".xlsx")]
if locks:
raise RuntimeError(
"检测到 WPS/Excel 锁文件(%s),目标文件正被打开,请先关闭后重试" % "、".join(locks))
t2 = today - timedelta(days=2)
# 文件名只有 MMDD、没有年份:按积分日期所在年份解析,跨年(1/1、1/2 运行时 T-2 在去年)才不会错配
files = [f for f in os.listdir(save_dir)
if f.startswith(config.FILE_PREFIX) and f.endswith(".xlsx")
and not f.startswith("~$") and parse_name_dates(f, t2.year)]
if not files:
raise RuntimeError(
f"目录 {save_dir} 下未找到「{config.FILE_PREFIX}MMDD.xlsx」格式数据文件,"
"请先放入模板文件")
for f in files:
if t2 not in parse_name_dates(f, t2.year):
continue
path = os.path.join(save_dir, f)
# MMDD 无年份:往年同名批次(如去年 1230)不能误当本轮续用,按修改时间年份校验
if datetime.fromtimestamp(os.path.getmtime(path)).year != t2.year:
continue
config.logger.info("命中文件名含 T-2(%s) 的数据文件:%s(续用追加模式)",
t2.strftime("%m%d"), f)
return path, False, t2
# 复制源按「文件名积分日期最大」取,而不是按 mtime:批次文件被 WPS 打开另存后
# mtime 会变新,按 mtime 取会拿到更早的批次(上一轮快照随之错位)。同日多份再比 mtime。
newest = max(files, key=lambda f: (max(parse_name_dates(f, t2.year)),
os.path.getmtime(os.path.join(save_dir, f))))
src_dates = parse_name_dates(newest, t2.year)
covered_until = max(src_dates) if src_dates else None
new_name = f"{config.FILE_PREFIX}{t2.strftime('%m%d')}.xlsx"
new_path = os.path.join(save_dir, new_name)
if os.path.exists(new_path):
config.logger.warning("新批文件 %s 已存在但文件名未匹配 T-2,直接复用", new_name)
return new_path, False, covered_until
shutil.copy2(os.path.join(save_dir, newest), new_path)
config.logger.info("未找到文件名含 T-2 的文件,已从积分日期最大的文件 %s 复制新建批次文件:%s"
"(上轮积分日期推断为 %s)",
newest, new_name, covered_until or "未知")
return new_path, True, covered_until
def pick_prev_file(save_dir, prev_day):
"""上一轮批次文件:文件名积分日期段包含 prev_day(= T-3)的那个文件,同日多份取 mtime 最新。
用它里面的「考勤--今日导出」作为本批「考勤-前一日导出」,比「复制本文件旧快照」更稳:
- 目录里旧文件被 WPS 另存后 mtime 会变新,按日期取才取得到真正的上一轮;
- 同一天重跑时本文件快照已被上一轮改写,按日期取则始终是上一轮那份,
差值可复现(重跑幂等),月头补导入行不会因为重跑而消失。
找不到(跳天断档、文件被删)返回 None,由调用方退化为「文件内快照平滚」。
"""
if not save_dir or not os.path.isdir(save_dir):
return None
cands = []
for f in os.listdir(save_dir):
if f.startswith("~$") or not f.endswith(".xlsx") or not f.startswith(config.FILE_PREFIX):
continue
if prev_day not in parse_name_dates(f, prev_day.year):
continue
path = os.path.join(save_dir, f)
# MMDD 无年份:往年同名批次(如去年同日的 File)不能当上轮快照
if datetime.fromtimestamp(os.path.getmtime(path)).year != prev_day.year:
continue
cands.append(path)
if not cands:
return None
return max(cands, key=os.path.getmtime)