139 lines
5.2 KiB
Python
139 lines
5.2 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""从共享盘复制「昨天」的表到本地副本(**共享盘全程只读,绝不回写**)。
|
||
|
||
源在共享盘,目标在本机 ``WORK_DIR/_work/``,文件名日期同步替换::
|
||
|
||
源(共享盘,只读)
|
||
1111/TG/2026年11月/11.10/美团11.10.xlsx / 抖音11.10.xlsx
|
||
1111/TG/2026年11月/11.10/马敏团购总表11.10.xlsx
|
||
目标(本地副本)
|
||
D:\\资料\\财务\\新美大平台核对\\_work\\美团11.11.xlsx
|
||
D:\\资料\\财务\\新美大平台核对\\_work\\抖音11.11.xlsx
|
||
D:\\资料\\财务\\新美大平台核对\\_work\\马敏团购总表11.11.xlsx
|
||
|
||
两张核对表复制到本地后,后续所有处理都只改本地副本。
|
||
"""
|
||
import os
|
||
import re
|
||
import shutil
|
||
from datetime import date, datetime, timedelta
|
||
|
||
from .. import config
|
||
|
||
|
||
def _parse_day(value):
|
||
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 day_dir(root, day):
|
||
return os.path.join(root, f'{day.year}年{day.month}月', f'{day.month}.{day.day}')
|
||
|
||
|
||
def table_name(keyword, day, suffix='.xlsx'):
|
||
return f'{keyword}{day.month}.{day.day}{suffix}'
|
||
|
||
|
||
def _list_tables(folder, keyword, suffix):
|
||
try:
|
||
return sorted(f for f in os.listdir(folder)
|
||
if keyword in f and f.lower().endswith(suffix))
|
||
except OSError:
|
||
return []
|
||
|
||
|
||
def _pick_source(folder, keyword, day, suffix):
|
||
exact = os.path.join(folder, table_name(keyword, day, suffix))
|
||
if os.path.isfile(exact):
|
||
return exact
|
||
found = _list_tables(folder, keyword, suffix)
|
||
if len(found) == 1:
|
||
return os.path.join(folder, found[0])
|
||
return ''
|
||
|
||
|
||
def copy_prev_table(share_root='', keyword='', ext='', day=None, local_dir='', dry_run=False):
|
||
"""从共享盘昨天目录复制一张表到本地副本(文件名日期同步替换)。"""
|
||
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'本地副本已存在,跳过复制:{os.path.basename(dst_path)}')
|
||
return result
|
||
|
||
if dry_run:
|
||
result.update(ok=True, message=f'[演练] 将复制 {os.path.basename(src_path)} → {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, keywords=None, local_dir='', dry_run=False):
|
||
"""把昨天的核对表批量拉到本地副本(共享盘只读)。
|
||
|
||
Args:
|
||
keywords: 要复制的关键词列表,默认 ``[美团, 抖音, 马敏团购总表]``
|
||
"""
|
||
jobs = list(keywords or [config.SHARE_TABLE_KEYWORD, config.DOUYIN_SHARE_KEYWORD,
|
||
config.LINK_BOOK])
|
||
tables = []
|
||
for kw in jobs:
|
||
item = copy_prev_table(share_root=share_root, keyword=kw, ext=config.SHARE_TABLE_EXT,
|
||
day=day, local_dir=local_dir, dry_run=dry_run)
|
||
item['label'] = kw
|
||
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),
|
||
}
|