dingdanquanliucheng/backend/app/services/export_service.py

45 lines
1.6 KiB
Python
Raw Normal View History

import csv
from datetime import datetime
from pathlib import Path
class ExportService:
def __init__(self) -> None:
self.export_root = Path("D:/tmp/order-flow-exports")
self.export_root.mkdir(parents=True, exist_ok=True)
def build_performance_export(self, report: dict) -> dict:
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
suffix = report["stat_type"]
file_name = f"performance-{suffix}-{timestamp}.csv"
file_path = self.export_root / file_name
with file_path.open("w", encoding="utf-8-sig", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["统计周期", "订单数", "订单金额", "固定提成", "分类明细"])
for item in report["list"]:
category_text = "".join(
f"{category['category_name']}:{category['amount']:.2f}"
for category in item.get("category_amounts", [])
)
writer.writerow(
[
item["stat_period"],
item["order_count"],
f"{item['order_amount']:.2f}",
f"{item['commission_amount']:.2f}",
category_text,
]
)
return {
"file_name": file_name,
"file_path": str(file_path),
"file_size": file_path.stat().st_size,
"content_type": "text/csv",
"object_key": f"exports/performance/{file_name}",
}
export_service = ExportService()