ofdkit 0.2.0__tar.gz → 0.3.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ofdkit
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Read OFD documents (GB/T 33190) and Chinese e-invoices: text, invoice fields, and AI tool integrations.
5
5
  Keywords: ofd,gb/t 33190,e-invoice,fapiao,电子发票,数电票,mcp
6
6
  License-Expression: Apache-2.0
@@ -30,8 +30,8 @@ Description-Content-Type: text/markdown
30
30
 
31
31
  A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese fixed-layout format used for e-invoices and official documents): extract text and invoice fields, and use them from AI tools.
32
32
 
33
- > 状态:0.2 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
34
- > Status: 0.2, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
33
+ > 状态:0.3 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
34
+ > Status: 0.3, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
35
35
 
36
36
  ## 能做什么 / What it does
37
37
 
@@ -39,6 +39,8 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
39
39
  Show an invoice: number, date, buyer, seller, amounts and line items, with one command.
40
40
  - 把一个文件夹里的发票汇总到 Excel,也能直接读税务平台批量下载的 .zip 压缩包。发票号码保持原样(不会变成 2.4E+19),金额可以直接求和,重复的发票会标出来。
41
41
  Summarise a folder of invoices, or a .zip archive downloaded from the tax service, into an Excel workbook: invoice numbers stay intact, amounts are numbers, duplicates are flagged.
42
+ - 报销帮手:检查发票抬头(购买方名称、税号)对不对;按发票内容给文件改名,可以预览、可以改回去。
43
+ For reimbursement: check that invoices are made out to the right buyer, and rename invoice files after their contents, with a preview and an undo.
42
44
  - 按阅读顺序提取文字,包括模板和复合对象里的文字。
43
45
  Text in reading order, including text in templates and composite objects.
44
46
  - 给程序和 AI 用:发票字段输出 JSON,提供 MCP 服务器、Agent Skill 和 MarkItDown 插件。
@@ -93,6 +95,25 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
93
95
  Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红并写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行。
94
96
  The workbook has two sheets: 发票 (one row per invoice, with totals; duplicates in yellow, unreadable files in red with the reason) and 明细 (one row per line item). Totals use SUBTOTAL, so they follow filters.
95
97
 
98
+ 5. 检查发票抬头:加上 `--buyer`,购买方名称或税号不是你公司的发票会标出来(Excel 里标橙色)。名称和税号都要查,就写两次:
99
+ Check who the invoices are made out to: with `--buyer`, invoices for another buyer name or tax ID are flagged (orange in Excel). Repeat it to check both:
100
+
101
+ ```bash
102
+ ofdkit 发票文件夹 --buyer 某某有限公司 --buyer 91310000XXXXXXXXXX
103
+ ```
104
+
105
+ 6. 按发票内容给文件改名,例如 `dzfp_2411…_20240528.ofd` 改成 `2024-05-28_某某公司_4449.00_2411….ofd`。不加 `--apply` 只是预览;同名的 PDF、XML 会一起改;改名记录可以用 `--undo` 改回去:
106
+ Rename invoice files after their contents. Without `--apply` it only previews; PDF and XML copies with the same name are renamed too; `--undo` restores the old names from the log:
107
+
108
+ ```bash
109
+ ofdkit rename 发票文件夹 # 预览 / preview
110
+ ofdkit rename 发票文件夹 --apply # 改名 / rename
111
+ ofdkit rename --undo 发票文件夹/改名记录_20261028_093000.csv
112
+ ```
113
+
114
+ 名字的格式可以改,例如 `--pattern "{开票日期}_{购买方}_{商品}"`。可以用的字段:开票日期、发票号码、发票代码、发票种类、销售方、销售方税号、购买方、购买方税号、金额、税额、价税合计、商品、原文件名。
115
+ The name format can be changed with `--pattern`; fields are listed by `ofdkit rename --help` (English names such as `{date}`, `{seller}` and `{total}` work too).
116
+
96
117
  ## 命令行 / Command line
97
118
 
98
119
  ```bash
@@ -100,14 +121,16 @@ ofdkit 文件.ofd # 看发票,不是发票就显
100
121
  ofdkit 文件夹或压缩包.zip # 发票列表和合计 / list invoices with totals
101
122
  ofdkit batch 文件夹 -o 发票汇总.xlsx # 导出 Excel / export to Excel
102
123
  ofdkit batch 文件夹 -o 发票汇总.csv # 导出 CSV(给程序用)/ export CSV for programs
124
+ ofdkit 文件夹 --buyer 公司名或税号 # 检查发票抬头 / check the buyer
125
+ ofdkit rename 文件夹 # 按内容改名(先预览)/ rename after contents (preview first)
103
126
  ofdkit text 文件.ofd # 提取文字 / print text
104
127
  ofdkit invoice 发票.ofd # 发票字段(JSON)/ invoice fields as JSON
105
128
  ofdkit info 文件.ofd # 页数、作者等信息 / pages and metadata
106
129
  ofdkit describe 文件.ofd -o 结构.json # 打码的结构,用于报告问题 / masked structure for bug reports
107
130
  ```
108
131
 
109
- `batch` 和 `show` 加 `-r` 会连子文件夹一起找。`ofdkit 文件.ofd` 是 `ofdkit show 文件.ofd` 的简写。
110
- Add `-r` to `batch` and `show` to include subfolders. `ofdkit PATH` is short for `ofdkit show PATH`.
132
+ `show`、`batch` 和 `rename` 加 `-r` 会连子文件夹一起找。`ofdkit 文件.ofd` 是 `ofdkit show 文件.ofd` 的简写。
133
+ Add `-r` to `show`, `batch` and `rename` to include subfolders. `ofdkit PATH` is short for `ofdkit show PATH`.
111
134
 
112
135
  `ofdkit invoice` 的输出示例(数据是虚构的)/ Example output (fictional data):
113
136
 
