CaiWuXiTong/scripts/erp-daily-bills/xiaohongshu-summary.py

105 lines
3.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.

"""流式汇总聚水潭小红书订单结算明细,供每日导入前核验。"""
import argparse
import json
from datetime import datetime
from decimal import Decimal, InvalidOperation
from openpyxl import load_workbook
REQUIRED_HEADERS = (
"记录编码",
"收入金额",
"支出金额",
"结算时间",
)
def text(value):
return "" if value is None else str(value).strip()
def money(value):
raw = text(value).replace(",", "").replace(",", "").replace("¥", "").replace("¥", "")
try:
return Decimal(raw or "0")
except InvalidOperation as error:
raise ValueError(f"无效金额:{value!r}") from error
def date_time(value):
if isinstance(value, datetime):
return value
raw = text(value)
for format_string in ("%Y-%m-%d %H:%M:%S", "%Y/%m/%d %H:%M:%S", "%Y-%m-%d", "%Y/%m/%d"):
try:
return datetime.strptime(raw, format_string)
except ValueError:
continue
raise ValueError(f"无效结算时间:{value!r}")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("path")
parser.add_argument("--from", dest="from_date", default=None)
parser.add_argument("--to", dest="to_date", default=None)
args = parser.parse_args()
workbook = load_workbook(args.path, read_only=True, data_only=True)
try:
sheet = workbook[workbook.sheetnames[0]]
rows = sheet.iter_rows(values_only=True)
headers = [text(value) for value in next(rows)]
missing = [header for header in REQUIRED_HEADERS if header not in headers]
if missing:
raise ValueError("缺少小红书账单表头:" + "、".join(missing))
indexes = {header: headers.index(header) for header in REQUIRED_HEADERS}
count = 0
income = Decimal("0")
expense = Decimal("0")
occurred_min = None
occurred_max = None
seen_codes = set()
record_index = headers.index("记录编码")
for row in rows:
if not any(value not in (None, "") for value in row):
continue
code = text(row[record_index])
if not code:
raise ValueError("小红书账单存在空记录编码")
if code in seen_codes:
raise ValueError(f"小红书账单记录编码重复:{code}")
seen_codes.add(code)
occurred = date_time(row[indexes["结算时间"]])
occurred_text = occurred.strftime("%Y-%m-%d %H:%M:%S")
occurred_min = occurred_text if occurred_min is None or occurred_text < occurred_min else occurred_min
occurred_max = occurred_text if occurred_max is None or occurred_text > occurred_max else occurred_max
count += 1
income += money(row[indexes["收入金额"]])
expense += money(row[indexes["支出金额"]])
finally:
workbook.close()
if count == 0:
raise ValueError("小红书账单没有数据")
if args.from_date and occurred_min[:10] < args.from_date:
raise ValueError(f"结算时间 {occurred_min} 早于账期起点 {args.from_date}")
if args.to_date and occurred_max[:10] > args.to_date:
raise ValueError(f"结算时间 {occurred_max} 晚于账期终点 {args.to_date}")
print(json.dumps({
"rows": count,
"income": format(income, ".2f"),
"expense": format(expense, ".2f"),
"net": format(income - expense, ".2f"),
"occurred_min": occurred_min,
"occurred_max": occurred_max,
}, ensure_ascii=False))
if __name__ == "__main__":
main()