Files
37duAutomation/libs/hotel_report/hotel_report/exports.py
T
puddy 1664821117 restore: 恢复 11-06~11-09 本地未提交改动
- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto
- controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图
- electron-shell: 插件同步、注册表、runner 调整
- plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新
- tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
2026-11-09 17:27:10 +08:00

244 lines
10 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 -*-
"""对外编排层:一次调用 = 取数 + 渲染 + 落盘。
契约(对应设计文档 §6.5):
- 不接收 `ctx`,日志/进度/取消都由调用方以回调形式传入(可选);
- 不 `print`、不 `sys.exit()`、不读写 cwd 相对路径;
- 返回结构化结果字典,调用方自行决定怎么展示。
"""
from __future__ import annotations
import os
from datetime import date, datetime, timedelta
from .collect import collect_member_balance, collect_member_detail, collect_sales, collect_shift
from .collect.shift_time import latest_shift as _latest_shift
from .config import HotelConfig
from .errors import CancelledError, DataError
from .render import (write_member_balance_xlsx, write_member_detail_xlsx,
write_sales_xlsx, write_shift_xlsx)
def _as_day(value, default: datetime | None = None) -> datetime:
"""把 'YYYY-MM-DD' / date / datetime 统一成当天 00:00。"""
if value in (None, ""):
return default or datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
if isinstance(value, datetime):
return value.replace(hour=0, minute=0, second=0, microsecond=0)
if isinstance(value, date):
return datetime(value.year, value.month, value.day)
return datetime.strptime(str(value).strip()[:10], "%Y-%m-%d")
def _emit(log, msg: str, level: str = "INFO") -> None:
if log:
log(msg, level)
def _tick(progress, pct: int) -> None:
if progress:
progress(int(pct))
def _check(should_cancel) -> None:
if should_cancel and should_cancel():
raise CancelledError("调用方请求取消")
def export_shift(cfg: HotelConfig | None = None, start=None, end=None,
out_path: str = "", *, runday: str = "", query=None,
log=None, progress=None, should_cancel=None) -> dict:
"""导出「交班查询」;`runday` 非空时按营业日口径,忽略 start/end。"""
cfg = cfg or HotelConfig()
s = _as_day(start)
e = _as_day(end, default=s)
_check(should_cancel)
_tick(progress, 5)
if runday:
_emit(log, f"取交班数据:营业日 {runday}")
else:
_emit(log, f"取交班数据:{s:%Y-%m-%d} ~ {e:%Y-%m-%d}")
table = collect_shift(s, e, cfg, query=query, runday=runday)
if table.count == 0:
_emit(log, "该区间没有总交班记录", "WARN")
return {"report": "交班查询", "count": 0, "path": "", "label": table.label,
"pay_methods": [], "empty": True}
_check(should_cancel)
_tick(progress, 60)
path = write_shift_xlsx(table, out_path)
_tick(progress, 100)
_emit(log, f"交班查询已导出:{table.count} 条 × 支付方式 {len(table.pay_methods)} 列 → {path}")
return {"report": "交班查询", "count": table.count, "path": path, "label": table.label,
"pay_methods": table.pay_methods, "totals": table.fixed_totals, "empty": False}
def export_sales(cfg: HotelConfig | None = None, start=None, end=None,
out_path: str = "", *, query=None,
log=None, progress=None, should_cancel=None) -> dict:
"""导出「销售明细」(35 列 + 合计行)。"""
cfg = cfg or HotelConfig()
s = _as_day(start)
e = _as_day(end, default=s)
_check(should_cancel)
_tick(progress, 5)
_emit(log, f"取销售明细:{s:%Y-%m-%d} ~ {e:%Y-%m-%d}")
table = collect_sales(s, e, cfg, query=query)
_check(should_cancel)
_tick(progress, 60)
path = write_sales_xlsx(table, out_path)
_tick(progress, 100)
_emit(log, f"销售明细已导出:{table.count} 行 → {path}")
return {"report": "销售明细", "count": table.count, "path": path, "label": table.label,
"empty": table.count == 0}
def export_daily(cfg: HotelConfig | None = None, day=None, out_path: str = "", *,
template: str = "", month=None, query=None, log=None, progress=None) -> dict:
"""导出「营业日报」(12 区块,骨架按数据库现场生成)。
实现放在 `hotel_report.daily`(体量大、与 legacy 口径逐条对齐),这里延迟导入,
不导出日报的调用方不会为它付出导入成本。
"""
from .daily import write_daily
return write_daily(cfg or HotelConfig(), day, out_path, template=template, month=month,
query=query, log=log, progress=progress)
def latest_shift_time(cfg: HotelConfig | None = None, day=None, *, query=None) -> dict:
"""取某天的最晚交班时间(营业日结算参考)。"""
return _latest_shift(_as_day(day), cfg or HotelConfig(), query=query)
def settle_window(cfg: HotelConfig | None = None, day=None, *, query=None) -> dict:
"""结算窗口 = **前一日最晚总交班 ~ 当日最晚总交班**。
营业日由交班切开,不用 00:00:零点会把上一营业日的尾巴算进来,且随补录数据变化。
返回 {day, start, end, prev_latest, latest, closed, label};
当日还没交班时 `closed=False`、`end=""`(此时不该出会员卡统计)。
"""
cfg = cfg or HotelConfig()
d = _as_day(day)
cur = _latest_shift(d, cfg, query=query)
prev = _latest_shift(d - timedelta(days=1), cfg, query=query)
end = cur.get("latest") or ""
start = prev.get("latest") or (d - timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
return {
"day": d.strftime("%Y-%m-%d"),
"start": start,
"end": end,
"prev_latest": prev.get("latest"),
"latest": end,
"closed": bool(end),
"label": "%s ~ %s" % (start, end or "当日尚未交班"),
}
def _member_window(window, cfg: HotelConfig, day, query) -> dict:
"""统一 window 入参:dict / (start, end) 元组 / 空(= 按 settle_window 现算)。"""
if not window:
return settle_window(cfg, day, query=query)
if isinstance(window, dict):
w = dict(window)
else:
w = {"start": str(window[0]), "end": str(window[1])}
w.setdefault("closed", bool(w.get("end")))
w.setdefault("label", "%s ~ %s" % (w.get("start", ""), w.get("end", "")))
return w
def _require_closed(w: dict) -> None:
if not w.get("end"):
raise DataError("%s 还没有交班记录,结算窗口未闭合:等夜审交班后再跑" % (w.get("day") or ""))
def export_member_balance(cfg: HotelConfig | None = None, window=None, out_path: str = "",
*, day=None, query=None, log=None, progress=None,
should_cancel=None) -> dict:
"""导出「会员卡余额」(截至窗口结束时间 `end` 的快照,一人一行)。"""
cfg = cfg or HotelConfig()
w = _member_window(window, cfg, day, query)
_require_closed(w)
_check(should_cancel)
_tick(progress, 5)
_emit(log, "取会员卡余额:截至 %s" % w["end"])
table = collect_member_balance(w["end"], cfg, query=query,
window=(w["start"], w["end"]))
_check(should_cancel)
_tick(progress, 85)
path = write_member_balance_xlsx(table, out_path)
_tick(progress, 100)
_emit(log, "会员卡余额已导出:%d 人,卡内余额合计 %.2f → %s"
% (table.count, table.totals.get("卡内余额", 0.0), path))
return {"report": "会员卡余额", "count": table.count, "path": path, "window": w,
"totals": table.totals, "label": table.label, "empty": table.count == 0}
def export_member_detail(cfg: HotelConfig | None = None, window=None, out_path: str = "",
*, day=None, query=None, log=None, progress=None,
should_cancel=None) -> dict:
"""导出「会员卡明细」(窗口内的充值/消费/调整流水,可见列跟随会员系统参数)。"""
cfg = cfg or HotelConfig()
w = _member_window(window, cfg, day, query)
_require_closed(w)
_check(should_cancel)
_tick(progress, 5)
_emit(log, "取会员卡明细:%s ~ %s" % (w["start"], w["end"]))
table = collect_member_detail(w["start"], w["end"], cfg, query=query,
window=(w["start"], w["end"]))
_check(should_cancel)
_tick(progress, 70)
path = write_member_detail_xlsx(table, out_path)
_tick(progress, 100)
_emit(log, "会员卡明细已导出:%d 行 × %d 列 → %s"
% (table.count, len(table.headers), path))
return {"report": "会员卡明细", "count": table.count, "path": path, "window": w,
"headers": table.headers, "pay_methods": table.pay_methods,
"empty": table.count == 0}
def export_member(cfg: HotelConfig | None = None, day=None, out_dir: str = "", *,
window=None, query=None, log=None, progress=None,
should_cancel=None) -> dict:
"""会员卡统计一次出两份:`会员卡余额_<日期>.xlsx` + `会员卡明细_<日期>.xlsx`。"""
cfg = cfg or HotelConfig()
w = _member_window(window, cfg, day, query)
_require_closed(w)
day_text = w.get("day") or _as_day(day).strftime("%Y-%m-%d")
stamp = day_text.replace("-", "")
_emit(log, "结算窗口:%s ~ %s" % (w["start"], w["end"]))
def _sub(base: float, span: float):
def _fn(pct):
_tick(progress, int(base + span * max(0, min(100, int(pct))) / 100.0))
return _fn
balance = export_member_balance(
cfg, w, os.path.join(out_dir, "会员卡余额_%s.xlsx" % stamp),
query=query, log=log, progress=_sub(5, 50), should_cancel=should_cancel)
detail = export_member_detail(
cfg, w, os.path.join(out_dir, "会员卡明细_%s.xlsx" % stamp),
query=query, log=log, progress=_sub(55, 45), should_cancel=should_cancel)
files = [p for p in (balance.get("path"), detail.get("path")) if p]
_tick(progress, 100)
return {"report": "会员卡统计", "window": w, "day": day_text, "files": files,
"path": files[0] if files else "", "balance": balance, "detail": detail,
"empty": balance.get("empty") and detail.get("empty")}
def date_range_for(ref_date=None, days: int = 1) -> tuple[datetime, datetime]:
"""常用区间助手:给一个参考日,返回连续 `days` 天的起止。"""
end = _as_day(ref_date)
start = end - timedelta(days=max(0, int(days) - 1))
return start, end