"""Inspect local sales data, then write the approved reports inside the workspace."""
import argparse
from collections import Counter, defaultdict
import csv
from datetime import date
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
import json
from pathlib import Path
from tempfile import TemporaryDirectory
HEADER = ("订单", "日期", "地区", "商品", "数量", "单价", "折扣", "销售额")
REGIONS = ("华东", "华南", "华北", "华中", "西南")
CENT = Decimal("0.01")
INPUTS = ("sales.csv", "sales-invalid.csv")
def money(value):
return str(value.quantize(CENT, rounding=ROUND_HALF_UP))
def audit(workspace, filename):
root = workspace.resolve(strict=True)
if filename not in INPUTS:
raise ValueError("请选择练习中登记的 CSV")
path = root / filename
if path.is_symlink() or path.resolve().parent != root:
raise ValueError("拒绝工作区之外的文件或符号链接")
findings, orders = [], []
with path.open(encoding="utf-8-sig", newline="") as source:
reader = csv.DictReader(source, strict=True)
if tuple(reader.fieldnames or ()) != HEADER:
return {"status": "blocked", "issues": [[1, "header"]]}
for row in reader:
line = reader.line_num
if None in row or any(not value or not value.strip() for value in row.values()):
findings.append([line, "missing_or_extra"])
continue
order, when, region, item, count, price, discount, amount = (row[key].strip() for key in HEADER)
try:
month = date.fromisoformat(when).isoformat()[:7]
quantity = int(count)
unit, ratio, recorded = map(Decimal, (price, discount, amount))
if not (0 < quantity <= 1_000_000 and 0 <= unit <= 1_000_000
and 0 <= ratio <= 1 and 0 <= recorded <= 1_000_000_000_000 and region in REGIONS):
raise ValueError
calculated = (quantity * unit * ratio).quantize(CENT, rounding=ROUND_HALF_UP)
except (ValueError, InvalidOperation):
findings.append([line, "invalid_value"])
continue
if recorded != calculated:
findings.append([line, "amount_mismatch"])
orders.append((line, order, month, region, item, quantity, recorded))
duplicate = Counter(order for _, order, *_ in orders)
findings.extend([line, "duplicate_order"] for line, order, *_ in orders if duplicate[order] > 1)
if not orders and not findings:
findings.append([1, "no_orders"])
if findings:
return {"status": "blocked", "issues": sorted(findings)}
monthly = defaultdict(Decimal)
items = defaultdict(Decimal)
units = Counter()
regions = dict.fromkeys(REGIONS, Decimal(0))
for _, _, month, region, item, quantity, amount in orders:
monthly[month] += amount
items[item] += amount
units[item] += quantity
regions[region] += amount
total = sum(monthly.values())
products = [[name, units[name], money(amount)]
for name, amount in sorted(items.items(), key=lambda pair: (-pair[1], pair[0]))]
return {"status": "verified", "issues": [], "orders": len(orders), "total": money(total),
"average": money(total / len(orders)),
"monthly": [[k, money(v)] for k, v in sorted(monthly.items())],
"products": products, "top_three": products[:3],
"regions": [[k, money(v)] for k, v in regions.items()]}
def report(workspace, filename, approved, font=None):
summary = audit(workspace, filename)
if summary["status"] == "blocked":
return summary
if not approved:
return {**summary, "status": "awaiting_approval"}
from office_outputs import deliver
root = workspace.resolve(strict=True)
destination = root / "sales-report"
if destination.exists() or destination.is_symlink():
raise FileExistsError(destination)
with TemporaryDirectory(prefix=".sales-build-", dir=root) as tmp:
staged = Path(tmp) / "report"
staged.mkdir()
deliver(staged, summary, font=font)
staged.rename(destination)
return {**summary, "status": "written", "destination": destination.name}
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--workspace", type=Path, required=True)
parser.add_argument("--input", choices=INPUTS, default=INPUTS[0])
parser.add_argument("--approve", action="store_true")
parser.add_argument("--font", type=Path)
args = parser.parse_args()
result = report(args.workspace, args.input, args.approve, args.font)
print(json.dumps(result, ensure_ascii=False, indent=2))
return 2 if result["status"] == "blocked" else 0
if __name__ == "__main__":
raise SystemExit(main())
本例需在 CPython 3.12,XlsxWriter 3.3.1、openpyxl 3.1.5、Matplotlib 3.11.2、python-docx 1.2.0 和 python-pptx 1.0.2;本地样本,无模型服务。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12,XlsxWriter 3.3.1、openpyxl 3.1.5、Matplotlib 3.11.2、python-docx 1.2.0 和 python-pptx 1.0.2;本地样本,无模型服务。
入口文件:projects/ai-agent-first-sales/sales.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
sales.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12,XlsxWriter 3.3.1、openpyxl 3.1.5、Matplotlib 3.11.2、python-docx 1.2.0 和 python-pptx 1.0.2;本地样本,无模型服务。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联48章) · 含当前章节或实例 · mbskycom202612a3073.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3081.zip