auditloop-oss 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- auditloop/__init__.py +6 -0
- auditloop/analytics.py +317 -0
- auditloop/checks.py +202 -0
- auditloop/cli.py +285 -0
- auditloop/engine.py +109 -0
- auditloop/excel.py +177 -0
- auditloop/fixtures.py +57 -0
- auditloop/models.py +124 -0
- auditloop/workpaper.py +96 -0
- auditloop_oss-0.1.0.dist-info/METADATA +178 -0
- auditloop_oss-0.1.0.dist-info/RECORD +15 -0
- auditloop_oss-0.1.0.dist-info/WHEEL +5 -0
- auditloop_oss-0.1.0.dist-info/entry_points.txt +2 -0
- auditloop_oss-0.1.0.dist-info/licenses/LICENSE +21 -0
- auditloop_oss-0.1.0.dist-info/top_level.txt +1 -0
auditloop/cli.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""命令行入口。
|
|
2
|
+
|
|
3
|
+
python -m auditloop.cli demo
|
|
4
|
+
python -m auditloop.cli run --entity "Acme Industrial" --out out/workpaper.xlsx
|
|
5
|
+
python -m auditloop.cli analytics --facts tests/fixtures/acme_annual.json [--json]
|
|
6
|
+
python -m auditloop.cli init [--dir out/init]
|
|
7
|
+
python -m auditloop.cli analytics --facts out/init/facts.xlsx
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import json
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from . import __version__
|
|
17
|
+
from . import checks, fixtures
|
|
18
|
+
from .analytics import assess, series_from_years
|
|
19
|
+
from .engine import AuditRun
|
|
20
|
+
from .excel import read_facts, write_facts_template
|
|
21
|
+
from .models import COMPLETENESS, CUTOFF, EXISTENCE, VALUATION
|
|
22
|
+
from .workpaper import write_workpaper
|
|
23
|
+
|
|
24
|
+
POLICY_AR_90 = 90
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def build_run(entity: str = "Acme Industrial") -> AuditRun:
|
|
28
|
+
ents = fixtures.entries()
|
|
29
|
+
lines = fixtures.bank_lines()
|
|
30
|
+
invs = fixtures.invoices()
|
|
31
|
+
period_end = fixtures.PERIOD_END
|
|
32
|
+
as_of = fixtures.AS_OF
|
|
33
|
+
# rec / buckets 必须**在闭包里**算:原先它们在 register 之前求值,
|
|
34
|
+
# 一行脏数据就让 build_run 直接抛 traceback 退出,engine 的
|
|
35
|
+
# try/except → status=degraded 这条防线根本没被触达。
|
|
36
|
+
# 前置计算搬进各自的步骤后,register 才是唯一的执行入口。
|
|
37
|
+
|
|
38
|
+
def bank_recon():
|
|
39
|
+
rec = checks.reconcile_bank(ents, lines)
|
|
40
|
+
out = []
|
|
41
|
+
for e, b in rec.amount_diff:
|
|
42
|
+
out.append(checks.Finding(
|
|
43
|
+
"bank_recon", EXISTENCE, ref=e.entry_id, severity="medium",
|
|
44
|
+
detail=f"日期差异 {abs((b.date - e.date).days)} 天,可能为未达账项", amount=e.amount))
|
|
45
|
+
for b in rec.unmatched_bank:
|
|
46
|
+
out.append(checks.Finding("bank_recon", COMPLETENESS, ref=b.line_id, severity="medium",
|
|
47
|
+
detail=f"银行已记、企业未记:{b.memo}", amount=b.amount))
|
|
48
|
+
for e in rec.unmatched_gl:
|
|
49
|
+
out.append(checks.Finding("bank_recon", EXISTENCE, ref=e.entry_id, severity="low",
|
|
50
|
+
detail=f"企业已记、银行未见:{e.memo}", amount=e.amount))
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
def aging():
|
|
54
|
+
buckets = checks.ar_aging(invs, as_of)
|
|
55
|
+
out = []
|
|
56
|
+
for b in buckets:
|
|
57
|
+
if b.label == ">90" and b.invoices:
|
|
58
|
+
out.append(checks.Finding(
|
|
59
|
+
"ar_aging", VALUATION, ref=",".join(i.invoice_id for i in b.invoices),
|
|
60
|
+
severity="medium",
|
|
61
|
+
detail=f"逾期 {POLICY_AR_90} 天以上 {len(b.invoices)} 笔,合计 {b.total:,.2f},需评估坏账准备",
|
|
62
|
+
amount=b.total))
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
return (
|
|
66
|
+
AuditRun(entity=entity, period_end=period_end)
|
|
67
|
+
.register("bank_recon", EXISTENCE, bank_recon, rows=lambda: len(ents) + len(lines))
|
|
68
|
+
.register("ar_aging", VALUATION, aging, rows=lambda: len(invs))
|
|
69
|
+
.register("revenue_cutoff", CUTOFF,
|
|
70
|
+
lambda: checks.revenue_cutoff(invs, period_end), rows=lambda: len(invs))
|
|
71
|
+
.register("duplicate_payment", EXISTENCE,
|
|
72
|
+
lambda: checks.duplicate_payments(ents), rows=lambda: len(ents))
|
|
73
|
+
.register("ar_sanity", VALUATION,
|
|
74
|
+
lambda: checks.ar_negative_or_zero(invs), rows=lambda: len(invs))
|
|
75
|
+
.register("ar_completeness", COMPLETENESS,
|
|
76
|
+
lambda: checks.missing_due_date(invs), rows=lambda: len(invs))
|
|
77
|
+
).run()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _finding_payload(f) -> dict:
|
|
81
|
+
return {"check": f.check, "assertion": f.assertion, "ref": f.ref,
|
|
82
|
+
"severity": f.severity, "detail": f.detail, "amount": f.amount}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def run_payload(run) -> dict:
|
|
86
|
+
"""一轮审计的结构化形状:steps 是「跑了什么」,exceptions 是「要人看什么」。"""
|
|
87
|
+
return {
|
|
88
|
+
"entity": run.entity,
|
|
89
|
+
"period_end": run.period_end.isoformat(),
|
|
90
|
+
"status": run.status,
|
|
91
|
+
"steps": [
|
|
92
|
+
{
|
|
93
|
+
"name": r.name,
|
|
94
|
+
"assertion": r.assertion,
|
|
95
|
+
"status": r.status,
|
|
96
|
+
"error": r.error,
|
|
97
|
+
"rows_examined": r.rows_examined,
|
|
98
|
+
"findings": len(r.findings),
|
|
99
|
+
}
|
|
100
|
+
for r in run.results
|
|
101
|
+
],
|
|
102
|
+
"exceptions": [_finding_payload(f) for f in run.findings],
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def cmd_run(args: argparse.Namespace) -> int:
|
|
107
|
+
run = build_run(args.entity)
|
|
108
|
+
if args.json:
|
|
109
|
+
if args.out:
|
|
110
|
+
print(json.dumps(run_payload(run), ensure_ascii=False, indent=2))
|
|
111
|
+
detail = {
|
|
112
|
+
"总账分录": [f"{e.entry_id} {e.date} {e.account} {e.amount:,.2f} {e.memo}" for e in fixtures.entries()],
|
|
113
|
+
"银行流水": [f"{b.line_id} {b.date} {b.amount:,.2f} {b.memo}" for b in fixtures.bank_lines()],
|
|
114
|
+
"发票": [f"{i.invoice_id} {i.customer} {i.amount:,.2f} 到期 {i.due_date}" for i in fixtures.invoices()],
|
|
115
|
+
}
|
|
116
|
+
write_workpaper(run, args.out, detail)
|
|
117
|
+
else:
|
|
118
|
+
print(json.dumps(run_payload(run), ensure_ascii=False, indent=2))
|
|
119
|
+
return 0
|
|
120
|
+
print(run.to_markdown())
|
|
121
|
+
if args.out:
|
|
122
|
+
detail = {
|
|
123
|
+
"总账分录": [f"{e.entry_id} {e.date} {e.account} {e.amount:,.2f} {e.memo}" for e in fixtures.entries()],
|
|
124
|
+
"银行流水": [f"{b.line_id} {b.date} {b.amount:,.2f} {b.memo}" for b in fixtures.bank_lines()],
|
|
125
|
+
"发票": [f"{i.invoice_id} {i.customer} {i.amount:,.2f} 到期 {i.due_date}" for i in fixtures.invoices()],
|
|
126
|
+
}
|
|
127
|
+
p = write_workpaper(run, args.out, detail)
|
|
128
|
+
print(f"\n底稿已写入:{p}")
|
|
129
|
+
return 0
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def cmd_demo(args: argparse.Namespace) -> int:
|
|
133
|
+
# 显式给全 cmd_run 会读的字段:漏一个就是 AttributeError,
|
|
134
|
+
# 而且是在 6 个程序都跑完之后崩在打印分支上(用户连「哪步坏了」都看不到)。
|
|
135
|
+
ns = argparse.Namespace(entity="Acme Industrial", out="out/workpaper.xlsx",
|
|
136
|
+
json=False)
|
|
137
|
+
return cmd_run(ns)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# 精度与 analytics._PRECISION 一致:两边对同一个数四舍五入到同一位,
|
|
141
|
+
# 文本与 --json 才可能逐字对上。
|
|
142
|
+
_PRECISION = {"pp": 1, "%": 1, "x": 2}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _verdict(item) -> str:
|
|
146
|
+
if item.status == "flag":
|
|
147
|
+
return f"异常({item.severity})"
|
|
148
|
+
return "正常" if item.status == "ok" else "数据不足"
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def analytics_line(item) -> str:
|
|
152
|
+
"""人读输出的一行:指标名 / 本期 / 上期 / 变化 / 判定(异常时附原因)。"""
|
|
153
|
+
p = _PRECISION[item.unit]
|
|
154
|
+
head = f"{item.label}({item.unit})"
|
|
155
|
+
if item.ref:
|
|
156
|
+
head += f" FY{item.ref}"
|
|
157
|
+
if item.status == "insufficient":
|
|
158
|
+
line = f"{head} 本期 — 上期 — 变化 — 判定 数据不足"
|
|
159
|
+
# 为什么「数据不足」也要带原因:只印四个字,现场无从判断是缺列、
|
|
160
|
+
# 缺上期,还是数据本身有问题 —— 三种情况的补救办法完全不同。
|
|
161
|
+
if item.detail:
|
|
162
|
+
line += f" {item.detail}"
|
|
163
|
+
return line
|
|
164
|
+
cur = f"{item.current:.{p}f}"
|
|
165
|
+
prior = "—" if item.prior is None else f"{item.prior:.{p}f}"
|
|
166
|
+
change = "—" if item.change is None else f"{item.change:+.{p}f}"
|
|
167
|
+
line = f"{head} 本期 {cur} 上期 {prior} 变化 {change} 判定 {_verdict(item)}"
|
|
168
|
+
if item.detail:
|
|
169
|
+
line += f" {item.detail}"
|
|
170
|
+
return line
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def cmd_analytics(args: argparse.Namespace) -> int:
|
|
174
|
+
"""分析性程序的命令行出口。
|
|
175
|
+
|
|
176
|
+
退出码四档(README 的「退出码」一节逐条写明了):
|
|
177
|
+
0=跑完,至少一条指标判定成立且无异常;1=跑完且有异常;
|
|
178
|
+
2=根本没跑成(文件缺失/JSON 坏了/没有收入列);
|
|
179
|
+
3=跑完了,但一条指标都没判定成(全部「数据不足」)。
|
|
180
|
+
|
|
181
|
+
为什么要第 3 档:0 的含义是「查过了,没问题」。全部指标都算不出来时
|
|
182
|
+
退出码仍是 0,流水线上它与「真查过且干净」长得一模一样 —— 这是审计里
|
|
183
|
+
最贵的一种失败(没查被当成查过)。部分未判定时走 stderr 说明,仍按 0/1。
|
|
184
|
+
"""
|
|
185
|
+
# .xlsx 与 .json 走同一个入口:审计师手上是 Excel,脚本里是 JSON,
|
|
186
|
+
# 两种输入必须产出同构的 dict —— 否则「换一种填法结论就变」。
|
|
187
|
+
try:
|
|
188
|
+
payload = read_facts(args.facts)
|
|
189
|
+
except FileNotFoundError:
|
|
190
|
+
print(f"找不到 facts 文件:{args.facts}", file=sys.stderr)
|
|
191
|
+
return 2
|
|
192
|
+
except json.JSONDecodeError as exc:
|
|
193
|
+
print(f"facts 不是合法 JSON:{args.facts}({exc})", file=sys.stderr)
|
|
194
|
+
return 2
|
|
195
|
+
except ValueError as exc:
|
|
196
|
+
# Excel 表头/年度坏掉、扩展名不认识、JSON 结构不对,都是「没跑成」
|
|
197
|
+
print(f"facts 内容不可用:{args.facts}({exc})", file=sys.stderr)
|
|
198
|
+
return 2
|
|
199
|
+
except OSError as exc:
|
|
200
|
+
print(f"facts 读取失败:{args.facts}({exc})", file=sys.stderr)
|
|
201
|
+
return 2
|
|
202
|
+
if not isinstance(payload, dict):
|
|
203
|
+
print(f"facts 顶层必须是对象:{args.facts}", file=sys.stderr)
|
|
204
|
+
return 2
|
|
205
|
+
try:
|
|
206
|
+
series = series_from_years(payload.get("years"))
|
|
207
|
+
except ValueError as exc:
|
|
208
|
+
print(f"facts 内容不可用:{args.facts}({exc})", file=sys.stderr)
|
|
209
|
+
return 2
|
|
210
|
+
|
|
211
|
+
entity = payload.get("entity") or "未知主体"
|
|
212
|
+
items = assess(series)
|
|
213
|
+
anomalies = [i for i in items if i.flag]
|
|
214
|
+
insufficient = [i for i in items if i.status == "insufficient"]
|
|
215
|
+
nothing_judged = bool(items) and len(insufficient) == len(items)
|
|
216
|
+
|
|
217
|
+
if args.json:
|
|
218
|
+
print(json.dumps({
|
|
219
|
+
"entity": entity,
|
|
220
|
+
"items": [i.as_dict() for i in items],
|
|
221
|
+
"summary": {"total": len(items), "anomalies": len(anomalies),
|
|
222
|
+
"insufficient": len(insufficient),
|
|
223
|
+
"nothing_judged": nothing_judged},
|
|
224
|
+
}, ensure_ascii=False, indent=2))
|
|
225
|
+
else:
|
|
226
|
+
print(f"{entity} · 分析性程序")
|
|
227
|
+
for item in items:
|
|
228
|
+
print(analytics_line(item))
|
|
229
|
+
if anomalies:
|
|
230
|
+
print(f"异常 {len(anomalies)} 项 / 共 {len(items)} 项"
|
|
231
|
+
f"(未计算 {len(insufficient)} 项)")
|
|
232
|
+
|
|
233
|
+
if nothing_judged:
|
|
234
|
+
print(f"一条指标都没判定成:{len(items)} 项全部数据不足(缺列或只有一个财年),"
|
|
235
|
+
f"这份输入给不出任何结论", file=sys.stderr)
|
|
236
|
+
return 3
|
|
237
|
+
if insufficient:
|
|
238
|
+
print(f"未判定 {len(insufficient)} 项 / 共 {len(items)} 项(无可比上期或缺列)",
|
|
239
|
+
file=sys.stderr)
|
|
240
|
+
return 1 if anomalies else 0
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def cmd_init(args: argparse.Namespace) -> int:
|
|
244
|
+
"""写一张中文表头的填空模板,并把下一步命令原样印出来。
|
|
245
|
+
|
|
246
|
+
路径用绝对路径打印:审计师复制这行就能跑,不用自己拼目录。
|
|
247
|
+
"""
|
|
248
|
+
target = Path(args.dir) / "facts.xlsx"
|
|
249
|
+
try:
|
|
250
|
+
path = write_facts_template(target)
|
|
251
|
+
except OSError as exc:
|
|
252
|
+
print(f"模板写入失败:{target}({exc})", file=sys.stderr)
|
|
253
|
+
return 2
|
|
254
|
+
print(f"模板已写入:{path}")
|
|
255
|
+
print("在 Excel 里把四个示例行换成自家四年数据(空着不填表示该年没有这个数),")
|
|
256
|
+
print(f"填好后运行:auditloop analytics --facts {path}")
|
|
257
|
+
return 0
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def main(argv: list[str] | None = None) -> int:
|
|
261
|
+
ap = argparse.ArgumentParser(prog="auditloop", description="审计底稿自动化")
|
|
262
|
+
ap.add_argument("--version", action="version",
|
|
263
|
+
version=f"%(prog)s {__version__}")
|
|
264
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
265
|
+
r = sub.add_parser("run", help="跑一轮审计程序")
|
|
266
|
+
r.add_argument("--entity", default="Acme Industrial")
|
|
267
|
+
r.add_argument("--out", default="out/workpaper.xlsx")
|
|
268
|
+
r.add_argument("--json", action="store_true", help="输出 JSON(不打印底稿正文)")
|
|
269
|
+
r.set_defaults(func=cmd_run)
|
|
270
|
+
d = sub.add_parser("demo", help="零配置演示")
|
|
271
|
+
d.set_defaults(func=cmd_demo)
|
|
272
|
+
a = sub.add_parser("analytics", help="分析性程序:比率与趋势的逐年复核")
|
|
273
|
+
a.add_argument("--facts", required=True,
|
|
274
|
+
help="年度序列 Excel(.xlsx,用 init 生成)或 JSON({\"entity\": ..., \"years\": {...}})")
|
|
275
|
+
a.add_argument("--json", action="store_true", help="输出结构化结果")
|
|
276
|
+
a.set_defaults(func=cmd_analytics)
|
|
277
|
+
i = sub.add_parser("init", help="生成年度数据填空模板(Excel)")
|
|
278
|
+
i.add_argument("--dir", default="out/init", help="写到哪个目录(默认 out/init)")
|
|
279
|
+
i.set_defaults(func=cmd_init)
|
|
280
|
+
args = ap.parse_args(argv)
|
|
281
|
+
return args.func(args)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
if __name__ == "__main__":
|
|
285
|
+
sys.exit(main())
|
auditloop/engine.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""审计执行引擎:把检查编排成有状态的步骤序列。
|
|
2
|
+
|
|
3
|
+
两条纪律:
|
|
4
|
+
1. **单步失败不许拖垮整轮**。审计现场的数据永远有脏行,一步抛异常就终止,
|
|
5
|
+
会计师会以为是软件坏了而不是数据有问题。所以捕获异常、记 status=error、继续。
|
|
6
|
+
2. **每一步必须声明它验证的审计认定**。底稿复核时,复核人先看「截止测试做了没」,
|
|
7
|
+
而不是「跑了几个脚本」。
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import traceback
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from datetime import date
|
|
14
|
+
from typing import Callable
|
|
15
|
+
|
|
16
|
+
from .models import Finding, StepResult, counts_as_high, severity_rank
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class Step:
|
|
21
|
+
name: str
|
|
22
|
+
assertion: str
|
|
23
|
+
fn: Callable[[], list[Finding]]
|
|
24
|
+
rows: Callable[[], int] | None = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class AuditRun:
|
|
29
|
+
entity: str
|
|
30
|
+
period_end: date
|
|
31
|
+
steps: list[Step] = field(default_factory=list)
|
|
32
|
+
results: list[StepResult] = field(default_factory=list)
|
|
33
|
+
|
|
34
|
+
def register(self, name: str, assertion: str, fn: Callable[[], list[Finding]],
|
|
35
|
+
rows: Callable[[], int] | None = None) -> "AuditRun":
|
|
36
|
+
self.steps.append(Step(name, assertion, fn, rows))
|
|
37
|
+
return self
|
|
38
|
+
|
|
39
|
+
def run(self) -> "AuditRun":
|
|
40
|
+
self.results = []
|
|
41
|
+
for step in self.steps:
|
|
42
|
+
r = StepResult(name=step.name, assertion=step.assertion)
|
|
43
|
+
try:
|
|
44
|
+
r.findings = list(step.fn() or [])
|
|
45
|
+
r.rows_examined = step.rows() if step.rows else 0
|
|
46
|
+
except Exception as exc: # noqa: BLE001 —— 故意捕获全部,单步失败不终止整轮
|
|
47
|
+
r.status = "error"
|
|
48
|
+
r.error = f"{type(exc).__name__}: {exc}"
|
|
49
|
+
r.findings = [Finding(
|
|
50
|
+
check=step.name, assertion=step.assertion, ref="ENGINE", severity="high",
|
|
51
|
+
detail=f"该程序执行失败,需人工补做:{r.error}")]
|
|
52
|
+
r.trace = traceback.format_exc(limit=3)
|
|
53
|
+
self.results.append(r)
|
|
54
|
+
return self
|
|
55
|
+
|
|
56
|
+
# ---- 汇总 ----
|
|
57
|
+
@property
|
|
58
|
+
def findings(self) -> list[Finding]:
|
|
59
|
+
return [f for r in self.results for f in r.findings]
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def high(self) -> list[Finding]:
|
|
63
|
+
# 判定走 counts_as_high:认不出的严重度按 high 处理(fail-closed)。
|
|
64
|
+
# 原先这里是 `== "high"` 精确匹配,一个 `critical` 就能让「high 例外 0 条」
|
|
65
|
+
# 与「结论:clean」并排印在同一张摘要上。
|
|
66
|
+
return [f for f in self.findings if counts_as_high(f.severity)]
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def status(self) -> str:
|
|
70
|
+
if any(r.status == "error" for r in self.results):
|
|
71
|
+
return "degraded"
|
|
72
|
+
if self.high:
|
|
73
|
+
return "attention_required"
|
|
74
|
+
return "clean"
|
|
75
|
+
|
|
76
|
+
def by_check(self) -> dict[str, int]:
|
|
77
|
+
out: dict[str, int] = {}
|
|
78
|
+
for f in self.findings:
|
|
79
|
+
out[f.check] = out.get(f.check, 0) + 1
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
def coverage(self) -> list[tuple[str, str, str, int]]:
|
|
83
|
+
"""(程序, 认定, 状态, 例外数) —— 底稿第一页。"""
|
|
84
|
+
return [(r.name, r.assertion, r.status, len(r.findings)) for r in self.results]
|
|
85
|
+
|
|
86
|
+
def to_markdown(self) -> str:
|
|
87
|
+
lines = [
|
|
88
|
+
f"# 审计执行摘要 · {self.entity}",
|
|
89
|
+
"",
|
|
90
|
+
f"- 期末:{self.period_end}",
|
|
91
|
+
f"- 结论:**{self.status}**(high 例外 {len(self.high)} 条)",
|
|
92
|
+
"",
|
|
93
|
+
"| 程序 | 认定 | 状态 | 例外 |",
|
|
94
|
+
"| --- | --- | --- | ---: |",
|
|
95
|
+
]
|
|
96
|
+
for name, assertion, status, n in self.coverage():
|
|
97
|
+
lines.append(f"| {name} | {assertion} | {status} | {n} |")
|
|
98
|
+
if self.findings:
|
|
99
|
+
lines += ["", "## 例外清单", "", "| 程序 | 认定 | 严重度 | 对象 | 说明 |", "| --- | --- | --- | --- | --- |"]
|
|
100
|
+
for f in sorted(self.findings, key=lambda x: (-severity_rank(x.severity), x.check)):
|
|
101
|
+
lines.append(f"| {f.check} | {f.assertion} | {f.severity} | {f.ref} | {f.detail} |")
|
|
102
|
+
failed = [r for r in self.results if r.status == "error"]
|
|
103
|
+
if failed:
|
|
104
|
+
# 失败追踪必须出现在交付物里:只有 status=error 一行时,
|
|
105
|
+
# 复核人无从判断是数据脏还是程序 bug,只能重跑一遍。
|
|
106
|
+
lines += ["", "## 失败程序追踪", ""]
|
|
107
|
+
for r in failed:
|
|
108
|
+
lines += [f"### {r.name} · {r.error}", "", "```", (r.trace or "(无追踪)").strip(), "```", ""]
|
|
109
|
+
return "\n".join(lines)
|
auditloop/excel.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Excel 进出:审计师填的是 Excel,分析性程序吃的是年度序列 dict。
|
|
2
|
+
|
|
3
|
+
这一层只做两件事,都要求**可逆且不撒谎**:
|
|
4
|
+
|
|
5
|
+
1. `write_facts_template()` 写一张审计师看得懂的模板 —— 表头是中文科目名,
|
|
6
|
+
单位写在第二行注释里,下面四行是可直接替换成自家数的示例。
|
|
7
|
+
2. `read_facts()` 把填好的表读回 `{"entity": ..., "years": {...}}`,
|
|
8
|
+
**空单元格表示「这家没这个数」,不是 0**。写 0 会让毛利率、现金含量算出
|
|
9
|
+
一个凭空成立的结论;缺失只会让那条程序报「数据不足」,那是诚实的。
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from openpyxl import Workbook, load_workbook
|
|
17
|
+
|
|
18
|
+
SHEET = "年度数据"
|
|
19
|
+
HEADERS = ["年度", "营业收入", "应收账款", "毛利", "经营活动现金流"]
|
|
20
|
+
UNIT_NOTE = "单位:元,可只填有数据的年份"
|
|
21
|
+
ENTITY_PREFIX = "主体:"
|
|
22
|
+
|
|
23
|
+
# 列号(1-based)→ facts JSON 里的字段名。顺序与 HEADERS 一一对应。
|
|
24
|
+
FIELDS = {1: "year", 2: "revenue", 3: "receivables", 4: "gross_profit", 5: "cfo"}
|
|
25
|
+
DATA_START_ROW = 3 # 1=表头,2=单位说明,3 起是数据
|
|
26
|
+
|
|
27
|
+
SAMPLE_ROWS = [
|
|
28
|
+
(2023, 1000.0, 100.0, 400.0, 250.0),
|
|
29
|
+
(2024, 1050.0, 108.0, 420.0, 210.0),
|
|
30
|
+
(2025, 1100.0, 115.0, 462.0, 200.0),
|
|
31
|
+
(2026, 1155.0, 250.0, 530.0, 150.0),
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def write_facts_template(path: str | Path, entity: str = "Acme Industrial") -> Path:
|
|
36
|
+
"""写出分析性程序的填空模板,返回实际写入的路径。
|
|
37
|
+
|
|
38
|
+
表头逐字固定(`read_facts` 按它认表),第二行是给人看的单位说明,
|
|
39
|
+
A 列非数字的行会被 `read_facts` 当注释跳过 —— 所以说明行可以随便改字,
|
|
40
|
+
但不要删掉它上面的表头。
|
|
41
|
+
"""
|
|
42
|
+
p = Path(path)
|
|
43
|
+
if p.parent and not p.parent.exists():
|
|
44
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
45
|
+
wb = Workbook()
|
|
46
|
+
ws = wb.active
|
|
47
|
+
ws.title = SHEET
|
|
48
|
+
ws.append(HEADERS)
|
|
49
|
+
ws.append([UNIT_NOTE])
|
|
50
|
+
# 主体名放在表头右侧,用户改公司名不用碰数据区;读回时按「主体:」前缀解析。
|
|
51
|
+
ws.cell(row=1, column=7, value=f"{ENTITY_PREFIX}{entity}")
|
|
52
|
+
for row in SAMPLE_ROWS:
|
|
53
|
+
ws.append(list(row))
|
|
54
|
+
# 年度按整数显示,别让 Excel 把 2023 显示成 2,023.00
|
|
55
|
+
for r in range(DATA_START_ROW, DATA_START_ROW + len(SAMPLE_ROWS)):
|
|
56
|
+
ws.cell(row=r, column=1).number_format = "0"
|
|
57
|
+
ws.freeze_panes = f"A{DATA_START_ROW}"
|
|
58
|
+
widths = {"A": 10, "B": 16, "C": 16, "D": 16, "E": 20, "G": 28}
|
|
59
|
+
for col, width in widths.items():
|
|
60
|
+
ws.column_dimensions[col].width = width
|
|
61
|
+
wb.save(p)
|
|
62
|
+
return p
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _parse_year(value: object, row: int) -> int:
|
|
66
|
+
"""年度列必须是数字(或纯数字字符串)。报错必须带行号 —— 现场只看报错文本。"""
|
|
67
|
+
if isinstance(value, bool):
|
|
68
|
+
raise ValueError(f"第 {row} 行:年度 {value!r} 不是数字")
|
|
69
|
+
if isinstance(value, int):
|
|
70
|
+
return value
|
|
71
|
+
if isinstance(value, float):
|
|
72
|
+
if value.is_integer():
|
|
73
|
+
return int(value)
|
|
74
|
+
raise ValueError(f"第 {row} 行:年度 {value!r} 不是整数年份")
|
|
75
|
+
if isinstance(value, str):
|
|
76
|
+
text = value.strip()
|
|
77
|
+
# 容忍 "2023年" / "FY2023" 这类手工输入
|
|
78
|
+
cleaned = text.replace("FY", "").replace("fy", "").rstrip("年").strip()
|
|
79
|
+
try:
|
|
80
|
+
return int(cleaned)
|
|
81
|
+
except ValueError:
|
|
82
|
+
raise ValueError(f"第 {row} 行:年度 {value!r} 不是数字") from None
|
|
83
|
+
raise ValueError(f"第 {row} 行:年度 {value!r} 不是数字")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _number(value: object, row: int, header: str) -> float:
|
|
87
|
+
if isinstance(value, bool):
|
|
88
|
+
raise ValueError(f"第 {row} 行:{header} {value!r} 不是数字")
|
|
89
|
+
if isinstance(value, (int, float)):
|
|
90
|
+
return float(value)
|
|
91
|
+
if isinstance(value, str):
|
|
92
|
+
try:
|
|
93
|
+
return float(value.strip().replace(",", ""))
|
|
94
|
+
except ValueError:
|
|
95
|
+
pass
|
|
96
|
+
raise ValueError(f"第 {row} 行:{header} {value!r} 不是数字")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _check_headers(ws) -> None:
|
|
100
|
+
actual = [ws.cell(row=1, column=i + 1).value for i in range(len(HEADERS))]
|
|
101
|
+
normalized = [str(v).strip() if v is not None else "" for v in actual]
|
|
102
|
+
if normalized != HEADERS:
|
|
103
|
+
raise ValueError(
|
|
104
|
+
f"表头认不出:期望 {HEADERS},实际 {normalized}。"
|
|
105
|
+
f"请使用 auditloop init 生成的模板,或把第一行改成上述五个表头。"
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _entity(ws, path: Path) -> str:
|
|
110
|
+
for col in range(6, 12):
|
|
111
|
+
value = ws.cell(row=1, column=col).value
|
|
112
|
+
if isinstance(value, str) and value.startswith(ENTITY_PREFIX):
|
|
113
|
+
return value[len(ENTITY_PREFIX):].strip() or path.stem
|
|
114
|
+
return path.stem
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def read_facts_xlsx(path: str | Path) -> dict:
|
|
118
|
+
"""读 `.xlsx`,产出与 `acme_annual.json` 同构的 dict。"""
|
|
119
|
+
p = Path(path)
|
|
120
|
+
wb = load_workbook(p, data_only=True)
|
|
121
|
+
if SHEET not in wb.sheetnames:
|
|
122
|
+
raise ValueError(
|
|
123
|
+
f"找不到工作表 {SHEET!r}(现有:{wb.sheetnames})。"
|
|
124
|
+
f"请使用 auditloop init 生成的模板。"
|
|
125
|
+
)
|
|
126
|
+
ws = wb[SHEET]
|
|
127
|
+
_check_headers(ws)
|
|
128
|
+
|
|
129
|
+
years: dict[str, dict[str, float]] = {}
|
|
130
|
+
seen: dict[int, int] = {} # 年份 → 首次出现的行号,重复年份要报错而不是静默覆盖
|
|
131
|
+
for row in range(DATA_START_ROW, ws.max_row + 1):
|
|
132
|
+
raw = {col: ws.cell(row=row, column=col).value for col in FIELDS}
|
|
133
|
+
if all(v is None or (isinstance(v, str) and not v.strip()) for v in raw.values()):
|
|
134
|
+
continue # 整行空:模板尾部或用户删掉的行
|
|
135
|
+
year_cell = raw[1]
|
|
136
|
+
if isinstance(year_cell, str) and year_cell.strip().startswith(("单位", "注释", "说明")):
|
|
137
|
+
continue # 注释性说明行(模板第二行就是这种)
|
|
138
|
+
if year_cell is None or (isinstance(year_cell, str) and not year_cell.strip()):
|
|
139
|
+
raise ValueError(f"第 {row} 行:年度为空,但有数据填在旁边")
|
|
140
|
+
|
|
141
|
+
year = _parse_year(year_cell, row)
|
|
142
|
+
if year in seen:
|
|
143
|
+
raise ValueError(
|
|
144
|
+
f"第 {row} 行:年度 {year} 与第 {seen[year]} 行重复,"
|
|
145
|
+
f"一个年度只能有一行"
|
|
146
|
+
)
|
|
147
|
+
seen[year] = row
|
|
148
|
+
|
|
149
|
+
record: dict[str, float] = {}
|
|
150
|
+
for col, field in FIELDS.items():
|
|
151
|
+
if field == "year":
|
|
152
|
+
continue
|
|
153
|
+
value = raw[col]
|
|
154
|
+
if value is None or (isinstance(value, str) and not value.strip()):
|
|
155
|
+
continue # 空单元格 = 这个字段缺失,不是 0
|
|
156
|
+
record[field] = _number(value, row, HEADERS[col - 1])
|
|
157
|
+
years[str(year)] = record
|
|
158
|
+
|
|
159
|
+
if not years:
|
|
160
|
+
raise ValueError(f"{SHEET!r} 里没有任何数据行:请填入至少一个年度的营业收入")
|
|
161
|
+
return {"entity": _entity(ws, p), "years": years}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def read_facts(path: str | Path) -> dict:
|
|
165
|
+
"""读 facts:按后缀分派 `.xlsx` / `.json`,两种输入同构。"""
|
|
166
|
+
p = Path(path)
|
|
167
|
+
suffix = p.suffix.lower()
|
|
168
|
+
if suffix == ".xlsx":
|
|
169
|
+
return read_facts_xlsx(p)
|
|
170
|
+
if suffix == ".json":
|
|
171
|
+
payload = json.loads(p.read_text(encoding="utf-8"))
|
|
172
|
+
if not isinstance(payload, dict):
|
|
173
|
+
raise ValueError("facts JSON 顶层必须是对象")
|
|
174
|
+
if not isinstance(payload.get("years"), dict) or not payload["years"]:
|
|
175
|
+
raise ValueError("facts JSON 里没有 years 对象")
|
|
176
|
+
return payload
|
|
177
|
+
raise ValueError(f"不认识的扩展名 {p.suffix!r}:只支持 .xlsx 与 .json")
|
auditloop/fixtures.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""夹具:一家虚构公司(Acme Industrial)的一个季度末数据,故意埋入 6 类例外。
|
|
2
|
+
|
|
3
|
+
每一条埋点都在 tests 里被断言到具体 ref —— 夹具不许「差不多」,
|
|
4
|
+
否则检测能力就没被证明。
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from datetime import date
|
|
9
|
+
|
|
10
|
+
from .models import BankLine, Entry, Invoice
|
|
11
|
+
|
|
12
|
+
PERIOD_END = date(2026, 9, 30)
|
|
13
|
+
AS_OF = date(2026, 10, 31)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def entries() -> list[Entry]:
|
|
17
|
+
return [
|
|
18
|
+
Entry("G1", date(2026, 9, 2), "银行存款", debit=5000, memo="客户回款 A"),
|
|
19
|
+
Entry("G2", date(2026, 9, 10), "银行存款", credit=1200, memo="付 Northwind 货款", vendor="Northwind"),
|
|
20
|
+
Entry("G3", date(2026, 9, 20), "银行存款", credit=800, memo="顾问费", vendor="Northwind"),
|
|
21
|
+
Entry("G4", date(2026, 9, 25), "银行存款", credit=300, memo="办公用品", vendor="Staples"),
|
|
22
|
+
Entry("G6", date(2026, 9, 21), "银行存款", credit=800, memo="顾问费(重复录入)", vendor="Northwind"),
|
|
23
|
+
Entry("G7", date(2026, 9, 12), "管理费用", debit=3300, memo="按月结转"),
|
|
24
|
+
Entry("G8", date(2026, 9, 30), "营业收入", credit=28000, memo="本期确认收入"),
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def bank_lines() -> list[BankLine]:
|
|
29
|
+
return [
|
|
30
|
+
BankLine("B1", date(2026, 9, 3), 5000, "客户回款"),
|
|
31
|
+
BankLine("B2", date(2026, 9, 10), -1200, "Northwind"),
|
|
32
|
+
BankLine("B3", date(2026, 10, 2), -800, "顾问费(跨月)"),
|
|
33
|
+
BankLine("B4", date(2026, 9, 30), -45, "银行手续费"),
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def invoices() -> list[Invoice]:
|
|
38
|
+
return [
|
|
39
|
+
# 正常:未到期、期末前发货并确认
|
|
40
|
+
Invoice("INV-1001", "Blue Harbor", 10_000, date(2026, 9, 1), date(2026, 11, 15),
|
|
41
|
+
shipped_date=date(2026, 9, 28), revenue_date=date(2026, 9, 28)),
|
|
42
|
+
# 逾期 6 天
|
|
43
|
+
Invoice("INV-1002", "Ridgeway", 5_000, date(2026, 8, 25), date(2026, 10, 25),
|
|
44
|
+
shipped_date=date(2026, 8, 20), revenue_date=date(2026, 8, 25)),
|
|
45
|
+
# 逾期 36 天 + 截止例外(发货晚于期末,收入确认在期末)
|
|
46
|
+
Invoice("INV-1003", "Cobalt Labs", 7_500, date(2026, 8, 10), date(2026, 9, 25),
|
|
47
|
+
shipped_date=date(2026, 10, 5), revenue_date=date(2026, 9, 30)),
|
|
48
|
+
# 逾期 67 天 + 截止例外(无发货记录)
|
|
49
|
+
Invoice("INV-1004", "Dunmore", 3_000, date(2026, 7, 1), date(2026, 8, 25),
|
|
50
|
+
shipped_date=None, revenue_date=date(2026, 9, 29)),
|
|
51
|
+
# 逾期 123 天
|
|
52
|
+
Invoice("INV-1005", "Eastvale", 2_000, date(2026, 5, 20), date(2026, 6, 30),
|
|
53
|
+
shipped_date=date(2026, 5, 18), revenue_date=date(2026, 5, 20)),
|
|
54
|
+
# 金额为 0 + 到期日早于开票日(数据完整性例外)
|
|
55
|
+
Invoice("INV-1006", "Fenwick", 0, date(2026, 10, 10), date(2026, 10, 5),
|
|
56
|
+
shipped_date=date(2026, 10, 8), revenue_date=date(2026, 10, 8)),
|
|
57
|
+
]
|