feat(财务台账): 接入招商银行邮件账单 (#1392)

接入招商银行邮件账单下载、整目录导入和余额同步。
This commit is contained in:
shanshi 2026-11-25 10:11:08 +08:00
parent 04aab012b9
commit 39769abd26
12 changed files with 1073 additions and 6 deletions

View File

@ -0,0 +1,57 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\EcommerceFinance\Services\BankBillStatementDirectoryImporter;
use Throwable;
class ImportBankBillsDirectory extends Command
{
protected $signature = 'finance-ledger:import-bank-bills-directory
{path : 已解压的银行账单目录}
{--bank= : 招商银行、华夏银行或网商银行}
{--dry-run : 只校验,不写入账单数据}';
protected $description = '一次导入目录中的多份银行账单,并统一同步余额';
public function handle(BankBillStatementDirectoryImporter $importer): int
{
try {
$result = $importer->import(
(string) $this->argument('path'),
(string) $this->option('bank'),
(bool) $this->option('dry-run'),
);
} catch (Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$this->info(sprintf(
'%s%s:%d 个文件,成功 %d 个,失败 %d 个,共 %d 条;新增 %d 条,更新 %d 条,跳过 %d 条。',
$result['dry_run'] ? '校验完成,' : '账单已导入,',
$result['bank'],
$result['files'],
$result['imported_files'],
$result['failed_files'],
$result['rows'],
$result['inserted'],
$result['updated'],
$result['skipped'],
));
$this->line(sprintf(
'账务日期:%s 至 %s;涉及 %d 个账户,已同步 %d 个账户余额。',
$result['first_date'] ?? '无',
$result['last_date'] ?? '无',
$result['accounts'],
$result['synced_accounts'],
));
foreach ($result['failures'] as $failure) {
$this->error($failure);
}
return $result['failed_files'] === 0 ? self::SUCCESS : self::FAILURE;
}
}

View File

@ -12,6 +12,7 @@
"dewu-bills:import-authoritative",
"business-mirror:import-douyin-authoritative",
"business-mirror:import-douyin-opening-balances",
"business-mirror:import-ding-attendance-schedules",
"business-mirror:import-kuka-posting-base",
"business-mirror:import-kuka-posting-labels",
"business-mirror:import-kuka-posting-material-repair",
@ -19,8 +20,13 @@
"business-mirror:import-kuka-posting-quotation",
"kuka-posting:import-erp-recipients",
"finance-ledger:import-company-alipay",
"finance-ledger:import-alipay-statement",
"finance-ledger:import-bank-bill-headers",
"finance-ledger:import-bank-bills",
"finance-ledger:import-bank-bills-directory",
"finance-ledger:import-bank-direct-balances",
"finance-ledger:import-wangshang-bank",
"finance-ledger:import-wechat-statement",
"finance-ledger:import-base",
"finance-ledger:import-snapshot",
"internal-flow:import",
@ -30,6 +36,7 @@
"business-mirror:import-jd-daily",
"business-mirror:import-jd-wallet",
"business-mirror:import-pdd-platform-balances",
"ding:import-process-details",
"jst-order-labels:import-planting-rules",
"jst-order-labels:import",
"jst-order-labels:sync-daily",

View File

@ -16,6 +16,21 @@ def available_memory_kib():
return int(meminfo['MemAvailable'].split()[0])
def stage_tree(source, destination):
files = [item for item in source.rglob('*') if item.is_file()]
if len(files) > 1000:
raise ValueError('Import directory contains more than 1000 files.')
if sum(item.stat().st_size for item in files) > 600 * 1024 * 1024:
raise ValueError('Import directory exceeds 600 MiB.')
shutil.copytree(source, destination)
destination.chmod(0o755)
for item in destination.rglob('*'):
if item.is_file():
item.chmod(0o444)
elif item.is_dir():
item.chmod(0o755)
def main():
arguments = sys.argv[1:]
registry = json.loads(pathlib.Path(__file__).with_name('finance-batch-imports.json').read_text())
@ -55,12 +70,19 @@ def main():
source = pathlib.Path(value)
if not source.is_absolute():
source = pathlib.Path(os.environ.get('CAIWU_BATCH_CALLER_DIR', os.getcwd())) / source
if (prefix or not argument.startswith('-')) and source.is_file():
if (prefix or not argument.startswith('-')) and (source.is_file() or source.is_dir()):
parent = inputs / str(staged_count)
parent.mkdir(mode=0o755)
destination = parent / source.name
shutil.copyfile(source, destination)
destination.chmod(0o444)
if source.is_dir():
try:
stage_tree(source, destination)
except (OSError, ValueError) as exception:
print(f'Unable to stage import directory: {exception}', file=sys.stderr)
return 65
else:
shutil.copyfile(source, destination)
destination.chmod(0o444)
staged_arguments.append(prefix + '/run/caiwu-import/' + parent.name + '/' + destination.name)
staged_count += 1
else:

View File

@ -0,0 +1,132 @@
<?php
namespace Modules\EcommerceFinance\Services;
use FilesystemIterator;
use InvalidArgumentException;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use SplFileInfo;
use Throwable;
final class BankBillStatementDirectoryImporter
{
public function __construct(
private readonly BankBillStatementImporter $statements,
private readonly FinanceLedgerBankBalanceSynchronizer $balanceSynchronizer,
) {
}
/**
* @return array{
* bank:string,files:int,imported_files:int,failed_files:int,rows:int,
* inserted:int,updated:int,skipped:int,accounts:int,synced_accounts:int,
* first_date:?string,last_date:?string,dry_run:bool,failures:list<string>
* }
*/
public function import(
string $directory,
string $bankName,
bool $dryRun = false,
): array {
if (! is_dir($directory) || ! is_readable($directory)) {
throw new InvalidArgumentException('银行账单目录不存在或不可读取。');
}
$files = $this->files($directory);
if ($files === []) {
throw new InvalidArgumentException('银行账单目录中没有 XLSX、XLS 或 CSV 文件。');
}
$result = [
'bank' => trim($bankName),
'files' => count($files),
'imported_files' => 0,
'failed_files' => 0,
'rows' => 0,
'inserted' => 0,
'updated' => 0,
'skipped' => 0,
'accounts' => 0,
'synced_accounts' => 0,
'first_date' => null,
'last_date' => null,
'dry_run' => $dryRun,
'failures' => [],
];
$accountNumbers = [];
foreach ($files as $file) {
try {
$fileResult = $this->statements->import(
$file,
$bankName,
$dryRun,
false,
false,
);
$result['imported_files']++;
$result['rows'] += $fileResult['rows'];
$result['inserted'] += $fileResult['inserted'];
$result['updated'] += $fileResult['updated'];
$result['skipped'] += $fileResult['skipped'];
foreach ($fileResult['account_numbers'] as $accountNumber) {
$accountNumbers[(string) $accountNumber] = true;
}
if ($fileResult['first_date'] !== null
&& ($result['first_date'] === null
|| $fileResult['first_date'] < $result['first_date'])) {
$result['first_date'] = $fileResult['first_date'];
}
if ($fileResult['last_date'] !== null
&& ($result['last_date'] === null
|| $fileResult['last_date'] > $result['last_date'])) {
$result['last_date'] = $fileResult['last_date'];
}
} catch (Throwable $exception) {
$result['failed_files']++;
$result['failures'][] = basename($file) . ':' . $exception->getMessage();
}
}
$result['accounts'] = count($accountNumbers);
if (! $dryRun && $accountNumbers !== []) {
$result['synced_accounts'] = $this->balanceSynchronizer->syncAccountNumbers(
array_keys($accountNumbers),
$result['last_date'],
);
}
return $result;
}
/**
* @return list<string>
*/
private function files(string $directory): array
{
$files = [];
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$directory,
FilesystemIterator::SKIP_DOTS,
),
);
foreach ($iterator as $file) {
if (! $file instanceof SplFileInfo || ! $file->isFile()) {
continue;
}
if (! in_array(
strtolower($file->getExtension()),
['xlsx', 'xls', 'csv'],
true,
)) {
continue;
}
$files[] = $file->getPathname();
}
sort($files, SORT_NATURAL | SORT_FLAG_CASE);
return $files;
}
}

