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/__init__.py
ADDED
auditloop/analytics.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""分析性程序(analytical procedures):不看单笔凭证,看「比率和趋势是否自相矛盾」。
|
|
2
|
+
|
|
3
|
+
这是审计里最能抓到「收入被做高」的一类程序,因为它不需要逐笔抽凭:
|
|
4
|
+
收入涨 5%、应收账款涨 40%,两句话放在一起就说明有问题。
|
|
5
|
+
所有判断都**逐年**做(相邻两年一比),单年噪声靠阈值挡,不靠「连续两年」——
|
|
6
|
+
审计现场最常见的就是「某一年突然出现大背离」,要求连续两年才报会把最该看的那年漏掉。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
|
|
13
|
+
from .models import Finding, VALUATION, EXISTENCE
|
|
14
|
+
|
|
15
|
+
# 阈值:都是「百分点」/ 比率,逐年判;单年波动由阈值本身过滤
|
|
16
|
+
RECEIVABLE_GAP_PP = 20.0 # 应收增速 - 收入增速
|
|
17
|
+
MARGIN_SHIFT_PP = 3.0 # 毛利率变动
|
|
18
|
+
CASH_CONVERSION_DROP = 0.10 # 经营现金流/收入 的绝对下滑
|
|
19
|
+
CASH_CONVERSION_DROP_REL = 0.25 # 或相对下滑 25%——两家收入规模不同,绝对阈值单用会漏
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class Series:
|
|
24
|
+
"""某家公司的年度序列:{财年: 数值}。缺年不许插值,缺就报缺口。"""
|
|
25
|
+
|
|
26
|
+
revenue: dict[int, float]
|
|
27
|
+
receivables: dict[int, float] | None = None
|
|
28
|
+
gross_profit: dict[int, float] | None = None
|
|
29
|
+
cfo: dict[int, float] | None = None
|
|
30
|
+
|
|
31
|
+
def years(self) -> list[int]:
|
|
32
|
+
return sorted(self.revenue)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _num(v: float | None) -> float | None:
|
|
36
|
+
"""把 None / 非数值挡在外面。
|
|
37
|
+
|
|
38
|
+
导出表里某年缺列是常态;原实现让 None 一路进到除法,直接 TypeError,
|
|
39
|
+
而同模块的 cash_conversion 又静默跳过 —— 同一份脏数据两种命运。
|
|
40
|
+
"""
|
|
41
|
+
return v if isinstance(v, (int, float)) and not isinstance(v, bool) else None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _pct(cur: float | None, prev: float | None) -> float | None:
|
|
45
|
+
cur, prev = _num(cur), _num(prev)
|
|
46
|
+
if cur is None or prev is None or not prev:
|
|
47
|
+
return None
|
|
48
|
+
return (cur - prev) / abs(prev) * 100
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def revenue_vs_receivables(s: Series) -> list[Finding]:
|
|
52
|
+
"""收入与应收账款增速背离 —— 渠道压货/提前确认收入的经典信号。"""
|
|
53
|
+
out: list[Finding] = []
|
|
54
|
+
if not s.receivables:
|
|
55
|
+
return out
|
|
56
|
+
common = sorted(set(s.revenue) & set(s.receivables))
|
|
57
|
+
for prev_y, cur_y in zip(common, common[1:]):
|
|
58
|
+
rg = _pct(s.revenue.get(cur_y), s.revenue.get(prev_y))
|
|
59
|
+
ag = _pct(s.receivables.get(cur_y), s.receivables.get(prev_y))
|
|
60
|
+
if rg is None or ag is None:
|
|
61
|
+
continue
|
|
62
|
+
gap = ag - rg
|
|
63
|
+
if gap > RECEIVABLE_GAP_PP:
|
|
64
|
+
out.append(Finding(
|
|
65
|
+
check="analytics.revenue_vs_receivables", assertion=EXISTENCE,
|
|
66
|
+
ref=f"FY{cur_y}", severity="high" if gap > 2 * RECEIVABLE_GAP_PP else "medium",
|
|
67
|
+
detail=(f"应收账款增速 {ag:+.1f}% 高于收入增速 {rg:+.1f}%(差 {gap:+.1f}pt),"
|
|
68
|
+
f"需检查是否存在提前确认收入或渠道压货"),
|
|
69
|
+
amount=s.receivables[cur_y],
|
|
70
|
+
))
|
|
71
|
+
return out
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def gross_margin_trend(s: Series) -> list[Finding]:
|
|
75
|
+
"""毛利率突变:定价、成本结构或分类口径被改动。"""
|
|
76
|
+
out: list[Finding] = []
|
|
77
|
+
if not s.gross_profit:
|
|
78
|
+
return out
|
|
79
|
+
common = sorted(set(s.revenue) & set(s.gross_profit))
|
|
80
|
+
margins = []
|
|
81
|
+
for y in common:
|
|
82
|
+
rev, gp = _num(s.revenue.get(y)), _num(s.gross_profit.get(y))
|
|
83
|
+
if rev and gp is not None:
|
|
84
|
+
margins.append((y, gp / rev * 100))
|
|
85
|
+
for (py, pm), (cy, cm) in zip(margins, margins[1:]):
|
|
86
|
+
shift = cm - pm
|
|
87
|
+
if abs(shift) > MARGIN_SHIFT_PP:
|
|
88
|
+
out.append(Finding(
|
|
89
|
+
check="analytics.gross_margin_trend", assertion=VALUATION,
|
|
90
|
+
ref=f"FY{cy}", severity="medium",
|
|
91
|
+
detail=(f"毛利率由 FY{py} 的 {pm:.1f}% 变为 {cm:.1f}%({shift:+.1f}pt),"
|
|
92
|
+
f"需确认成本归集与分类口径是否变化"),
|
|
93
|
+
))
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def cash_conversion(s: Series) -> list[Finding]:
|
|
98
|
+
"""经营现金流/收入 下滑:利润没有变成现金。"""
|
|
99
|
+
out: list[Finding] = []
|
|
100
|
+
if not s.cfo:
|
|
101
|
+
return out
|
|
102
|
+
common = sorted(set(s.revenue) & set(s.cfo))
|
|
103
|
+
ratios = []
|
|
104
|
+
for y in common:
|
|
105
|
+
rev, cfo = _num(s.revenue.get(y)), _num(s.cfo.get(y))
|
|
106
|
+
if rev and cfo is not None:
|
|
107
|
+
ratios.append((y, cfo / rev))
|
|
108
|
+
for (py, pr), (cy, cr) in zip(ratios, ratios[1:]):
|
|
109
|
+
absolute = pr - cr
|
|
110
|
+
# 相对变化必须除 |pr|:pr<0 时(经营现金流为负)除以负数会把「改善」算成
|
|
111
|
+
# 「+60% 下滑」。方向由 absolute 的正负决定,量级由 |pr| 归一。
|
|
112
|
+
relative = absolute / abs(pr) if pr else 0.0
|
|
113
|
+
dropped = absolute > 0
|
|
114
|
+
if dropped and (absolute > CASH_CONVERSION_DROP or relative > CASH_CONVERSION_DROP_REL):
|
|
115
|
+
out.append(Finding(
|
|
116
|
+
check="analytics.cash_conversion", assertion=VALUATION,
|
|
117
|
+
ref=f"FY{cy}", severity="medium",
|
|
118
|
+
detail=(f"经营现金流/收入 由 {pr:.2f} 降至 {cr:.2f}"
|
|
119
|
+
f"({relative:.1%} 相对下滑),利润的现金含量下降,需检查收入质量"),
|
|
120
|
+
amount=s.cfo[cy],
|
|
121
|
+
))
|
|
122
|
+
return out
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def run_all(s: Series) -> list[Finding]:
|
|
126
|
+
findings: list[Finding] = []
|
|
127
|
+
for fn in (revenue_vs_receivables, gross_margin_trend, cash_conversion):
|
|
128
|
+
findings.extend(fn(s))
|
|
129
|
+
return findings
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# ---------------- 逐年明细(CLI 的「指标 / 本期 / 上期 / 变化 / 判定」行) ----------------
|
|
133
|
+
#
|
|
134
|
+
# 上面三个程序只吐「例外」,看不出「这一年到底算出了什么数」。命令行要的是
|
|
135
|
+
# 一张逐年明细表,所以这里把**同一个指标**在相邻两年的取值摊开成一条记录:
|
|
136
|
+
# current/prior 都指这个指标本身(例如收入应收增速差取的是「差值」),
|
|
137
|
+
# change = current - prior。文本与 --json 都从这一条记录渲染,
|
|
138
|
+
# 两边不会各算一遍,也就不会出现数字口径不一致。
|
|
139
|
+
|
|
140
|
+
_PRECISION = {"pp": 1, "%": 1, "x": 2}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@dataclass
|
|
144
|
+
class Item:
|
|
145
|
+
name: str # 程序键,与 Finding.check 的后半段一致
|
|
146
|
+
label: str # 中文指标名
|
|
147
|
+
ref: str # 本期财年("2026"),数据不足时为空
|
|
148
|
+
prior_ref: str # 上期财年,首年为空
|
|
149
|
+
current: float | None
|
|
150
|
+
prior: float | None
|
|
151
|
+
change: float | None
|
|
152
|
+
unit: str # pp(百分点)| % | x(比率)
|
|
153
|
+
status: str # ok | flag | insufficient
|
|
154
|
+
severity: str = ""
|
|
155
|
+
detail: str = ""
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def flag(self) -> bool:
|
|
159
|
+
return self.status == "flag"
|
|
160
|
+
|
|
161
|
+
def as_dict(self) -> dict:
|
|
162
|
+
return {
|
|
163
|
+
"name": self.name, "label": self.label,
|
|
164
|
+
"ref": self.ref, "prior_ref": self.prior_ref,
|
|
165
|
+
"current": self.current, "prior": self.prior, "change": self.change,
|
|
166
|
+
"unit": self.unit, "status": self.status, "flag": self.flag,
|
|
167
|
+
"severity": self.severity, "detail": self.detail,
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _round(v: float | None, unit: str) -> float | None:
|
|
172
|
+
if v is None:
|
|
173
|
+
return None
|
|
174
|
+
# + 0.0 把 -0.0 归一成 0.0,否则文本会印出 "-0.00"
|
|
175
|
+
return round(v, _PRECISION[unit]) + 0.0
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _consecutive(values: dict[int, float]) -> list[tuple[int, int]]:
|
|
179
|
+
years = sorted(values)
|
|
180
|
+
return list(zip(years, years[1:]))
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def revenue_gap_series(s: Series) -> dict[int, float]:
|
|
184
|
+
"""{财年: 应收增速 - 收入增速},单位百分点。"""
|
|
185
|
+
if not s.receivables:
|
|
186
|
+
return {}
|
|
187
|
+
out: dict[int, float] = {}
|
|
188
|
+
common = sorted(set(s.revenue) & set(s.receivables))
|
|
189
|
+
for prev_y, cur_y in zip(common, common[1:]):
|
|
190
|
+
rg = _pct(s.revenue.get(cur_y), s.revenue.get(prev_y))
|
|
191
|
+
ag = _pct(s.receivables.get(cur_y), s.receivables.get(prev_y))
|
|
192
|
+
if rg is None or ag is None:
|
|
193
|
+
continue
|
|
194
|
+
out[cur_y] = ag - rg
|
|
195
|
+
return out
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def margin_series(s: Series) -> dict[int, float]:
|
|
199
|
+
"""{财年: 毛利率%}。"""
|
|
200
|
+
if not s.gross_profit:
|
|
201
|
+
return {}
|
|
202
|
+
out: dict[int, float] = {}
|
|
203
|
+
for y in sorted(set(s.revenue) & set(s.gross_profit)):
|
|
204
|
+
rev, gp = _num(s.revenue.get(y)), _num(s.gross_profit.get(y))
|
|
205
|
+
if rev and gp is not None:
|
|
206
|
+
out[y] = gp / rev * 100
|
|
207
|
+
return out
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def cash_ratio_series(s: Series) -> dict[int, float]:
|
|
211
|
+
"""{财年: 经营现金流/收入}。"""
|
|
212
|
+
if not s.cfo:
|
|
213
|
+
return {}
|
|
214
|
+
out: dict[int, float] = {}
|
|
215
|
+
for y in sorted(set(s.revenue) & set(s.cfo)):
|
|
216
|
+
rev, cfo = _num(s.revenue.get(y)), _num(s.cfo.get(y))
|
|
217
|
+
if rev and cfo is not None:
|
|
218
|
+
out[y] = cfo / rev
|
|
219
|
+
return out
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _items(values: dict[int, float], *, name: str, label: str, unit: str,
|
|
223
|
+
check: str, findings: list[Finding], needs_prior: bool = False) -> list[Item]:
|
|
224
|
+
"""把逐年指标摊成逐项 Item;判定与 detail 直接复用 run_all 的 Finding。
|
|
225
|
+
|
|
226
|
+
判定不在这里另写一套阈值 —— 否则 CLI 与程序本身迟早给出相反的结论
|
|
227
|
+
(正是审查里 P1-d 那类「注释与实现不一致」的近亲)。
|
|
228
|
+
|
|
229
|
+
`needs_prior`:这个指标本身是不是「同比」量。毛利率、现金含量是**某年的水平值**,
|
|
230
|
+
首年没有上期就无从判断它「变没变」,必须报未判定;而应收增速差每个数本身
|
|
231
|
+
就已经是同比结果,首条不需要上期。原实现一刀切 `status="flag" if f else "ok"`,
|
|
232
|
+
把「没查」写成了「正常」。
|
|
233
|
+
"""
|
|
234
|
+
idx = {(f.check, f.ref): f for f in findings}
|
|
235
|
+
years = sorted(values)
|
|
236
|
+
out: list[Item] = []
|
|
237
|
+
for i, y in enumerate(years):
|
|
238
|
+
prev_y = years[i - 1] if i else None
|
|
239
|
+
cur = values[y]
|
|
240
|
+
prior = values[prev_y] if prev_y is not None else None
|
|
241
|
+
if needs_prior and prior is None:
|
|
242
|
+
out.append(Item(
|
|
243
|
+
name=name, label=label, ref=str(y), prior_ref="",
|
|
244
|
+
current=_round(cur, unit), prior=None, change=None,
|
|
245
|
+
unit=unit, status="insufficient",
|
|
246
|
+
detail="无可比上期,未做同比判定",
|
|
247
|
+
))
|
|
248
|
+
continue
|
|
249
|
+
f = idx.get((check, f"FY{y}"))
|
|
250
|
+
out.append(Item(
|
|
251
|
+
name=name, label=label, ref=str(y),
|
|
252
|
+
prior_ref=str(prev_y) if prev_y is not None else "",
|
|
253
|
+
current=_round(cur, unit), prior=_round(prior, unit),
|
|
254
|
+
change=_round(cur - prior, unit) if prior is not None else None,
|
|
255
|
+
unit=unit, status="flag" if f else "ok",
|
|
256
|
+
severity=f.severity if f else "", detail=f.detail if f else "",
|
|
257
|
+
))
|
|
258
|
+
return out
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def assess(s: Series) -> list[Item]:
|
|
262
|
+
"""三条分析性程序的逐年明细。
|
|
263
|
+
|
|
264
|
+
算不出来的程序返回**一条 insufficient 记录**而不是空清单:空清单与
|
|
265
|
+
「跑了且没问题」在输出上完全一样(README 已知边界点过这一条),
|
|
266
|
+
命令行必须把「没查」说出来。
|
|
267
|
+
"""
|
|
268
|
+
findings = run_all(s)
|
|
269
|
+
# 第三个元素 = 这个指标是不是「同比」量(首年没有上期就必须报未判定)
|
|
270
|
+
specs = (
|
|
271
|
+
("revenue_vs_receivables", "应收增速差", "pp",
|
|
272
|
+
"analytics.revenue_vs_receivables", revenue_gap_series(s), False),
|
|
273
|
+
("gross_margin", "毛利率", "%", "analytics.gross_margin_trend",
|
|
274
|
+
margin_series(s), True),
|
|
275
|
+
("cash_conversion", "现金含量", "x", "analytics.cash_conversion",
|
|
276
|
+
cash_ratio_series(s), True),
|
|
277
|
+
)
|
|
278
|
+
out: list[Item] = []
|
|
279
|
+
for name, label, unit, check, values, needs_prior in specs:
|
|
280
|
+
out.extend(_items(values, name=name, label=label, unit=unit,
|
|
281
|
+
check=check, findings=findings, needs_prior=needs_prior)
|
|
282
|
+
or [Item(name=name, label=label, ref="", prior_ref="",
|
|
283
|
+
current=None, prior=None, change=None, unit=unit,
|
|
284
|
+
status="insufficient")])
|
|
285
|
+
return out
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def series_from_years(years: object) -> Series:
|
|
289
|
+
"""把 facts JSON 的 {"2026": {"revenue": ...}} 转成 Series。
|
|
290
|
+
|
|
291
|
+
每列独立收:导出表整列缺失是常态,一列没有不该拖垮另外两列。
|
|
292
|
+
只有收入一列为空算输入错误 —— 三条程序全以收入为基准,没收入什么也算不出来。
|
|
293
|
+
"""
|
|
294
|
+
if not isinstance(years, dict) or not years:
|
|
295
|
+
raise ValueError("facts 里没有 years 对象")
|
|
296
|
+
|
|
297
|
+
def col(key: str) -> dict[int, float]:
|
|
298
|
+
out: dict[int, float] = {}
|
|
299
|
+
for raw_year, row in years.items():
|
|
300
|
+
if not isinstance(row, dict):
|
|
301
|
+
continue
|
|
302
|
+
try:
|
|
303
|
+
year = int(raw_year)
|
|
304
|
+
except (TypeError, ValueError):
|
|
305
|
+
raise ValueError(f"财年不是整数:{raw_year!r}") from None
|
|
306
|
+
v = _num(row.get(key))
|
|
307
|
+
if v is not None:
|
|
308
|
+
out[year] = float(v)
|
|
309
|
+
return out
|
|
310
|
+
|
|
311
|
+
revenue = col("revenue")
|
|
312
|
+
if not revenue:
|
|
313
|
+
raise ValueError("years 里没有任何 revenue 数字")
|
|
314
|
+
return Series(revenue=revenue,
|
|
315
|
+
receivables=col("receivables") or None,
|
|
316
|
+
gross_profit=col("gross_profit") or None,
|
|
317
|
+
cfo=col("cfo") or None)
|
auditloop/checks.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""三个高频审计程序:银行存款余额调节、应收账款账龄、收入截止测试。
|
|
2
|
+
|
|
3
|
+
全部纯函数、无 IO、无随机 —— 同样的输入永远给同样的例外清单。
|
|
4
|
+
会计师复核的是「你为什么把这一条列为例外」,不是「模型觉得」。
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from collections import Counter, defaultdict
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import date, timedelta
|
|
11
|
+
|
|
12
|
+
from .models import (CLASSIFICATION, COMPLETENESS, CUTOFF, EXISTENCE, VALUATION,
|
|
13
|
+
BankLine, Entry, Finding, Invoice)
|
|
14
|
+
|
|
15
|
+
TOL = 0.01
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class ReconResult:
|
|
20
|
+
matched: list[tuple[Entry, BankLine]] = field(default_factory=list)
|
|
21
|
+
unmatched_gl: list[Entry] = field(default_factory=list)
|
|
22
|
+
unmatched_bank: list[BankLine] = field(default_factory=list)
|
|
23
|
+
amount_diff: list[tuple[Entry, BankLine]] = field(default_factory=list)
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def gl_total(self) -> float:
|
|
27
|
+
return round(sum(e.amount for e in self.unmatched_gl), 2)
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def bank_total(self) -> float:
|
|
31
|
+
return round(sum(b.amount for b in self.unmatched_bank), 2)
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def difference(self) -> float:
|
|
35
|
+
"""调节后差额:应等于未达账项净额。"""
|
|
36
|
+
return round(self.bank_total - self.gl_total, 2)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
CASH_ACCOUNTS = ("银行存款", "现金", "cash", "bank")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def reconcile_bank(entries: list[Entry], lines: list[BankLine], window_days: int = 3,
|
|
43
|
+
accounts: tuple[str, ...] = CASH_ACCOUNTS) -> ReconResult:
|
|
44
|
+
"""按金额 + 日期窗口做 1:1 匹配;金额相同但日期超出窗口记为「时间性差异」。
|
|
45
|
+
|
|
46
|
+
只对现金类科目做调节 —— 把管理费用/收入科目拿去跟银行流水碰,会造出一堆假例外。
|
|
47
|
+
"""
|
|
48
|
+
res = ReconResult()
|
|
49
|
+
used: set[int] = set()
|
|
50
|
+
# 科目名大小写不敏感:底稿里几乎都写 "Bank Account USD" / "CASH-1000",
|
|
51
|
+
# 而 CASH_ACCOUNTS 里是小写 cash/bank —— 区分大小写时一整批现金科目一个都不匹配,
|
|
52
|
+
# 还全部落到「银行已记、企业未记」一侧,看起来像"漏记了所有银行流水"。
|
|
53
|
+
accounts_cf = tuple(a.casefold() for a in accounts)
|
|
54
|
+
cash = [e for e in entries if any(a in e.account.casefold() for a in accounts_cf)]
|
|
55
|
+
for e in sorted(cash, key=lambda x: x.date):
|
|
56
|
+
best: tuple[int, int] | None = None
|
|
57
|
+
for i, b in enumerate(lines):
|
|
58
|
+
if i in used or abs(b.amount - e.amount) > TOL:
|
|
59
|
+
continue
|
|
60
|
+
delta = abs((b.date - e.date).days)
|
|
61
|
+
if best is None or delta < best[1]:
|
|
62
|
+
best = (i, delta)
|
|
63
|
+
if best is None:
|
|
64
|
+
res.unmatched_gl.append(e)
|
|
65
|
+
continue
|
|
66
|
+
idx, delta = best
|
|
67
|
+
used.add(idx)
|
|
68
|
+
if delta <= window_days:
|
|
69
|
+
res.matched.append((e, lines[idx]))
|
|
70
|
+
else:
|
|
71
|
+
res.amount_diff.append((e, lines[idx]))
|
|
72
|
+
res.unmatched_bank = [b for i, b in enumerate(lines) if i not in used]
|
|
73
|
+
return res
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class AgingBucket:
|
|
78
|
+
label: str
|
|
79
|
+
invoices: list[Invoice] = field(default_factory=list)
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def total(self) -> float:
|
|
83
|
+
return round(sum(i.amount for i in self.invoices), 2)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
BUCKETS = [("current", None, 0), ("1-30", 1, 30), ("31-60", 31, 60), ("61-90", 61, 90), (">90", 91, None)]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
UNKNOWN_DUE_LABEL = "无到期日"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def ar_aging(invoices: list[Invoice], as_of: date) -> list[AgingBucket]:
|
|
93
|
+
"""按到期日计算逾期天数。未到期归 current,缺到期日单列一桶。
|
|
94
|
+
|
|
95
|
+
缺到期日的发票不进任何逾期桶:算不出账龄就报不出逾期,硬塞进 current
|
|
96
|
+
会让「未到期」这个结论凭空成立。单列一桶,让会计师一眼看到有多少笔算不了。
|
|
97
|
+
"""
|
|
98
|
+
out = [AgingBucket(label=lbl) for lbl, _, _ in BUCKETS]
|
|
99
|
+
out.append(AgingBucket(label=UNKNOWN_DUE_LABEL))
|
|
100
|
+
for inv in invoices:
|
|
101
|
+
if inv.due_date is None:
|
|
102
|
+
out[-1].invoices.append(inv)
|
|
103
|
+
continue
|
|
104
|
+
days = (as_of - inv.due_date).days
|
|
105
|
+
for bucket, (_, lo, hi) in zip(out, BUCKETS):
|
|
106
|
+
if lo is None:
|
|
107
|
+
continue
|
|
108
|
+
if hi is None and days >= lo:
|
|
109
|
+
bucket.invoices.append(inv)
|
|
110
|
+
break
|
|
111
|
+
if days >= lo and days <= hi:
|
|
112
|
+
bucket.invoices.append(inv)
|
|
113
|
+
break
|
|
114
|
+
else:
|
|
115
|
+
out[0].invoices.append(inv)
|
|
116
|
+
return out
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def revenue_cutoff(invoices: list[Invoice], period_end: date, tolerance_days: int = 0) -> list[Finding]:
|
|
120
|
+
"""截止测试:确认收入但发货在期末之后(含未发货)→ 截止例外。
|
|
121
|
+
|
|
122
|
+
tolerance_days 允许会计师按重要性设宽限(例如期末后 1 天内发货不调整)。
|
|
123
|
+
"""
|
|
124
|
+
findings: list[Finding] = []
|
|
125
|
+
for inv in invoices:
|
|
126
|
+
if not inv.recognized:
|
|
127
|
+
continue
|
|
128
|
+
if inv.shipped_date is None:
|
|
129
|
+
# 未发货分支同样必须先过「收入是否落在本期内」——原实现直接报,
|
|
130
|
+
# 下期收入(2027-01-15,期末 2026-09-30)被成本期截止例外,
|
|
131
|
+
# 而本期收入确认 + 无发货记录才是真例外。
|
|
132
|
+
if inv.revenue_date > period_end:
|
|
133
|
+
continue
|
|
134
|
+
findings.append(Finding(
|
|
135
|
+
check="revenue_cutoff", assertion=CUTOFF, ref=inv.invoice_id, severity="high",
|
|
136
|
+
detail=f"{inv.customer} 已确认收入但无发货记录(期末 {period_end})", amount=inv.amount))
|
|
137
|
+
continue
|
|
138
|
+
if inv.shipped_date > period_end + timedelta(days=tolerance_days) and inv.revenue_date <= period_end:
|
|
139
|
+
findings.append(Finding(
|
|
140
|
+
check="revenue_cutoff", assertion=CUTOFF, ref=inv.invoice_id, severity="high",
|
|
141
|
+
detail=(f"{inv.customer} 收入确认日 {inv.revenue_date} 早于发货日 {inv.shipped_date},"
|
|
142
|
+
f"期末 {period_end} 前未发货却确认收入"), amount=inv.amount))
|
|
143
|
+
return findings
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def duplicate_payments(entries: list[Entry], window_days: int = 5) -> list[Finding]:
|
|
147
|
+
"""同一供应商、同金额、短期内重复付款 —— 存在性/计价的高频舞弊信号。"""
|
|
148
|
+
groups: dict[tuple[str, float], list[Entry]] = defaultdict(list)
|
|
149
|
+
for e in entries:
|
|
150
|
+
if e.amount < 0 and e.vendor:
|
|
151
|
+
groups[(e.vendor, round(abs(e.amount), 2))].append(e)
|
|
152
|
+
findings: list[Finding] = []
|
|
153
|
+
for (vendor, amt), items in groups.items():
|
|
154
|
+
items.sort(key=lambda x: x.date)
|
|
155
|
+
for prev, cur in zip(items, items[1:]):
|
|
156
|
+
if (cur.date - prev.date).days <= window_days:
|
|
157
|
+
findings.append(Finding(
|
|
158
|
+
check="duplicate_payment", assertion=EXISTENCE, ref=f"{prev.entry_id}/{cur.entry_id}",
|
|
159
|
+
severity="high",
|
|
160
|
+
detail=f"{vendor} 在 {prev.date} 与 {cur.date} 各付 {amt:,.2f},疑似重复付款",
|
|
161
|
+
amount=amt))
|
|
162
|
+
return findings
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def ar_negative_or_zero(invoices: list[Invoice]) -> list[Finding]:
|
|
166
|
+
out = [Finding(check="ar_sanity", assertion=VALUATION, ref=i.invoice_id, severity="medium",
|
|
167
|
+
detail=f"{i.customer} 发票金额异常:{i.amount:,.2f}", amount=i.amount)
|
|
168
|
+
for i in invoices if i.amount <= 0]
|
|
169
|
+
return out
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def missing_due_date(invoices: list[Invoice]) -> list[Finding]:
|
|
173
|
+
"""到期日缺失或倒挂 —— 两种都让账龄不可靠,但原因不同,必须分开写。"""
|
|
174
|
+
out: list[Finding] = []
|
|
175
|
+
for i in invoices:
|
|
176
|
+
if i.due_date is None:
|
|
177
|
+
out.append(Finding(check="ar_completeness", assertion=COMPLETENESS,
|
|
178
|
+
ref=i.invoice_id, severity="medium",
|
|
179
|
+
detail=f"{i.customer} 到期日缺失,无法计算账龄", amount=i.amount))
|
|
180
|
+
elif i.due_date < i.issue_date:
|
|
181
|
+
out.append(Finding(check="ar_completeness", assertion=COMPLETENESS,
|
|
182
|
+
ref=i.invoice_id, severity="low",
|
|
183
|
+
detail=f"{i.customer} 到期日早于开票日,账龄不可靠", amount=i.amount))
|
|
184
|
+
return out
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def classification_summary(entries: list[Entry]) -> dict[str, float]:
|
|
188
|
+
"""按科目汇总借贷净额 —— 底稿第一页永远需要这张表。"""
|
|
189
|
+
agg: dict[str, float] = defaultdict(float)
|
|
190
|
+
for e in entries:
|
|
191
|
+
agg[e.account] += e.amount
|
|
192
|
+
return {k: round(v, 2) for k, v in sorted(agg.items())}
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def vendor_concentration(entries: list[Entry]) -> list[tuple[str, float, float]]:
|
|
196
|
+
"""供应商集中度:帮助判断是否存在未披露的关联方。"""
|
|
197
|
+
spend: Counter = Counter()
|
|
198
|
+
for e in entries:
|
|
199
|
+
if e.amount < 0 and e.vendor:
|
|
200
|
+
spend[e.vendor] += abs(e.amount)
|
|
201
|
+
total = sum(spend.values()) or 1.0
|
|
202
|
+
return [(v, round(a, 2), round(a / total, 4)) for v, a in spend.most_common()]
|