feat: 打卡记录拉取/缺卡统计工具(iEPMS token直连, 无需签名)
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
"""PunchLog command-line tool.
|
||||
|
||||
Usage examples:
|
||||
python -m punchlog # 当月记录 + 今日提醒 + 缺卡统计
|
||||
python -m punchlog --month 2026-10 # 指定月份
|
||||
python -m punchlog --start 2026-10-01 --end 2026-10-31
|
||||
python -m punchlog --csv out.csv # 同时导出明细 CSV
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from .analyze import daily_summaries, today_status, problems, STATUS_OK
|
||||
from .config import config_from_env
|
||||
from .iepms import IepmsClient
|
||||
|
||||
|
||||
def _month_range(month: str) -> tuple[str, str]:
|
||||
y, m = (int(x) for x in month.split("-"))
|
||||
start = date(y, m, 1)
|
||||
nxt = date(y + (m == 12), (m % 12) + 1, 1)
|
||||
end = nxt - timedelta(days=1)
|
||||
return start.isoformat(), end.isoformat()
|
||||
|
||||
|
||||
def _default_month() -> str:
|
||||
return datetime.now().strftime("%Y-%m")
|
||||
|
||||
|
||||
def _fmt_t(dt) -> str:
|
||||
return dt.strftime("%H:%M:%S") if dt else "-"
|
||||
|
||||
|
||||
def _memo_oneline(rec: dict) -> str:
|
||||
return " / ".join(x.strip() for x in (rec.get("memo") or "").replace("\r", "\n").split("\n") if x.strip())
|
||||
|
||||
|
||||
def print_table(summaries) -> None:
|
||||
print(f"{'日期':<12}{'次数':>4} {'最早':<9}{'最晚':<9}{'时长h':>6} {'状态':<18}站点 / 打卡内容")
|
||||
print("-" * 110)
|
||||
for s in summaries:
|
||||
rec = s.records[-1] if s.records else {}
|
||||
site = (rec.get("siteName") or "").strip()
|
||||
memo = _memo_oneline(rec)
|
||||
extra = (site[:16] + "… " if site else "") + memo
|
||||
print(f"{s.day.isoformat():<12}{s.count:>4} {_fmt_t(s.first):<9}{_fmt_t(s.last):<9}"
|
||||
f"{s.hours:>6.1f} {s.status:<18}{extra[:60]}")
|
||||
|
||||
|
||||
def export_csv(rows: list[dict], path: str) -> None:
|
||||
cols = ["signDate", "signType", "distance", "siteCode", "siteName", "memo", "phoneSubmitTime", "status"]
|
||||
with open(path, "w", newline="", encoding="utf-8-sig") as f:
|
||||
w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore")
|
||||
w.writeheader()
|
||||
for r in sorted(rows, key=lambda x: x.get("signDate") or ""):
|
||||
w.writerow({k: r.get(k, "") for k in cols})
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
p = argparse.ArgumentParser(prog="punchlog", description="个人打卡记录与缺卡统计")
|
||||
p.add_argument("--month", help="月份 YYYY-MM(默认当月)")
|
||||
p.add_argument("--start", help="起始日期 YYYY-MM-DD")
|
||||
p.add_argument("--end", help="结束日期 YYYY-MM-DD", default="")
|
||||
p.add_argument("--csv", help="导出明细 CSV 到指定路径")
|
||||
p.add_argument("--env", help=".env 路径")
|
||||
return p
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
if args.start:
|
||||
start, end = args.start, args.end
|
||||
else:
|
||||
start, end = _month_range(args.month or _default_month())
|
||||
|
||||
cfg = config_from_env(args.env)
|
||||
client = IepmsClient(cfg)
|
||||
rows = client.fetch_all(start, end)
|
||||
|
||||
summaries = daily_summaries(rows)
|
||||
print(f"\n== 打卡记录 {start} ~ {end or '今'}({len(rows)} 条, {len(summaries)} 天)==")
|
||||
print_table(summaries)
|
||||
|
||||
# 今日提醒
|
||||
today = date.today()
|
||||
today_in_range = start <= today.isoformat() <= (end or "9999")
|
||||
print("\n== 今日提醒 ==")
|
||||
if not today_in_range:
|
||||
print(f"(所选区间 {start}~{end or '今'} 不含今日 {today.isoformat()},跳过今日提醒)")
|
||||
else:
|
||||
ts = today_status(rows, today)
|
||||
if ts is None:
|
||||
print("⚠ 今天还没有打卡记录!")
|
||||
elif ts.status == STATUS_OK:
|
||||
print(f"✓ 今日已打卡 {ts.count} 次,{_fmt_t(ts.first)}~{_fmt_t(ts.last)}({ts.hours:.1f}h),{ts.status}")
|
||||
else:
|
||||
print(f"⚠ 今日打卡 {ts.count} 次,{_fmt_t(ts.first)}~{_fmt_t(ts.last)}({ts.hours:.1f}h),{ts.status}")
|
||||
|
||||
# 缺卡统计
|
||||
probs = problems(rows)
|
||||
print(f"\n== 缺卡/不足统计({len(probs)} 天)==")
|
||||
if not probs:
|
||||
print("✓ 区间内无缺卡/时间不足。")
|
||||
for s in probs:
|
||||
print(f" {s.day.isoformat()} {s.status} 次数={s.count} 时长={s.hours:.1f}h "
|
||||
f"({_fmt_t(s.first)}~{_fmt_t(s.last)})")
|
||||
|
||||
if args.csv:
|
||||
export_csv(rows, args.csv)
|
||||
print(f"\n明细已导出: {args.csv}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user