View File

@ -33,7 +33,8 @@ final class BankBillStatementImporter
/**
* @return array{
* bank:string,rows:int,affected:int,inserted:int,updated:int,skipped:int,
* accounts:int,synced_accounts:int,first_date:?string,last_date:?string,dry_run:bool
* accounts:int,synced_accounts:int,first_date:?string,last_date:?string,
* dry_run:bool,account_numbers:list<string>
* }
*/
public function import(
@ -41,6 +42,7 @@ final class BankBillStatementImporter
string $bankName,
bool $dryRun = false,
bool $replaceBank = false,
bool $syncBalances = true,
): array
{
$bankName = trim($bankName);
@ -98,6 +100,7 @@ final class BankBillStatementImporter
'first_date' => null,
'last_date' => null,
'dry_run' => $dryRun,
'account_numbers' => [],
];
$accountNumbers = [];
$incomeRows = 0;
@ -275,9 +278,10 @@ final class BankBillStatementImporter
}
$stats['accounts'] = count($accountNumbers);
if (! $dryRun) {
$stats['account_numbers'] = array_keys($accountNumbers);
if (! $dryRun && $syncBalances) {
$stats['synced_accounts'] = $this->balanceSynchronizer->syncAccountNumbers(
array_keys($accountNumbers),
$stats['account_numbers'],
);
}

View File

@ -0,0 +1,38 @@
# 招商银行邮件账单
每天从 163 邮箱读取招商银行 `95555@message.cmbchina.com` 发来的
“招商银行企业交易明细”邮件,提取正文中的限时下载链接,解压 ZIP,
导入“银行账单”,并同步账户当前余额。
## 运行规则
- 默认处理前一天的交易明细。
- 邮箱必须开启 IMAP,配置复用
`runtime/private/wangshang-mail-accounts.json` 中的邮箱连接信息。
- 招商银行下载链接有效期 12 小时,生产任务在 02:10、03:10、04:10、05:10
重试;相同 ZIP 指纹只导入一次。
- ZIP 只接收 XLSX、XLS、CSV,每次解压前校验文件数量、总大小和路径安全。
- 导入按银行流水指纹幂等更新,重复下载不会产生重复流水。
## 手动测试
```powershell
python scripts\cmb-mail\fetch_daily.py fetch `
--config runtime\private\wangshang-mail-accounts.json `
--date 2026-11-24
```
生产导入:
```sh
/bin/sh /opt/caiwuxitong/runtime/private/cmb-mail/run-server.sh 2026-11-24
```
## 部署
```powershell
pwsh -File scripts\cmb-mail\install-from-workstation.ps1 -RunNow
```
安装脚本复用生产环境已有的 163 邮箱配置,并安装
`/etc/cron.d/caiwu-cmb-mail` 定时任务。

View File

@ -0,0 +1,438 @@
#!/usr/bin/env python3
"""Download the daily China Merchants Bank statement delivered by email."""
from __future__ import annotations
import argparse
import email
import email.policy
import hashlib
import html
import imaplib
import json
import os
import re
import ssl
import sys
import urllib.parse
import urllib.request
import zipfile
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from email.utils import parsedate_to_datetime
from html.parser import HTMLParser
from pathlib import Path, PurePosixPath
from typing import Any
from zoneinfo import ZoneInfo
SHANGHAI = ZoneInfo("Asia/Shanghai")
MONTHS = (
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
)
DEFAULT_SENDER = "95555@message.cmbchina.com"
DEFAULT_SUBJECT = "招商银行企业交易明细"
DOWNLOAD_TEXT = "点击此处下载文件"
DATE_RANGE = re.compile(r"(?P<start>\d{8})-(?P<end>\d{8})")
SUPPORTED_FILES = {".xlsx", ".xls", ".csv"}
MAX_DOWNLOAD_BYTES = 300 * 1024 * 1024
MAX_EXTRACTED_BYTES = 600 * 1024 * 1024
MAX_ARCHIVE_MEMBERS = 1000
class CmbMailError(RuntimeError):
"""The CMB email or statement package cannot be safely processed."""
@dataclass(frozen=True)
class DownloadLink:
url: str
archive_name: str
date_start: str
date_end: str
class _AnchorParser(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.links: list[tuple[str, str]] = []
self._href = ""
self._text: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag.lower() != "a":
return
attributes = {key.lower(): value or "" for key, value in attrs}
self._href = attributes.get("href", "").strip()
self._text = []
def handle_data(self, data: str) -> None:
if self._href:
self._text.append(data)
def handle_endtag(self, tag: str) -> None:
if tag.lower() == "a" and self._href:
self.links.append((self._href, "".join(self._text).strip()))
self._href = ""
self._text = []
def text(value: Any) -> str:
return "" if value is None else str(value).strip()
def compact(value: Any) -> str:
return re.sub(r"\s+", "", text(value))
def parse_date(value: str) -> date:
try:
parsed = date.fromisoformat(value)
except ValueError as exception:
raise CmbMailError("日期必须使用 YYYY-MM-DD 格式。") from exception
if parsed.isoformat() != value:
raise CmbMailError("日期必须使用 YYYY-MM-DD 格式。")
return parsed
def imap_date(value: date) -> str:
return f"{value.day:02d}-{MONTHS[value.month - 1]}-{value.year}"
def write_json(path: Path, payload: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
os.replace(temporary, path)
def connect_mail(mail: dict[str, Any]) -> imaplib.IMAP4_SSL:
imaplib.Commands["ID"] = ("AUTH",)
connection = imaplib.IMAP4_SSL(
str(mail["host"]),
int(mail.get("port", 993)),
ssl_context=ssl.create_default_context(),
)
connection.login(str(mail["username"]), str(mail["auth_code"]))
connection._simple_command(
"ID",
'("name" "CaiWuXiTong" "version" "1.0" "vendor" "CaiWuXiTong")',
)
status, data = connection.select("INBOX", readonly=True)
if status != "OK":
connection.logout()
raise CmbMailError(f"无法打开邮箱收件箱:{data!r}")
return connection
def message_date(message: email.message.Message) -> datetime:
try:
parsed = parsedate_to_datetime(str(message.get("Date", "")))
if parsed.tzinfo is None:
return parsed.replace(tzinfo=SHANGHAI)
return parsed.astimezone(SHANGHAI)
except (TypeError, ValueError):
return datetime.min.replace(tzinfo=SHANGHAI)
def message_text_parts(message: email.message.Message) -> list[str]:
parts: list[str] = []
for part in message.walk():
disposition = text(part.get("Content-Disposition")).lower()
if "attachment" in disposition:
continue
content_type = text(part.get_content_type()).lower()
if content_type not in {"text/html", "text/plain"}:
continue
payload = part.get_payload(decode=True)
if payload is None:
continue
charset = part.get_content_charset() or "utf-8"
try:
parts.append(payload.decode(charset, errors="replace"))
except LookupError:
parts.append(payload.decode("utf-8", errors="replace"))
return parts
def download_link_from_body(body: str) -> DownloadLink | None:
parser = _AnchorParser()
parser.feed(body)
for href, label in parser.links:
if compact(label) != DOWNLOAD_TEXT:
continue
url = html.unescape(href.strip())
if url.startswith("//"):
url = "https:" + url
elif not url.lower().startswith(("http://", "https://")):
url = "https://" + url.lstrip("/")
parsed = urllib.parse.urlsplit(url)
if parsed.hostname not in {"s3gw.cmbimg.com"}:
continue
decoded = url
for _ in range(3):
next_decoded = urllib.parse.unquote(decoded)
if next_decoded == decoded:
break
decoded = next_decoded
dates = DATE_RANGE.search(decoded)
filename_match = re.search(
r'filename\*?=(?:UTF-8\'\')?"?([^";&]+)',
decoded,
flags=re.IGNORECASE,
)
archive_name = (
urllib.parse.unquote(filename_match.group(1)).strip()
if filename_match
else "招商银行企业交易明细.zip"
)
return DownloadLink(
url=url,
archive_name=archive_name,
date_start=dates.group("start") if dates else "",
date_end=dates.group("end") if dates else "",
)
return None
def load_candidates(
mail: dict[str, Any],
target_date: date,
) -> list[dict[str, Any]]:
connection = connect_mail(mail)
candidates: list[dict[str, Any]] = []
since = target_date - timedelta(days=max(1, int(mail.get("search_grace_days", 2))))
sender_match = compact(mail.get("sender", DEFAULT_SENDER)).lower()
subject_match = compact(mail.get("subject", DEFAULT_SUBJECT))
try:
status, data = connection.uid("search", None, "SINCE", imap_date(since))
if status != "OK":
raise CmbMailError(f"邮箱搜索失败:{data!r}")
uids = data[0].split() if data and data[0] else []
for uid in uids:
status, parts = connection.uid(
"fetch",
uid,
"(BODY.PEEK[HEADER.FIELDS (FROM SUBJECT DATE)])",
)
if status != "OK":
continue
raw_header = b"".join(part[1] for part in parts if isinstance(part, tuple))
header = email.message_from_bytes(raw_header, policy=email.policy.default)
sender = compact(header.get("From")).lower()
subject = text(header.get("Subject"))
if sender_match not in sender or subject_match not in compact(subject):
continue
status, parts = connection.uid("fetch", uid, "(BODY.PEEK[])")
if status != "OK":
continue
raw = b"".join(part[1] for part in parts if isinstance(part, tuple))
message = email.message_from_bytes(raw, policy=email.policy.default)
link = None
for body in message_text_parts(message):
link = download_link_from_body(body)
if link is not None:
break
sent_at = message_date(message)
if link is None or sent_at.date() != target_date + timedelta(days=1):
continue
candidates.append(
{
"uid": uid.decode(),
"sent_at": sent_at,
"subject": subject,
"link": link,
}
)
finally:
try:
connection.logout()
except imaplib.IMAP4.error:
pass
return sorted(candidates, key=lambda item: item["sent_at"], reverse=True)
def download_archive(link: DownloadLink, target: Path) -> dict[str, Any]:
request = urllib.request.Request(
link.url,
headers={
"User-Agent": "CaiWuXiTong/1.0",
"Accept": "application/zip,application/octet-stream,*/*",
},
)
digest = hashlib.sha256()
total = 0
target.parent.mkdir(parents=True, exist_ok=True)
temporary = target.with_suffix(target.suffix + ".tmp")
try:
with urllib.request.urlopen(request, timeout=120) as response:
content_type = text(response.headers.get("Content-Type")).lower()
if "zip" not in content_type and "octet-stream" not in content_type:
raise CmbMailError(f"招商银行下载链接返回了非 ZIP 内容:{content_type or '未知'}")
with temporary.open("wb") as stream:
while True:
chunk = response.read(1024 * 1024)
if not chunk:
break
total += len(chunk)
if total > MAX_DOWNLOAD_BYTES:
raise CmbMailError("招商银行账单 ZIP 超过 300 MB,已停止下载。")
digest.update(chunk)
stream.write(chunk)
os.replace(temporary, target)
except Exception:
temporary.unlink(missing_ok=True)
raise
if total == 0:
target.unlink(missing_ok=True)
raise CmbMailError("招商银行账单 ZIP 下载为空。")
return {
"size": total,
"sha256": digest.hexdigest(),
"content_type": content_type,
}
def safe_extract(archive_path: Path, destination: Path) -> list[dict[str, Any]]:
destination.mkdir(parents=True, exist_ok=True)
files: list[dict[str, Any]] = []
try:
with zipfile.ZipFile(archive_path) as archive:
members = [item for item in archive.infolist() if not item.is_dir()]
if len(members) > MAX_ARCHIVE_MEMBERS:
raise CmbMailError("招商银行 ZIP 文件数量异常。")
if sum(max(0, item.file_size) for item in members) > MAX_EXTRACTED_BYTES:
raise CmbMailError("招商银行 ZIP 解压后超过 600 MB,已停止处理。")
for item in members:
member = PurePosixPath(item.filename)
if member.is_absolute() or ".." in member.parts:
raise CmbMailError("招商银行 ZIP 包含不安全文件路径。")
if any(part.startswith("__MACOSX") for part in member.parts):
continue
suffix = member.suffix.lower()
if suffix not in SUPPORTED_FILES:
continue
target = destination.joinpath(*member.parts)
target.parent.mkdir(parents=True, exist_ok=True)
with archive.open(item) as source, target.open("wb") as output:
while True:
chunk = source.read(1024 * 1024)
if not chunk:
break
output.write(chunk)
file_digest = hashlib.sha256(target.read_bytes()).hexdigest()
files.append(
{
"path": str(target),
"name": target.name,
"size": target.stat().st_size,
"sha256": file_digest,
}
)
except zipfile.BadZipFile as exception:
raise CmbMailError("招商银行下载内容不是有效 ZIP。") from exception
if not files:
raise CmbMailError("招商银行 ZIP 中没有可导入的 XLSX、XLS 或 CSV 文件。")
return files
def fetch(args: argparse.Namespace) -> int:
config_file = Path(args.config).expanduser().resolve()
if not config_file.is_file():
raise CmbMailError(f"缺少招商银行邮件配置:{config_file}")
config = json.loads(config_file.read_text(encoding="utf-8"))
mail = config.get("mail")
if not isinstance(mail, dict):
raise CmbMailError("招商银行邮件配置缺少 mail。")
mail = dict(mail)
mail["sender"] = text(config.get("sender", DEFAULT_SENDER))
mail["subject"] = text(config.get("subject", DEFAULT_SUBJECT))
target_date = parse_date(
args.date or (datetime.now(SHANGHAI).date() - timedelta(days=1)).isoformat()
)
output_root = Path(
args.out or config_file.parent / "exports" / target_date.isoformat()
).expanduser().resolve()
run_directory = (
Path(args.run_dir).expanduser().resolve()
if args.run_dir
else output_root / datetime.now(SHANGHAI).strftime("%Y%m%d-%H%M%S")
)
run_directory.mkdir(parents=True, exist_ok=True)
state_file = run_directory / "last-fetch.json"
candidates = load_candidates(mail, target_date)
print(f"邮箱匹配到 {len(candidates)} 封招商银行账单邮件")
if not candidates:
raise CmbMailError(f"{target_date.isoformat()} 的招商银行账单邮件未找到。")
selected = candidates[0]
link: DownloadLink = selected["link"]
archive_path = run_directory / "cmb-statement.zip"
archive_info = download_archive(link, archive_path)
extract_directory = run_directory / "contents"
files = safe_extract(archive_path, extract_directory)
state = {
"ok": True,
"target_date": target_date.isoformat(),
"mail_uid": selected["uid"],
"mail_sent_at": selected["sent_at"].isoformat(timespec="seconds"),
"subject": selected["subject"],
"archive_name": link.archive_name,
"date_start": link.date_start,
"date_end": link.date_end,
"download_url_sha256": hashlib.sha256(link.url.encode("utf-8")).hexdigest(),
"archive": str(archive_path),
"archive_size": archive_info["size"],
"archive_sha256": archive_info["sha256"],
"files": files,
"generated_at": datetime.now(SHANGHAI).isoformat(timespec="seconds"),
}
write_json(state_file, state)
print(f"已下载并解压 {len(files)} 个招商银行账单文件")
print(f"状态文件:{state_file}")
return 0
def parser() -> argparse.ArgumentParser:
root = argparse.ArgumentParser(description="招商银行邮件账单自动获取")
commands = root.add_subparsers(dest="command", required=True)
fetch_command = commands.add_parser("fetch", help="从邮箱获取并解压招商银行账单")
fetch_command.add_argument("--config", required=True)
fetch_command.add_argument("--date", default="")
fetch_command.add_argument("--out", default="")
fetch_command.add_argument("--run-dir", default="")
fetch_command.set_defaults(handler=fetch)
return root
def main() -> int:
args = parser().parse_args()
try:
return int(args.handler(args))
except CmbMailError as exception:
print(f"招商银行邮件任务失败:{exception}", file=sys.stderr)
return 2
except Exception as exception:
print(f"招商银行邮件任务异常:{type(exception).__name__}: {exception}", file=sys.stderr)
return 2
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,96 @@
[CmdletBinding()]
param(
[string] $Server = '218.93.190.75',
[ValidatePattern('^[A-Za-z0-9._-]+$')]
[string] $SshUser = 'root',
[switch] $RunNow,
[ValidatePattern('^\d{4}-\d{2}-\d{2}$')]
[string] $Date
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
. (Join-Path $root 'scripts\deploy-auth.ps1')
$target = "${SshUser}@${Server}"
$remoteBase = '/opt/caiwuxitong/runtime/private/cmb-mail'
$auth = Start-CaiwuDeploymentAuth -Server $Server -SshUser $SshUser
try {
& ssh @($auth.Options) $target "install -d -m 700 '$remoteBase' '$remoteBase/logs' '$remoteBase/state'"
if ($LASTEXITCODE -ne 0) {
throw '创建招商银行邮件运行目录失败'
}
& scp @($auth.Options) `
(Join-Path $PSScriptRoot 'fetch_daily.py') `
(Join-Path $PSScriptRoot 'run-server.sh') `
"${target}:$remoteBase/"
if ($LASTEXITCODE -ne 0) {
throw '上传招商银行邮件脚本失败'
}
$install = @'
set -eu
BASE_DIR="/opt/caiwuxitong/runtime/private/cmb-mail"
SOURCE_CONFIG="/opt/caiwuxitong/runtime/private/wangshang-mail-accounts.json"
chmod 700 "$BASE_DIR/run-server.sh"
chmod 600 "$BASE_DIR/fetch_daily.py"
python3 - "$SOURCE_CONFIG" "$BASE_DIR/config.json" <<'PY'
import json
import os
import sys
source = json.load(open(sys.argv[1], encoding="utf-8"))
mail = dict(source.get("mail") or {})
if not mail.get("host") or not mail.get("username") or not mail.get("auth_code"):
raise SystemExit("现有 163 邮箱配置不完整")
config = {
"sender": "95555@message.cmbchina.com",
"subject": "招商银行企业交易明细",
"mail": {
"host": mail["host"],
"port": int(mail.get("port", 993)),
"username": mail["username"],
"auth_code": mail["auth_code"],
"search_grace_days": max(3, int(mail.get("search_grace_days", 2))),
},
}
temporary = sys.argv[2] + ".tmp"
with open(temporary, "w", encoding="utf-8") as stream:
json.dump(config, stream, ensure_ascii=False, indent=2)
stream.write("\n")
os.chmod(temporary, 0o600)
os.replace(temporary, sys.argv[2])
PY
cat > /etc/cron.d/caiwu-cmb-mail <<'CRON'
CRON_TZ=Asia/Shanghai
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
10 2,3,4,5 * * * root /usr/bin/flock -n /run/caiwu-cmb-mail.lock /bin/sh /opt/caiwuxitong/runtime/private/cmb-mail/run-server.sh >> /opt/caiwuxitong/runtime/private/cmb-mail/cron.log 2>&1
CRON
chmod 644 /etc/cron.d/caiwu-cmb-mail
'@
& ssh @($auth.Options) $target $install
if ($LASTEXITCODE -ne 0) {
throw '安装招商银行邮件配置或定时任务失败'
}
if ($RunNow) {
$arguments = if ([string]::IsNullOrWhiteSpace($Date)) { '' } else { " '$Date'" }
& ssh @($auth.Options) $target (
"/usr/bin/flock -n /run/caiwu-cmb-mail.lock /bin/sh '$remoteBase/run-server.sh'" +
$arguments
)
if ($LASTEXITCODE -ne 0) {
throw '立即执行招商银行邮件账单任务失败'
}
}
} finally {
Stop-CaiwuDeploymentAuth $auth
}
Write-Host "招商银行邮件账单任务已安装。每天 02:10、03:10、04:10、05:10 自动重试。"

View File

@ -0,0 +1,124 @@
#!/bin/sh
set -eu
BASE_DIR="${CMB_MAIL_BASE_DIR:-/opt/caiwuxitong/runtime/private/cmb-mail}"
CONFIG_FILE="$BASE_DIR/config.json"
FETCH_SCRIPT="$BASE_DIR/fetch_daily.py"
PYTHON_PATH="$BASE_DIR/python"
DATE="${1:-$(TZ=Asia/Shanghai date -d yesterday +%F)}"
STAMP="$(TZ=Asia/Shanghai date +%Y%m%d-%H%M%S)"
RUN_DIR="$BASE_DIR/exports/$DATE/server-$STAMP"
LOG_DIR="$BASE_DIR/logs"
LOG_FILE="$LOG_DIR/$(TZ=Asia/Shanghai date +%F).log"
STATE_FILE="$RUN_DIR/last-fetch.json"
IMPORT_MARKER="$BASE_DIR/state/$DATE.imported.json"
umask 077
mkdir -p "$RUN_DIR" "$LOG_DIR" "$BASE_DIR/state"
exec >>"$LOG_FILE" 2>&1
log() {
echo "[$(TZ=Asia/Shanghai date '+%F %T')] $*"
}
if [ ! -f "$CONFIG_FILE" ]; then
log "缺少招商银行邮件配置:$CONFIG_FILE"
exit 1
fi
if [ ! -f "$FETCH_SCRIPT" ]; then
log "缺少招商银行邮件抓取脚本:$FETCH_SCRIPT"
exit 1
fi
log "开始获取招商银行邮件账单 $DATE"
fetch_status=0
PYTHONPATH="$PYTHON_PATH" python3 -X utf8 "$FETCH_SCRIPT" fetch \
--config "$CONFIG_FILE" \
--date "$DATE" \
--out "$BASE_DIR/exports/$DATE" \
--run-dir "$RUN_DIR" || fetch_status=$?
if [ ! -f "$STATE_FILE" ]; then
log "抓取任务没有生成状态文件,停止导入"
exit 1
fi
archive_sha="$(
python3 - "$STATE_FILE" <<'PY'
import json
import sys
with open(sys.argv[1], encoding="utf-8") as stream:
state = json.load(stream)
print(state.get("archive_sha256") or "")
PY
)"
if [ -z "$archive_sha" ]; then
log "招商银行邮件状态文件缺少账单指纹"
exit 1
fi
if [ -f "$IMPORT_MARKER" ]; then
imported_sha="$(
python3 - "$IMPORT_MARKER" <<'PY'
import json
import sys
with open(sys.argv[1], encoding="utf-8") as stream:
state = json.load(stream)
print(state.get("archive_sha256") or "")
PY
)"
if [ "$imported_sha" = "$archive_sha" ]; then
log "当天相同招商银行账单已导入,跳过重复处理"
exit "$fetch_status"
fi
fi
umask 022
statement_directory="$(
python3 - "$STATE_FILE" <<'PY'
import json
import sys
from pathlib import Path
with open(sys.argv[1], encoding="utf-8") as stream:
state = json.load(stream)
files = [item.get("path") for item in state.get("files") or [] if isinstance(item, dict)]
print(str(Path(files[0]).parent) if files else "")
PY
)"
if [ -z "$statement_directory" ] || [ ! -d "$statement_directory" ]; then
log "招商银行 ZIP 中没有导入文件"
exit 1
fi
log "开始一次导入招商银行账单目录:$statement_directory"
/bin/sh /opt/caiwuxitong/run-finance-batch.sh \
finance-ledger:import-bank-bills-directory \
"$statement_directory" \
--bank=招商银行
python3 - "$STATE_FILE" "$IMPORT_MARKER" <<'PY'
import json
import sys
from datetime import datetime
from zoneinfo import ZoneInfo
with open(sys.argv[1], encoding="utf-8") as stream:
state = json.load(stream)
state["imported_files"] = len(state.get("files") or [])
state["imported_at"] = datetime.now(ZoneInfo("Asia/Shanghai")).isoformat(timespec="seconds")
with open(sys.argv[2], "w", encoding="utf-8") as stream:
json.dump(state, stream, ensure_ascii=False, indent=2)
stream.write("\n")
PY
if [ "$fetch_status" -ne 0 ]; then
log "招商银行邮件抓取返回失败,但已下载内容完成导入"
exit "$fetch_status"
fi
log "招商银行邮件账单已自动接入银行账单"

View File

@ -0,0 +1,53 @@
from __future__ import annotations
import io
import tempfile
import unittest
import zipfile
from pathlib import Path
from fetch_daily import CmbMailError, download_link_from_body, safe_extract
class FetchDailyTest(unittest.TestCase):
def test_extracts_download_link_and_date_range(self) -> None:
body = """
<p>链接:
<a href="s3gw.cmbimg.com/example/file.zip?filename=%E8%B4%A6%E5%8D%95-20261101-20261124.zip">
点击此处下载文件
</a>
</p>
"""
link = download_link_from_body(body)
self.assertIsNotNone(link)
self.assertEqual("20261101", link.date_start)
self.assertEqual("20261124", link.date_end)
def test_rejects_unsafe_zip_member(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
archive = root / "statement.zip"
with zipfile.ZipFile(archive, "w") as output:
output.writestr("../outside.xlsx", b"bad")
with self.assertRaises(CmbMailError):
safe_extract(archive, root / "contents")
def test_extracts_supported_statement_file(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
archive = root / "statement.zip"
with zipfile.ZipFile(archive, "w") as output:
output.writestr("企业账户交易明细.xlsx", b"fixture")
files = safe_extract(archive, root / "contents")
self.assertEqual(1, len(files))
self.assertEqual("企业账户交易明细.xlsx", files[0]["name"])
self.assertTrue(Path(files[0]["path"]).is_file())
if __name__ == "__main__":
unittest.main()

View File

@ -213,6 +213,78 @@ class ImportBankBillsTest extends FeatureTestCase
], 'business_mirror');
}
public function test_imports_all_bank_bill_files_in_directory_and_syncs_once(): void
{
$connection = DB::connection('business_mirror');
$connection->table('fin_accounts')->insert([
[
'company_name' => '目录招商公司一',
'account_short' => '目录招行一',
'account_type' => '公户',
'bank_name' => '招商银行',
'account_no' => '5199050000000101',
'account_should_keep' => '是',
],
[
'company_name' => '目录招商公司二',
'account_short' => '目录招行二',
'account_type' => '公户',
'bank_name' => '招商银行',
'account_no' => '5199050000000102',
'account_should_keep' => '是',
],
]);
$this->configureHeaders('招商银行', [
'账号', '账号名称', '交易日', '交易时间', '借方金额', '贷方金额', '余额', '流水号',
]);
$headers = [
'账号', '账号名称', '交易日', '交易时间', '借方金额', '贷方金额', '余额', '流水号',
];
$first = $this->workbook([
$headers,
['5199050000000101', '目录招商公司一', '2026-11-24', '09:00:00', '-', '100.00', '1100.00', 'DIR-IN-1'],
]);
$second = $this->workbook([
$headers,
['5199050000000102', '目录招商公司二', '2026-11-24', '10:00:00', '50.00', '-', '950.00', 'DIR-OUT-2'],
]);
$directory = sys_get_temp_dir() . '/bank-bills-directory-' . bin2hex(random_bytes(6));
mkdir($directory);
rename($first, $directory . '/01.xlsx');
rename($second, $directory . '/02.xlsx');
try {
$this->artisan('finance-ledger:import-bank-bills-directory', [
'path' => $directory,
'--bank' => '招商银行',
])->assertSuccessful();
} finally {
@unlink($directory . '/01.xlsx');
@unlink($directory . '/02.xlsx');
@rmdir($directory);
}
$this->assertDatabaseCount('fin_bank_direct_bills', 2, 'business_mirror');
$this->assertDatabaseHas('fin_bank_direct_bills', [
'record_code' => 'DIR-IN-1',
'income' => 100,
'expense' => 0,
], 'business_mirror');
$this->assertDatabaseHas('fin_bank_direct_bills', [
'record_code' => 'DIR-OUT-2',
'income' => 0,
'expense' => 50,
], 'business_mirror');
$this->assertDatabaseHas('fin_accounts', [
'account_no' => '5199050000000101',
'current_balance' => 1100,
], 'business_mirror');
$this->assertDatabaseHas('fin_accounts', [
'account_no' => '5199050000000102',
'current_balance' => 950,
], 'business_mirror');
}
/**
* @param list<string> $headers
*/

View File

@ -62,6 +62,30 @@ class FinanceImportTest(unittest.TestCase):
self.assertEqual(0, result)
self.assertEqual('--file=/run/caiwu-import/0/' + source.name, calls[0].args[0][-1])
def test_directory_is_read_only_and_copied_with_its_statement_files(self):
with tempfile.TemporaryDirectory() as folder:
source = pathlib.Path(folder) / '招商银行账单'
source.mkdir()
(source / '01.xlsx').write_bytes(b'first')
(source / '02.xlsx').write_bytes(b'second')
def execute(command, **kwargs):
if command[1] == 'rm':
return subprocess.CompletedProcess(command, 0)
mount = command[command.index('--volume') + 1]
staged = pathlib.Path(mount.rsplit(':', 2)[0]) / '0' / source.name
self.assertEqual(b'first', (staged / '01.xlsx').read_bytes())
self.assertEqual(b'second', (staged / '02.xlsx').read_bytes())
self.assertEqual(0, (staged / '01.xlsx').stat().st_mode & 0o222)
self.assertEqual('/run/caiwu-import/0/' + source.name, command[-2])
return subprocess.CompletedProcess(command, 0)
result, _ = self.run_import(
['finance-ledger:import-bank-bills-directory', str(source), '--bank=招商银行'],
execute,
)
self.assertEqual(0, result)
def test_low_memory_does_not_start_a_container(self):
result, calls = self.run_import(['order-data:import-after-sales-cost', '/input.xlsx'], memory=1024*1024)
self.assertEqual(75, result)