Files
37duAutomation/plugins/XQ0001-0100/XQ0041 新美大平台核对/data/share_copy.py
T
puddy e4be289835 feat(xq0041): 美团/抖音核对迁出至 XQ0085,保留导表与到账统计核对(v1.3.13)
download=只导打款/团购/预订收益明细;check_settlement=到账统计核对(并台账/门店归属/更新核对统计);金色印象与金色湖畔独立浏览器档案;新增 CRM 门店映射、基础信息同步与贴总表逻辑。
2026-11-26 09:28:32 +08:00

191 lines
7.6 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 -*-
"""从共享盘复制「昨天」的表到本地副本(**共享盘全程只读,绝不回写**)。
源在共享盘,目标在本机 ``WORK_DIR/_work/``,文件名日期同步替换::
源(共享盘,只读)
1111/TG/2026年11月/11.10/美团11.10.xlsx
1111/TG/2026年11月/11.10/马敏团购总表11.10.xlsx
目标(本地副本)
D:\\资料\\财务\\新美大平台核对\\_work\\美团11.11.xlsx
D:\\资料\\财务\\新美大平台核对\\_work\\马敏团购总表11.11.xlsx
两张表复制到本地后,后续所有处理(明细贴表、报表写值)都只改本地副本。
要点:
* **按日期取表**:源文件优先按 ``{关键词}{月}.{日}.xlsx`` 精确匹配;
匹配不到再在该日目录里取关键词命中的唯一 xlsx(人工临时改过名的场景);
* **跨月自动回退**:1 号的「昨天」在上个月的目录,月份目录按源日期算;
* **幂等**:本地目标已存在且非空就跳过,重复运行不会覆盖当天已处理的数据;
* **不依赖第三方库**:UNC 路径用标准库只读打开 + 本地写入,缺少凭据时给出提示。
"""
import os
import shutil
from datetime import date, datetime, timedelta
from .. import config
def _parse_day(value):
"""``date`` / ``datetime`` / 'YYYY-MM-DD' 统一成 date;无法解析返回 None。"""
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
text = str(value or '').strip()[:10]
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
try:
return datetime.strptime(text, fmt).date()
except ValueError:
continue
return None
def month_dir(root, day):
"""月份目录:``2026年11月``。"""
return os.path.join(root, f'{day.year}年{day.month}月')
def day_dir(root, day):
"""日期目录:``11.10``(不补零,与共享盘现有命名一致)。"""
return os.path.join(month_dir(root, day), f'{day.month}.{day.day}')
def table_name(keyword, day, ext):
"""核对表文件名:``美团11.10.xlsx``。"""
return f'{keyword}{day.month}.{day.day}{ext}'
def _list_tables(folder, keyword, ext):
"""列出目录里关键词 + 后缀命中的 xlsx(排除 Excel 临时文件 ``~$``)。"""
try:
names = os.listdir(folder)
except OSError:
return []
out = []
for name in names:
low = name.lower()
if name.startswith('~$') or not low.endswith(ext.lower()):
continue
if keyword and keyword not in name:
continue
out.append(name)
return sorted(out)
def _pick_source(folder, keyword, prev_day, ext):
"""在昨天目录里挑源文件:先精确日期,再退化为目录内唯一命中的表。"""
exact = os.path.join(folder, table_name(keyword, prev_day, ext))
if os.path.isfile(exact):
return exact
candidates = _list_tables(folder, keyword, ext)
if len(candidates) == 1:
return os.path.join(folder, candidates[0])
return ''
def copy_prev_table(share_root='', keyword='', ext='', day=None, local_dir='', dry_run=False):
"""从共享盘昨天目录复制一张表到本地副本(文件名日期同步替换)。
Args:
share_root: 共享根(只读,默认 :data:`config.SHARE_CHECK_ROOT`)
keyword: 文件名关键词(默认 :data:`config.SHARE_TABLE_KEYWORD`,如「美团」)
ext: 后缀(默认 :data:`config.SHARE_TABLE_EXT`)
day: 目标日期(默认今天)
local_dir: 本地副本目录(默认 ``WORK_DIR/_work``,共享盘只读不写入)
dry_run: 只检查不复制
Returns:
``{"ok", "message", "src", "dst", "skipped"}``
"""
root = str(share_root or config.SHARE_CHECK_ROOT).strip().strip('"').rstrip('\\/')
kw = str(keyword or config.SHARE_TABLE_KEYWORD).strip()
suffix = str(ext or config.SHARE_TABLE_EXT).strip()
if suffix and not suffix.startswith('.'):
suffix = '.' + suffix
target = _parse_day(day) or date.today()
prev = target - timedelta(days=1)
src_path = _pick_source(day_dir(root, prev), kw, prev, suffix)
dst_dir = str(local_dir or os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR))
dst_path = os.path.join(dst_dir, table_name(kw, target, suffix))
result = {'ok': False, 'message': '', 'src': src_path, 'dst': dst_path, 'skipped': False}
if not src_path:
folder = day_dir(root, prev)
found = _list_tables(folder, kw, suffix)
result['message'] = (
f'共享盘 {folder} 下没有找到 {kw}*{suffix}'
+ (f'(现有:{"、".join(found)})' if found else
';若共享盘未连接,请先确认当前机器能访问 ' + root))
return result
if os.path.isfile(dst_path) and os.path.getsize(dst_path) > 0:
result.update(ok=True, skipped=True,
message=f'本地副本已存在,跳过复制:'
f'{os.path.basename(dst_path)}')
return result
if dry_run:
result.update(ok=True, message=f'[演练] 将复制 {os.path.basename(src_path)} → '
f'{dst_path}')
return result
try:
os.makedirs(dst_dir, exist_ok=True)
shutil.copy2(src_path, dst_path)
except OSError as e:
tip = ''
if getattr(e, 'winerror', None) in (53, 67, 64, 1219, 1326):
tip = '(共享盘网络路径不可达 / 缺少凭据,请确认本机已能访问该共享)'
result['message'] = f'复制失败:{e}{tip}'
return result
if not os.path.isfile(dst_path) or os.path.getsize(dst_path) == 0:
result['message'] = f'复制后本地副本缺失或为空:{dst_path}'
return result
result.update(ok=True, message=f'已从共享盘复制 {os.path.basename(src_path)} → '
f'本地 {os.path.basename(dst_path)}')
return result
def copy_prev_tables(share_root='', day=None, local_dir='', dry_run=False):
"""把昨天的核对表 + 马敏团购总表一起拉到本地副本(共享盘只读)。
源文件在共享盘 ``{share_root}/{年}月/{月}.{日}/``,本地目标在 ``WORK_DIR/_work/``:
* 核对表:``美团11.10.xlsx`` → 本地 ``美团11.11.xlsx``
* 共享总表:``马敏团购总表11.10.xlsx`` → 本地 ``马敏团购总表11.11.xlsx``
Args:
share_root: 共享根(只读,默认 :data:`config.SHARE_CHECK_ROOT`)
day: 目标日期(默认今天;传「核对营业日」时按指定日期)
local_dir: 本地副本目录(默认 ``WORK_DIR/_work``)
dry_run: 只检查不复制
Returns:
``{"ok", "message", "tables": [...], "copied", "skipped", "failed"}``
"""
jobs = (
('核对表', config.SHARE_TABLE_KEYWORD, config.SHARE_TABLE_EXT),
('共享总表', config.LINK_BOOK, config.SHARE_TABLE_EXT),
)
tables = []
for label, keyword, ext in jobs:
item = copy_prev_table(share_root=share_root, keyword=keyword, ext=ext,
day=day, local_dir=local_dir, dry_run=dry_run)
item['label'] = label
tables.append(item)
failed = [t for t in tables if not t.get('ok')]
return {
'ok': not failed,
'message': ';'.join(f'{t["label"]}:{t["message"]}' for t in tables),
'tables': tables,
'copied': sum(1 for t in tables if t.get('ok') and not t.get('skipped')),
'skipped': sum(1 for t in tables if t.get('skipped')),
'failed': len(failed),
}