@@ -151,7 +174,7 @@ Lets Claude, Codex, Cursor and other AI tools read OFD files. Requires [uv](http
151
174
  | `read_ofd_text` | 按阅读顺序提取文字,可选 Markdown 和页码范围 / text in reading order, optional Markdown and page range |
152
175
  | `read_ofd_invoice` | 发票字段 / invoice fields |
153
176
  | `ofd_info` | 页数、尺寸、元数据 / pages, sizes, metadata |
154
- | `list_ofd_invoices` | 汇总一个文件夹里的发票 / summarise a folder of invoices |
177
+ | `list_ofd_invoices` | 汇总一个文件夹里的发票,可以检查抬头 / summarise a folder of invoices, optionally checking the buyer |
155
178
 
156
179
  Claude Code:
157
180
 
@@ -213,9 +236,9 @@ with ofdkit.open("发票.ofd") as doc:
213
236
  print(invoice.invoice_number, invoice.total_amount)
214
237
 
215
238
  # 文件夹、.zip 压缩包或多个文件 / folders, ZIP archives or several files
216
- for result in ofdkit.read_invoices("发票文件夹", recursive=True):
239
+ for result in ofdkit.read_invoices("发票文件夹", recursive=True, buyer=["某某有限公司"]):
217
240
  if result.invoice:
218
- print(result.file, result.invoice.total_amount, "重复" if result.duplicate else "")
241
+ print(result.file, result.invoice.total_amount, "重复" if result.duplicate else "", result.buyer_mismatch)
219
242
  else:
220
243
  print(result.file, result.error)
221
244
  ```
@@ -4,8 +4,8 @@
4
4
 
5
5
  A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese fixed-layout format used for e-invoices and official documents): extract text and invoice fields, and use them from AI tools.
6
6
 
7
- > 状态:0.2 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
8
- > Status: 0.2, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
7
+ > 状态:0.3 版,接口以后可能还会调整。更新记录见 [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md)。
8
+ > Status: 0.3, the API may still change. See the [CHANGELOG](https://github.com/Edgar-311/ofdkit/blob/main/CHANGELOG.md).
9
9
 
10
10
  ## 能做什么 / What it does
11
11
 
@@ -13,6 +13,8 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
13
13
  Show an invoice: number, date, buyer, seller, amounts and line items, with one command.
14
14
  - 把一个文件夹里的发票汇总到 Excel,也能直接读税务平台批量下载的 .zip 压缩包。发票号码保持原样(不会变成 2.4E+19),金额可以直接求和,重复的发票会标出来。
15
15
  Summarise a folder of invoices, or a .zip archive downloaded from the tax service, into an Excel workbook: invoice numbers stay intact, amounts are numbers, duplicates are flagged.
16
+ - 报销帮手:检查发票抬头(购买方名称、税号)对不对;按发票内容给文件改名,可以预览、可以改回去。
17
+ For reimbursement: check that invoices are made out to the right buyer, and rename invoice files after their contents, with a preview and an undo.
16
18
  - 按阅读顺序提取文字,包括模板和复合对象里的文字。
17
19
  Text in reading order, including text in templates and composite objects.
18
20
  - 给程序和 AI 用:发票字段输出 JSON,提供 MCP 服务器、Agent Skill 和 MarkItDown 插件。
@@ -67,6 +69,25 @@ A lightweight Python toolkit for reading OFD documents (GB/T 33190, the Chinese
67
69
  Excel 文件有两张表:"发票"每张发票一行,最后是合计;"明细"每个商品或服务一行。重复的发票标黄,读不出来的文件标红并写明原因。合计用的是 SUBTOTAL,筛选以后只算看得见的行。
68
70
  The workbook has two sheets: 发票 (one row per invoice, with totals; duplicates in yellow, unreadable files in red with the reason) and 明细 (one row per line item). Totals use SUBTOTAL, so they follow filters.
69
71
 
72
+ 5. 检查发票抬头:加上 `--buyer`,购买方名称或税号不是你公司的发票会标出来(Excel 里标橙色)。名称和税号都要查,就写两次:
73
+ Check who the invoices are made out to: with `--buyer`, invoices for another buyer name or tax ID are flagged (orange in Excel). Repeat it to check both:
74
+
75
+ ```bash
76
+ ofdkit 发票文件夹 --buyer 某某有限公司 --buyer 91310000XXXXXXXXXX
77
+ ```
78
+
79
+ 6. 按发票内容给文件改名,例如 `dzfp_2411…_20240528.ofd` 改成 `2024-05-28_某某公司_4449.00_2411….ofd`。不加 `--apply` 只是预览;同名的 PDF、XML 会一起改;改名记录可以用 `--undo` 改回去:
80
+ Rename invoice files after their contents. Without `--apply` it only previews; PDF and XML copies with the same name are renamed too; `--undo` restores the old names from the log:
81
+
82
+ ```bash
83
+ ofdkit rename 发票文件夹 # 预览 / preview
84
+ ofdkit rename 发票文件夹 --apply # 改名 / rename
85
+ ofdkit rename --undo 发票文件夹/改名记录_20261028_093000.csv
86
+ ```
87
+
88
+ 名字的格式可以改,例如 `--pattern "{开票日期}_{购买方}_{商品}"`。可以用的字段:开票日期、发票号码、发票代码、发票种类、销售方、销售方税号、购买方、购买方税号、金额、税额、价税合计、商品、原文件名。
89
+ The name format can be changed with `--pattern`; fields are listed by `ofdkit rename --help` (English names such as `{date}`, `{seller}` and `{total}` work too).
90
+
70
91
  ## 命令行 / Command line
71
92
 
72
93
  ```bash
@@ -74,14 +95,16 @@ ofdkit 文件.ofd # 看发票,不是发票就显
74
95
  ofdkit 文件夹或压缩包.zip # 发票列表和合计 / list invoices with totals
75
96
  ofdkit batch 文件夹 -o 发票汇总.xlsx # 导出 Excel / export to Excel
76
97
  ofdkit batch 文件夹 -o 发票汇总.csv # 导出 CSV(给程序用)/ export CSV for programs
98
+ ofdkit 文件夹 --buyer 公司名或税号 # 检查发票抬头 / check the buyer
99
+ ofdkit rename 文件夹 # 按内容改名(先预览)/ rename after contents (preview first)
77
100
  ofdkit text 文件.ofd # 提取文字 / print text
78
101
  ofdkit invoice 发票.ofd # 发票字段(JSON)/ invoice fields as JSON
79
102
  ofdkit info 文件.ofd # 页数、作者等信息 / pages and metadata
80
103
  ofdkit describe 文件.ofd -o 结构.json # 打码的结构,用于报告问题 / masked structure for bug reports
81
104
  ```
82
105
 
83
- `batch` 和 `show` 加 `-r` 会连子文件夹一起找。`ofdkit 文件.ofd` 是 `ofdkit show 文件.ofd` 的简写。
84
- Add `-r` to `batch` and `show` to include subfolders. `ofdkit PATH` is short for `ofdkit show PATH`.
106
+ `show`、`batch` 和 `rename` 加 `-r` 会连子文件夹一起找。`ofdkit 文件.ofd` 是 `ofdkit show 文件.ofd` 的简写。
107
+ Add `-r` to `show`, `batch` and `rename` to include subfolders. `ofdkit PATH` is short for `ofdkit show PATH`.
85
108
 
86
109
  `ofdkit invoice` 的输出示例(数据是虚构的)/ Example output (fictional data):
87
110
 
@@ -125,7 +148,7 @@ Lets Claude, Codex, Cursor and other AI tools read OFD files. Requires [uv](http
125
148
  | `read_ofd_text` | 按阅读顺序提取文字,可选 Markdown 和页码范围 / text in reading order, optional Markdown and page range |
126
149
  | `read_ofd_invoice` | 发票字段 / invoice fields |
127
150
  | `ofd_info` | 页数、尺寸、元数据 / pages, sizes, metadata |
128
- | `list_ofd_invoices` | 汇总一个文件夹里的发票 / summarise a folder of invoices |
151
+ | `list_ofd_invoices` | 汇总一个文件夹里的发票,可以检查抬头 / summarise a folder of invoices, optionally checking the buyer |
129
152
 
130
153
  Claude Code:
131
154
 
@@ -187,9 +210,9 @@ with ofdkit.open("发票.ofd") as doc:
187
210
  print(invoice.invoice_number, invoice.total_amount)
188
211
 
189
212
  # 文件夹、.zip 压缩包或多个文件 / folders, ZIP archives or several files
190
- for result in ofdkit.read_invoices("发票文件夹", recursive=True):
213
+ for result in ofdkit.read_invoices("发票文件夹", recursive=True, buyer=["某某有限公司"]):
191
214
  if result.invoice:
192
- print(result.file, result.invoice.total_amount, "重复" if result.duplicate else "")
215
+ print(result.file, result.invoice.total_amount, "重复" if result.duplicate else "", result.buyer_mismatch)
193
216
  else:
194
217
  print(result.file, result.error)
195
218
  ```
@@ -4,7 +4,7 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "ofdkit"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "Read OFD documents (GB/T 33190) and Chinese e-invoices: text, invoice fields, and AI tool integrations."
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -12,7 +12,7 @@ import zipfile
12
12
  import zlib
13
13
  from collections import Counter
14
14
  from collections.abc import Iterable, Sequence
15
- from dataclasses import dataclass
15
+ from dataclasses import dataclass, field
16
16
  from decimal import Decimal, InvalidOperation
17
17
  from pathlib import Path
18
18
  from typing import Any
@@ -43,6 +43,7 @@ COLUMNS = [
43
43
 
44
44
  NO_INVOICE = "no invoice data"
45
45
  DUPLICATE = "duplicate invoice number"
46
+ BUYER_MISMATCH = "buyer is not"
46
47
  EMPTY_ARCHIVE = "no .ofd files in this ZIP archive"
47
48
 
48
49
  #: Largest OFD file, uncompressed, that is read from inside a ZIP archive.
@@ -62,21 +63,28 @@ class InvoiceFile:
62
63
  error: str | None = None
63
64
  #: Another file has the same invoice number (and invoice code, for older invoices).
64
65
  duplicate: bool = False
66
+ #: Expected buyer names or tax IDs (see :func:`check_buyer`) this invoice does not match.
67
+ buyer_mismatch: list[str] = field(default_factory=list)
65
68
 
66
69
 
67
- def read_invoices(paths: str | Path | Iterable[str | Path], recursive: bool = False) -> list[InvoiceFile]:
70
+ def read_invoices(
71
+ paths: str | Path | Iterable[str | Path], recursive: bool = False, buyer: Sequence[str] = ()
72
+ ) -> list[InvoiceFile]:
68
73
  """Read every OFD file in ``paths``: files, folders and ZIP archives of OFD files.
69
74
 
70
75
  Folders are searched for ``.ofd`` files and for ZIP archives that contain some;
71
- ``recursive`` also searches their subfolders. Raises FileNotFoundError if a path
72
- does not exist.
76
+ ``recursive`` also searches their subfolders. With ``buyer`` (company names or tax
77
+ IDs), invoices made out to someone else are noted, see :func:`check_buyer`. Raises
78
+ FileNotFoundError if a path does not exist.
73
79
  """
74
80
  if isinstance(paths, (str, Path)):
75
81
  paths = [paths]
76
82
  files, missing = find_ofd_files(paths, recursive)
77
83
  if missing:
78
84
  raise FileNotFoundError(f"{missing[0]} does not exist")
79
- return read_invoice_files(files)
85
+ results = read_invoice_files(files)
86
+ check_buyer(results, buyer)
87
+ return results
80
88
 
81
89
 
82
90
  def find_ofd_files(paths: Iterable[str | Path], recursive: bool = False) -> tuple[list[Path], list[str]]:
@@ -136,7 +144,11 @@ def invoice_row(result: InvoiceFile | Path) -> dict[str, Any]:
136
144
  row["error"] = result.error or ""
137
145
  invoice = result.invoice
138
146
  if invoice is not None:
139
- warnings = [*invoice.warnings, *([DUPLICATE] if result.duplicate else [])]
147
+ warnings = [
148
+ *invoice.warnings,
149
+ *([DUPLICATE] if result.duplicate else []),
150
+ *(f"{BUYER_MISMATCH} {expected}" for expected in result.buyer_mismatch),
151
+ ]
140
152
  row.update(
141
153
  {
142
154
  "invoice_number": invoice.invoice_number or "",
@@ -169,6 +181,47 @@ def item_names(invoice: Invoice, limit: int | None = None) -> str:
169
181
  return ";".join(names)
170
182
 
171
183
 
184
+ _TAX_ID = re.compile(r"(?=.*\d)[0-9A-Z]{15,20}")
185
+
186
+
187
+ def check_buyer(results: Sequence[InvoiceFile], expected: Sequence[str]) -> None:
188
+ """Note the invoices whose buyer is not ``expected`` in :attr:`InvoiceFile.buyer_mismatch`.
189
+
190
+ Each expected value is a company name or a tax ID (统一社会信用代码, 15 to 20 letters
191
+ and digits). Names are compared without spaces, case or full-width brackets.
192
+ """
193
+ for result in results:
194
+ if result.invoice is not None:
195
+ result.buyer_mismatch = buyer_mismatch(result.invoice, expected)
196
+
197
+
198
+ def buyer_mismatch(invoice: Invoice, expected: Sequence[str]) -> list[str]:
199
+ """The expected buyer names or tax IDs that ``invoice`` does not match."""
200
+ missed = []
201
+ for value in expected:
202
+ if not value.strip():
203
+ continue
204
+ if _is_tax_id(value):
205
+ matched = _normal_tax_id(invoice.buyer.tax_id or "") == _normal_tax_id(value)
206
+ else:
207
+ matched = _normal_name(invoice.buyer.name or "") == _normal_name(value)
208
+ if not matched:
209
+ missed.append(value.strip())
210
+ return missed
211
+
212
+
213
+ def _is_tax_id(value: str) -> bool:
214
+ return bool(_TAX_ID.fullmatch(_normal_tax_id(value)))
215
+
216
+
217
+ def _normal_tax_id(value: str) -> str:
218
+ return re.sub(r"\s+", "", value).upper()
219
+
220
+
221
+ def _normal_name(value: str) -> str:
222
+ return re.sub(r"\s+", "", value).replace("(", "(").replace(")", ")").casefold()
223
+
224
+
172
225
  _TOTALS_WARNING = re.compile(r"amount_without_tax \+ tax_amount != total_amount \((.*) \+ (.*) != (.*)\)")
173
226
 
174
227
 
@@ -185,7 +238,13 @@ def problems(result: InvoiceFile) -> list[str]:
185
238
  found = []
186
239
  if result.duplicate:
187
240
  found.append("发票号码重复")
188
- for warning in result.invoice.warnings if result.invoice else []:
241
+ invoice = result.invoice
242
+ for expected in result.buyer_mismatch:
243
+ tax_id = _is_tax_id(expected)
244
+ actual = (invoice.buyer.tax_id if tax_id else invoice.buyer.name) if invoice else None
245
+ label = "购买方税号" if tax_id else "购买方"
246
+ found.append(f"{label}不是 {expected}(发票上是 {actual or '空的'})")
247
+ for warning in invoice.warnings if invoice else []:
189
248
  match = _TOTALS_WARNING.fullmatch(warning)
190
249
  found.append(f"金额 + 税额 ≠ 价税合计({match[1]} + {match[2]} ≠ {match[3]})" if match else warning)
191
250
  return found
@@ -217,6 +276,7 @@ def summary(results: Sequence[InvoiceFile | dict[str, Any]]) -> dict[str, Any]:
217
276
  "without_invoice_data": sum(1 for row in rows if row["error"] == NO_INVOICE),
218
277
  "errors": sum(1 for row in rows if row["error"] and row["error"] != NO_INVOICE),
219
278
  "duplicates": len(invoices) - len(unique),
279
+ "buyer_mismatches": sum(1 for row in invoices if BUYER_MISMATCH in row["warnings"]),
220
280
  "amount_without_tax_sum": total("amount_without_tax", invoices),
221
281
  "tax_amount_sum": total("tax_amount", invoices),
222
282
  "total_amount_sum": total("total_amount", invoices),
@@ -16,6 +16,8 @@ from .batch import (
16
16
  COLUMNS,
17
17
  NO_INVOICE,
18
18
  InvoiceFile,
19
+ buyer_mismatch,
20
+ check_buyer,
19
21
  find_ofd_files,
20
22
  invoice_row,
21
23
  problems,
@@ -25,6 +27,7 @@ from .batch import (
25
27
  from .document import OFDDocument
26
28
  from .errors import OFDError
27
29
  from .markdown import document_markdown
30
+ from .rename import DEFAULT_PATTERN, FIELDS
28
31
  from .report import display_width, invoice_report, pad, summary_text, table_report
29
32
 
30
33
  EXIT_OK = 0
@@ -34,13 +37,15 @@ EXIT_ERROR = 2
34
37
  # Kept for backward compatibility with code that imported it from here.
35
38
  CSV_COLUMNS = COLUMNS
36
39
 
37
- COMMANDS = ("show", "info", "text", "invoice", "batch", "describe", "mcp")
40
+ COMMANDS = ("show", "info", "text", "invoice", "batch", "rename", "describe", "mcp")
38
41
 
39
42
  EXAMPLES = """\
40
43
  例子 / examples:
41
44
  ofdkit 发票.ofd 看一张发票,或者一个文件的文字
42
45
  ofdkit 发票文件夹 列出文件夹(或 .zip 压缩包)里的发票和合计
43
46
  ofdkit batch 发票文件夹 -o 发票汇总.xlsx 导出到 Excel
47
+ ofdkit 发票文件夹 --buyer 公司名或税号 检查发票抬头对不对
48
+ ofdkit rename 发票文件夹 按发票内容给文件改名(先预览)
44
49
  ofdkit text 文件.ofd 提取文字
45
50
  ofdkit invoice 发票.ofd 发票字段(JSON,给程序用)
46
51
  """
@@ -63,6 +68,7 @@ def build_parser() -> argparse.ArgumentParser:
63
68
  )
64
69
  show.add_argument("paths", nargs="+", metavar="路径", help="OFD 文件、文件夹或 .zip 压缩包")
65
70
  show.add_argument("-r", "--recursive", action="store_true", help="也看子文件夹")
71
+ _add_buyer_option(show)
66
72
 
67
73
  info = commands.add_parser("info", help="页数、作者等信息,以及是不是发票")
68
74
  info.add_argument("file", metavar="文件", help="OFD 文件")
@@ -86,6 +92,20 @@ def build_parser() -> argparse.ArgumentParser:
86
92
  help="保存到这个文件:.xlsx 是 Excel 表格(推荐),其他是 CSV(UTF-8,带 BOM)。不写就把 CSV 显示在屏幕上",
87
93
  )
88
94
  batch.add_argument("-r", "--recursive", action="store_true", help="也看子文件夹")
95
+ _add_buyer_option(batch)
96
+
97
+ rename = commands.add_parser("rename", help="按发票内容给文件改名:先预览,加 --apply 才真的改")
98
+ rename.add_argument("paths", nargs="*", metavar="路径", help="OFD 文件或文件夹")
99
+ rename.add_argument("-r", "--recursive", action="store_true", help="也改子文件夹里的文件")
100
+ rename.add_argument(
101
+ "--pattern",
102
+ default=DEFAULT_PATTERN,
103
+ metavar="格式",
104
+ help=f"新名字的格式,默认 {DEFAULT_PATTERN}。可以用的字段:{'、'.join(FIELDS)}",
105
+ )
106
+ rename.add_argument("--apply", action="store_true", help="真的改名(不加就只预览)")
107
+ rename.add_argument("--only-ofd", action="store_true", help="只改 .ofd 文件;不加的话,同名的 PDF、XML 等也一起改")
108
+ rename.add_argument("--undo", metavar="改名记录", help="按改名记录把文件名改回去")
89
109
 
90
110
  describe = commands.add_parser("describe", help="导出文件结构(文字全部打码),用于报告问题")
91
111
  describe.add_argument("file", metavar="文件", help="OFD 文件")
@@ -112,6 +132,7 @@ def main(argv: Sequence[str] | None = None) -> int:
112
132
  "text": _text,
113
133
  "invoice": _invoice,
114
134
  "batch": _batch,
135
+ "rename": _rename,
115
136
  "describe": _describe,
116
137
  "mcp": _mcp,
117
138
  }
@@ -146,7 +167,8 @@ def _show(args: argparse.Namespace) -> int:
146
167
  invoice = document.invoice()
147
168
  text = None if invoice else document.text()
148
169
  if invoice is not None:
149
- print(invoice_report(invoice, problems(InvoiceFile(str(paths[0]), invoice=invoice))))
170
+ result = InvoiceFile(str(paths[0]), invoice=invoice, buyer_mismatch=buyer_mismatch(invoice, args.buyer))
171
+ print(invoice_report(invoice, problems(result)))
150
172
  elif text and text.strip():
151
173
  print(text)
152
174
  else:
@@ -161,13 +183,14 @@ def _show(args: argparse.Namespace) -> int:
161
183
  _say("没有找到 .ofd 文件。" + ("" if args.recursive else "要连子文件夹一起找,请加 -r。"))
162
184
  return EXIT_ERROR
163
185
  results = read_invoice_files(files)
186
+ check_buyer(results, args.buyer)
164
187
  print(table_report(results))
165
188
  print()
166
189
  print(summary_text(summary(results)))
167
190
  if any(result.invoice for result in results):
168
- quoted = " ".join(f'"{path}"' if " " in path else path for path in args.paths)
169
- flag = " -r" if args.recursive else ""
170
- print(f"\n导出到 Excel:ofdkit batch {quoted}{flag} -o 发票汇总.xlsx")
191
+ quoted = " ".join(_quote(path) for path in args.paths)
192
+ flags = (" -r" if args.recursive else "") + "".join(f" --buyer {_quote(value)}" for value in args.buyer)
193
+ print(f"\n导出到 Excel:ofdkit batch {quoted}{flags} -o 发票汇总.xlsx")
171
194
  return EXIT_OK
172
195
 
173
196
 
@@ -246,6 +269,7 @@ def _batch(args: argparse.Namespace) -> int:
246
269
  return EXIT_ERROR
247
270
 
248
271
  results = read_invoice_files(files)
272
+ check_buyer(results, args.buyer)
249
273
  output = Path(args.output) if args.output else None
250
274
  if output is not None and output.suffix.lower() == ".xlsx":
251
275
  from .xlsx import write_invoices_xlsx
@@ -266,6 +290,77 @@ def _batch(args: argparse.Namespace) -> int:
266
290
  return EXIT_OK
267
291
 
268
292
 
293
+ def _rename(args: argparse.Namespace) -> int:
294
+ from .rename import apply, plan, undo
295
+
296
+ if args.undo:
297
+ if args.paths:
298
+ _say("错误:用 --undo 的时候,不要再写文件或文件夹")
299
+ return EXIT_ERROR
300
+ try:
301
+ outcome = undo(args.undo)
302
+ except ValueError as exc:
303
+ _say(f"错误:{exc}")
304
+ return EXIT_ERROR
305
+ for old, new in outcome.done:
306
+ print(f"{old.name}\n → {new.name}")
307
+ print(f"\n已改回 {len(outcome.done)} 个文件。")
308
+ for old, new, reason in outcome.failed:
309
+ _say(f"没能把 {old} 改回 {new.name}:{reason}")
310
+ return EXIT_ERROR if outcome.failed else EXIT_OK
311
+
312
+ if not args.paths:
313
+ _say("错误:请写上要改名的文件或文件夹,例如 ofdkit rename 发票文件夹")
314
+ return EXIT_ERROR
315
+ try:
316
+ renames = plan(args.paths, args.pattern, args.recursive, companions=not args.only_ofd)
317
+ except ValueError as exc:
318
+ _say(f"错误:{exc}")
319
+ return EXIT_ERROR
320
+
321
+ planned = [rename for rename in renames if rename.target is not None]
322
+ skipped = [rename for rename in renames if rename.target is None]
323
+ if planned and not args.apply:
324
+ print("预览(还没有改名):\n")
325
+ for rename in planned:
326
+ assert rename.target is not None
327
+ print(f"{rename.source}\n → {rename.target.name}" + ("(和别的文件是同一张发票)" if rename.duplicate else ""))
328
+ for old, new in rename.companions:
329
+ print(f" 同名的 {old.name} 也改成 {new.name}")
330
+ if skipped:
331
+ print("\n不改名的文件:")
332
+ for rename in skipped:
333
+ print(f" {rename.source}:{rename.skipped}")
334
+ if not planned:
335
+ print("\n没有需要改名的文件。")
336
+ return EXIT_OK
337
+
338
+ companions = sum(len(rename.companions) for rename in planned)
339
+ extra = f"(另外还有 {companions} 个同名的 PDF、XML 等文件)" if companions else ""
340
+ if not args.apply:
341
+ command = " ".join(
342
+ [
343
+ "ofdkit rename",
344
+ *(_quote(path) for path in args.paths),
345
+ *(["-r"] if args.recursive else []),
346
+ *(["--pattern", _quote(args.pattern)] if args.pattern != DEFAULT_PATTERN else []),
347
+ *(["--only-ofd"] if args.only_ofd else []),
348
+ "--apply",
349
+ ]
350
+ )
351
+ print(f"\n共 {len(planned)} 个发票文件会改名{extra}。以上只是预览,还没有改。")
352
+ print(f"确认没问题的话,加上 --apply 再运行一次:\n{command}")
353
+ return EXIT_OK
354
+
355
+ outcome = apply(planned)
356
+ print(f"\n已改名 {len(outcome.done)} 个文件。")
357
+ for old, new, reason in outcome.failed:
358
+ _say(f"没能把 {old} 改成 {new.name}:{reason}")
359
+ if outcome.log is not None:
360
+ print(f"改名记录保存在 {outcome.log}\n要改回原来的名字,运行:ofdkit rename --undo {_quote(str(outcome.log))}")
361
+ return EXIT_ERROR if outcome.failed else EXIT_OK
362
+
363
+
269
364
  def _describe(args: argparse.Namespace) -> int:
270
365
  from .describe import describe
271
366
 
@@ -288,6 +383,20 @@ def _mcp(args: argparse.Namespace) -> int:
288
383
  return EXIT_OK
289
384
 
290
385
 
386
+ def _add_buyer_option(parser: argparse.ArgumentParser) -> None:
387
+ parser.add_argument(
388
+ "--buyer",
389
+ action="append",
390
+ default=[],
391
+ metavar="公司名或税号",
392
+ help="检查发票抬头:购买方不是这个公司(或税号)的发票会标出来。名称和税号都要查的话,写两次 --buyer",
393
+ )
394
+
395
+
396
+ def _quote(text: str) -> str:
397
+ return f'"{text}"' if any(char in text for char in " &()") else text
398
+
399
+
291
400
  def _write_csv(stream: Any, rows: list[dict[str, Any]]) -> None:
292
401
  writer = csv.DictWriter(stream, fieldnames=COLUMNS)
293
402
  writer.writeheader()
@@ -14,7 +14,7 @@ from mcp.server.mcpserver.exceptions import ToolError
14
14
  from mcp.types import ToolAnnotations
15
15
 
16
16
  from . import __version__
17
- from .batch import find_ofd_files, invoice_row, read_invoice_files, summary
17
+ from .batch import check_buyer, find_ofd_files, invoice_row, read_invoice_files, summary
18
18
  from .cli import file_info
19
19
  from .document import OFDDocument
20
20
  from .errors import OFDError
@@ -105,7 +105,7 @@ def create_server(root: str | Path | None = None) -> MCPServer:
105
105
  return file_info(document, path)
106
106
 
107
107
  @server.tool(title="List OFD invoices in a folder", annotations=_READ_ONLY)
108
- def list_ofd_invoices(folder: str, recursive: bool = False) -> dict[str, Any]:
108
+ def list_ofd_invoices(folder: str, recursive: bool = False, buyer: list[str] | None = None) -> dict[str, Any]:
109
109
  """Summarise every invoice in a folder of .ofd files, including ZIP archives of them.
110
110
 
111
111
  Returns one row per file (number, date, buyer, seller, amounts, item names, or the
@@ -115,6 +115,9 @@ def create_server(root: str | Path | None = None) -> MCPServer:
115
115
  Args:
116
116
  folder: Absolute path to a folder.
117
117
  recursive: Also look in subfolders.
118
+ buyer: The company the invoices should be made out to (发票抬头): its name, its
119
+ tax ID, or both. Invoices for another buyer get a "buyer is not" warning
120
+ and are counted in summary.buyer_mismatches.
118
121
  """
119
122
  directory = check(folder)
120
123
  if not directory.is_dir():
@@ -123,6 +126,7 @@ def create_server(root: str | Path | None = None) -> MCPServer:
123
126
  results = read_invoice_files(files, limit=MAX_BATCH_FILES + 1)
124
127
  truncated = len(results) > MAX_BATCH_FILES
125
128
  results = results[:MAX_BATCH_FILES]
129
+ check_buyer(results, buyer or [])
126
130
  return {"summary": summary(results), "truncated": truncated, "rows": [invoice_row(r) for r in results]}
127
131
 
128
132
  return server
File without changes
@@ -0,0 +1,285 @@
1
+ """Rename invoice files after what they contain, such as ``2026-01-02_测试单位乙_106.00_00000001.ofd``.
2
+
3
+ Invoices arrive with names like ``dzfp_24312000000123456789_某某公司_20260102.ofd``, or
4
+ worse. :func:`plan` works out new names from a pattern without touching anything;
5
+ :func:`apply` renames, never over an existing file, and writes a log that
6
+ :func:`undo` can use to restore the old names. Files with the same name and another
7
+ extension (the PDF and XML copies of the same invoice) are renamed along with the OFD.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import csv
13
+ import datetime as dt
14
+ import os
15
+ import re
16
+ from collections.abc import Callable, Iterable, Sequence
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+
20
+ from .batch import _duplicate_key, _read_one, find_ofd_files, item_names, problems
21
+ from .invoice import Invoice
22
+
23
+ DEFAULT_PATTERN = "{开票日期}_{销售方}_{价税合计}_{发票号码}"
24
+
25
+ #: Extensions of copies of the same invoice that are renamed together with the OFD file.
26
+ COMPANION_SUFFIXES = (".pdf", ".xml", ".png", ".jpg", ".jpeg")
27
+
28
+ #: Longest new name, in characters, without the extension.
29
+ MAX_NAME_LENGTH = 120
30
+
31
+ _FIELD_GETTERS: dict[str, Callable[[Invoice, Path], str | None]] = {
32
+ "开票日期": lambda i, p: i.issue_date,
33
+ "发票号码": lambda i, p: i.invoice_number,
34
+ "发票代码": lambda i, p: i.invoice_code,
35
+ "发票种类": lambda i, p: i.invoice_type,
36
+ "销售方": lambda i, p: i.seller.name,
37
+ "销售方税号": lambda i, p: i.seller.tax_id,
38
+ "购买方": lambda i, p: i.buyer.name,
39
+ "购买方税号": lambda i, p: i.buyer.tax_id,
40
+ "金额": lambda i, p: i.amount_without_tax,
41
+ "税额": lambda i, p: i.tax_amount,
42
+ "价税合计": lambda i, p: i.total_amount,
43
+ "商品": lambda i, p: item_names(i, limit=1),
44
+ "原文件名": lambda i, p: p.stem,
45
+ }
46
+ #: English names for the fields, for people who prefer typing them.
47
+ _ALIASES = {
48
+ "date": "开票日期",
49
+ "number": "发票号码",
50
+ "code": "发票代码",
51
+ "type": "发票种类",
52
+ "seller": "销售方",
53
+ "seller_tax_id": "销售方税号",
54
+ "buyer": "购买方",
55
+ "buyer_tax_id": "购买方税号",
56
+ "amount": "金额",
57
+ "tax": "税额",
58
+ "total": "价税合计",
59
+ "item": "商品",
60
+ "name": "原文件名",
61
+ }
62
+ FIELDS = tuple(_FIELD_GETTERS)
63
+
64
+ _PLACEHOLDER = re.compile(r"\{([^{}]*)\}")
65
+ _NOT_IN_NAMES = re.compile(r'[\\/:*?"<>|\x00-\x1f\x7f]') # not allowed in Windows file names
66
+ _RESERVED = re.compile(r"(?i)(con|prn|aux|nul|com\d|lpt\d)(\..*)?") # reserved names on Windows
67
+
68
+
69
+ @dataclass
70
+ class Rename:
71
+ """What happens to one OFD file."""
72
+
73
+ source: Path
74
+ #: The new path, or None when the file keeps its name.
75
+ target: Path | None = None
76
+ #: Why the file keeps its name, in Chinese.
77
+ skipped: str | None = None
78
+ #: Other copies of the same invoice, renamed with it: (old path, new path).
79
+ companions: list[tuple[Path, Path]] = field(default_factory=list)
80
+ #: Another file holds the same invoice.
81
+ duplicate: bool = False
82
+
83
+
84
+ @dataclass
85
+ class Outcome:
86
+ """What :func:`apply` or :func:`undo` did."""
87
+
88
+ #: Renames that were done: (old path, new path).
89
+ done: list[tuple[Path, Path]] = field(default_factory=list)
90
+ #: Renames that failed: (old path, new path, reason in Chinese).
91
+ failed: list[tuple[Path, Path, str]] = field(default_factory=list)
92
+ #: The log that :func:`undo` reads, if one was written.
93
+ log: Path | None = None
94
+
95
+
96
+ def check_pattern(pattern: str) -> None:
97
+ """Raise ValueError naming the problem if ``pattern`` cannot be used."""
98
+ names = _PLACEHOLDER.findall(pattern)
99
+ if not names:
100
+ raise ValueError(f"命名格式里没有任何字段,例如 {DEFAULT_PATTERN}")
101
+ unknown = [name for name in names if _field(name) is None]
102
+ if unknown:
103
+ raise ValueError(f"不认识的字段:{'、'.join(unknown)}。可以用的字段:{'、'.join(FIELDS)}")
104
+ if _NOT_IN_NAMES.search(_PLACEHOLDER.sub("", pattern)):
105
+ raise ValueError('命名格式里不能有这些字符:\\ / : * ? " < > |')
106
+
107
+
108
+ def new_name(invoice: Invoice, source: Path, pattern: str = DEFAULT_PATTERN) -> str:
109
+ """The new name for ``source``, without its extension. Empty if every field is empty."""
110
+ check_pattern(pattern)
111
+
112
+ def value(match: re.Match[str]) -> str:
113
+ getter = _FIELD_GETTERS[_field(match[1]) or ""]
114
+ return _clean(getter(invoice, source) or "")
115
+
116
+ name = _PLACEHOLDER.sub(value, pattern)
117
+ for separator in "_- ": # fields that were empty leave doubled separators
118
+ name = re.sub(f"{re.escape(separator)}{{2,}}", separator, name)
119
+ name = name.strip("_- .")[:MAX_NAME_LENGTH].rstrip("_- .")
120
+ if _RESERVED.fullmatch(name):
121
+ name = "_" + name
122
+ return name
123
+
124
+
125
+ def plan(
126
+ paths: Iterable[str | Path],
127
+ pattern: str = DEFAULT_PATTERN,
128
+ recursive: bool = False,
129
+ companions: bool = True,
130
+ ) -> list[Rename]:
131
+ """Work out new names for the OFD invoices in ``paths``; nothing is renamed.
132
+
133
+ Raises FileNotFoundError if a path does not exist and ValueError for a bad pattern.
134
+ """
135
+ check_pattern(pattern)
136
+ files, missing = find_ofd_files(paths, recursive)
137
+ if missing:
138
+ raise FileNotFoundError(f"{missing[0]} does not exist")
139
+
140
+ renames: list[Rename] = []
141
+ taken: dict[Path, set[str]] = {} # per folder: names in use, case-folded
142
+ keys: dict[tuple[str, str], int] = {}
143
+ for source in files:
144
+ rename = Rename(source)
145
+ renames.append(rename)
146
+ if source.suffix.lower() != ".ofd":
147
+ rename.skipped = "压缩包里的文件不能改名" if source.suffix.lower() == ".zip" else "不是 .ofd 文件"
148
+ continue
149
+ result = _read_one(str(source), source)
150
+ if result.invoice is None:
151
+ rename.skipped = problems(result)[0]
152
+ continue
153
+ key = _duplicate_key(result)
154
+ if key:
155
+ keys[key] = keys.get(key, 0) + 1
156
+ rename.duplicate = keys[key] > 1
157
+
158
+ stem = new_name(result.invoice, source, pattern)
159
+ if not stem:
160
+ rename.skipped = "发票上没有命名需要的内容"
161
+ continue
162
+ folder = source.parent
163
+ if folder not in taken:
164
+ taken[folder] = {entry.name.casefold() for entry in _entries(folder)}
165
+ copies = _companions(source) if companions else []
166
+ suffixes = [source.suffix, *(copy.suffix for copy in copies)]
167
+ own = {path.name.casefold() for path in [source, *copies]} # names this file may keep
168
+ stem = _free_stem(stem, suffixes, taken[folder] - own)
169
+ if stem.casefold() == source.stem.casefold(): # also true for a name that got " (2)" last time
170
+ rename.skipped = "已经是这个名字"
171
+ continue
172
+ rename.target = source.with_name(stem + source.suffix)
173
+ rename.companions = [(copy, copy.with_name(stem + copy.suffix)) for copy in copies]
174
+ for suffix in suffixes:
175
+ taken[folder].add((stem + suffix).casefold())
176
+ return renames
177
+
178
+
179
+ def apply(renames: Sequence[Rename], log_folder: str | Path | None = None) -> Outcome:
180
+ """Rename the files in ``renames``, never over an existing file.
181
+
182
+ The log of what was renamed is written to ``log_folder`` (by default the folder of
183
+ the first renamed file) as ``改名记录_<date>_<time>.csv``, for :func:`undo`.
184
+ """
185
+ outcome = Outcome()
186
+ for rename in renames:
187
+ if rename.target is None:
188
+ continue
189
+ for old, new in [(rename.source, rename.target), *rename.companions]:
190
+ _move(old, new, outcome)
191
+ if outcome.failed and outcome.failed[-1][0] == rename.source:
192
+ break # the OFD file kept its name, so its copies keep theirs too
193
+ if outcome.done:
194
+ folder = Path(log_folder) if log_folder is not None else outcome.done[0][1].parent
195
+ stamp = dt.datetime.now().astimezone().strftime("%Y%m%d_%H%M%S") # local time, as people read it
196
+ outcome.log = _unused(folder / f"改名记录_{stamp}.csv")
197
+ with open(outcome.log, "w", newline="", encoding="utf-8-sig") as stream:
198
+ writer = csv.writer(stream)
199
+ writer.writerow(["原来的文件", "新的文件"])
200
+ writer.writerows((str(old.resolve()), str(new.resolve())) for old, new in outcome.done)
201
+ return outcome
202
+
203
+
204
+ def undo(log: str | Path) -> Outcome:
205
+ """Give the files listed in a log written by :func:`apply` their old names back."""
206
+ with open(log, newline="", encoding="utf-8-sig") as stream:
207
+ rows = list(csv.reader(stream))
208
+ if not rows or rows[0] != ["原来的文件", "新的文件"]:
209
+ raise ValueError(f"{log} 不是 ofdkit 写的改名记录")
210
+ outcome = Outcome()
211
+ for row in reversed(rows[1:]):
212
+ if len(row) == 2:
213
+ _move(Path(row[1]), Path(row[0]), outcome)
214
+ return outcome
215
+
216
+
217
+ def _move(old: Path, new: Path, outcome: Outcome) -> None:
218
+ if not old.exists():
219
+ outcome.failed.append((old, new, "文件不见了"))
220
+ return
221
+ if new.exists() and not _same_file(old, new):
222
+ outcome.failed.append((old, new, "新名字已经有文件在用"))
223
+ return
224
+ try:
225
+ os.rename(old, new)
226
+ except OSError as exc:
227
+ reason = "文件可能正在被别的软件打开" if isinstance(exc, PermissionError) else str(exc)
228
+ outcome.failed.append((old, new, reason))
229
+ return
230
+ outcome.done.append((old, new))
231
+
232
+
233
+ def _same_file(a: Path, b: Path) -> bool:
234
+ """True when ``b`` is ``a`` under a name that differs only in case."""
235
+ try:
236
+ return os.path.samefile(a, b)
237
+ except OSError:
238
+ return False
239
+
240
+
241
+ def _field(name: str) -> str | None:
242
+ name = name.strip()
243
+ if name in _FIELD_GETTERS:
244
+ return name
245
+ return _ALIASES.get(name.lower())
246
+
247
+
248
+ def _clean(value: str) -> str:
249
+ value = re.sub(r"^\*([^*]+)\*", r"\1-", value.strip()) # *餐饮服务*餐费 -> 餐饮服务-餐费
250
+ return " ".join(_NOT_IN_NAMES.sub("", value).split())
251
+
252
+
253
+ def _entries(folder: Path) -> list[Path]:
254
+ try:
255
+ return list(folder.iterdir())
256
+ except OSError:
257
+ return []
258
+
259
+
260
+ def _companions(source: Path) -> list[Path]:
261
+ stem = source.stem.casefold()
262
+ return sorted(
263
+ entry
264
+ for entry in _entries(source.parent)
265
+ if entry != source
266
+ and entry.is_file()
267
+ and entry.stem.casefold() == stem
268
+ and entry.suffix.lower() in COMPANION_SUFFIXES
269
+ )
270
+
271
+
272
+ def _free_stem(stem: str, suffixes: list[str], taken: set[str]) -> str:
273
+ candidate, number = stem, 1
274
+ while any((candidate + suffix).casefold() in taken for suffix in suffixes):
275
+ number += 1
276
+ candidate = f"{stem} ({number})"
277
+ return candidate
278
+
279
+
280
+ def _unused(path: Path) -> Path:
281
+ candidate, number = path, 1
282
+ while candidate.exists():
283
+ number += 1
284
+ candidate = path.with_name(f"{path.stem} ({number}){path.suffix}")
285
+ return candidate
@@ -100,6 +100,8 @@ def summary_text(totals: dict[str, Any]) -> str:
100
100
  if Decimal(totals[key]) # left out when no invoice has the field
101
101
  ]
102
102
  text += f"\n价税合计 {money(totals['total_amount_sum'])} 元" + (f"({','.join(parts)})" if parts else "") + "。"
103
+ if totals.get("buyer_mismatches"):
104
+ text += f"\n有 {totals['buyer_mismatches']} 张发票的购买方不对(抬头或税号和你指定的不一样),请看“提醒”一栏。"
103
105
  if totals["duplicates"]:
104
106
  text += (
105
107
  f"\n有 {totals['duplicates']} 个文件和别的文件是同一张发票(发票号码相同),"
@@ -27,8 +27,9 @@ from .invoice import Invoice, LineItem
27
27
  #: Kinds of cell. ``text`` keeps digits as typed; ``money`` and ``number`` are numeric.
28
28
  TEXT, INTEGER, MONEY, NUMBER, DATE = "text", "integer", "money", "number", "date"
29
29
 
30
- # Row colours: header, a duplicate invoice, a file without invoice data, an unreadable file.
31
- _FILLS = {"header": "DDEBF7", "duplicate": "FFF2CC", "not_invoice": "F2F2F2", "error": "FCE4E4"}
30
+ # Row colours: header, a duplicate invoice, a file without invoice data, an unreadable file,
31
+ # an invoice for another buyer.
32
+ _FILLS = {"header": "DDEBF7", "duplicate": "FFF2CC", "not_invoice": "F2F2F2", "error": "FCE4E4", "mismatch": "FCE4D6"}
32
33
  _NUMBER_FORMATS = {TEXT: 49, INTEGER: 1, MONEY: 4, NUMBER: 0, DATE: 164} # 164 is yyyy-mm-dd, below
33
34
  _MAX_CELL_TEXT = 32_767 # Excel's limit
34
35
  _ILLEGAL_XML = re.compile("[\x00-\x08\x0b\x0c\x0e-\x1f￾￿]")
@@ -97,6 +98,8 @@ def _invoice_sheet(results: Sequence[InvoiceFile]) -> _Sheet:
97
98
  cells += [_Cell(";".join(problems(result))), _Cell(result.file)]
98
99
  if invoice is None:
99
100
  fill = "not_invoice" if problems(result)[0].startswith("不是发票") else "error"
101
+ elif result.buyer_mismatch:
102
+ fill = "mismatch"
100
103
  else:
101
104
  fill = "duplicate" if result.duplicate else None
102
105
  rows.append((cells, fill))
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes