CaiWuXiTong/modules/EcommerceFinance/Services/IcbcBankStatementPdfParser.php

362 lines
12 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Modules\EcommerceFinance\Services;
use DOMDocument;
use DOMElement;
use DOMXPath;
use InvalidArgumentException;
final class IcbcBankStatementPdfParser
{
private const HEADERS = [
'凭证号',
'对方账号',
'交易时间',
'借贷标志',
'对方单位',
'对方行号',
'用途',
'摘要',
'附言',
'转入金额',
'转出金额',
'余额',
];
/**
* @return array{
* account_no:string,
* account_name:string,
* opening_bank:string,
* currency:string,
* from:string,
* to:string,
* rows:list<array<string,mixed>>
* }
*/
public function parse(string $bboxXml): array
{
$pages = $this->pages($bboxXml);
if ($pages === []) {
throw new InvalidArgumentException('工商银行 PDF 中没有可读取的文字。');
}
$metadata = null;
$rows = [];
foreach ($pages as $words) {
$header = $this->header($words);
if ($header === null) {
continue;
}
$metadata ??= $this->metadata($words, $header['y']);
array_push($rows, ...$this->rows($words, $header));
}
if ($metadata === null) {
throw new InvalidArgumentException('工商银行 PDF 中未找到账户明细表头。');
}
if ($rows === []) {
throw new InvalidArgumentException('工商银行 PDF 中未识别到交易明细。');
}
return $metadata + ['rows' => $rows];
}
/**
* @return list<list<array{text:string,x:float,y:float}>>
*/
private function pages(string $bboxXml): array
{
$document = new DOMDocument();
$previous = libxml_use_internal_errors(true);
$loaded = $document->loadXML($bboxXml, LIBXML_NONET | LIBXML_NOBLANKS);
libxml_clear_errors();
libxml_use_internal_errors($previous);
if (! $loaded) {
throw new InvalidArgumentException('工商银行 PDF 的文字版面无法读取。');
}
$xpath = new DOMXPath($document);
$pages = [];
foreach ($xpath->query('//*[local-name()="page"]') as $page) {
if (! $page instanceof DOMElement) {
continue;
}
$words = [];
foreach ($xpath->query('.//*[local-name()="word"]', $page) as $word) {
if (! $word instanceof DOMElement) {
continue;
}
$xMin = (float) $word->getAttribute('xMin');
$xMax = (float) $word->getAttribute('xMax');
$yMin = (float) $word->getAttribute('yMin');
$text = trim($word->textContent);
if ($text === '') {
continue;
}
$words[] = [
'text' => $text,
'x' => ($xMin + $xMax) / 2,
'y' => $yMin,
];
}
if ($words !== []) {
usort($words, static fn (array $left, array $right): int => (
($left['y'] <=> $right['y']) ?: ($left['x'] <=> $right['x'])
));
$pages[] = $words;
}
}
return $pages;
}
/**
* @param list<array{text:string,x:float,y:float}> $words
* @return array{y:float,centers:list<float>,boundaries:list<float>}|null
*/
private function header(array $words): ?array
{
foreach ($this->lineGroups($words) as $line) {
if (count($line) !== count(self::HEADERS)) {
continue;
}
$labels = array_column($line, 'text');
if ($labels !== self::HEADERS) {
continue;
}
$centers = array_map(
static fn (array $word): float => (float) $word['x'],
$line,
);
$boundaries = [];
for ($index = 0; $index < count($centers); $index++) {
$left = $index === 0
? $centers[0] - (($centers[1] ?? $centers[0]) - $centers[0]) / 2
: ($centers[$index - 1] + $centers[$index]) / 2;
$boundaries[] = $left;
}
$lastGap = count($centers) > 1
? $centers[array_key_last($centers)] - $centers[count($centers) - 2]
: 60;
$boundaries[] = $centers[array_key_last($centers)] + $lastGap / 2;
return [
'y' => (float) $line[0]['y'],
'centers' => $centers,
'boundaries' => $boundaries,
];
}
return null;
}
/**
* @param list<array{text:string,x:float,y:float}> $words
* @return array{account_no:string,account_name:string,opening_bank:string,currency:string,from:string,to:string}
*/
private function metadata(array $words, float $headerY): array
{
$lines = [];
foreach ($this->lineGroups($words) as $line) {
if ($line[0]['y'] >= $headerY - 0.5) {
break;
}
$lines[] = implode('', array_column($line, 'text'));
}
$text = implode("\n", $lines);
if (preg_match('/账号[::](\d+).*?币种[::](\S+?)(?:单位|$)/u', $text, $account) !== 1) {
throw new InvalidArgumentException('工商银行 PDF 缺少账号或币种。');
}
if (preg_match(
'/本方账号户名[::](.*?)本方账号开户行[::](.*?)时间范围[::](\d{8})-(\d{8})/u',
$text,
$range,
) !== 1) {
throw new InvalidArgumentException('工商银行 PDF 缺少户名、开户行或查询时间范围。');
}
return [
'account_no' => trim($account[1]),
'account_name' => trim($range[1]),
'opening_bank' => trim($range[2]),
'currency' => trim($account[2]),
'from' => $this->compactDate($range[3]),
'to' => $this->compactDate($range[4]),
];
}
/**
* @param list<array{text:string,x:float,y:float}> $words
* @param array{y:float,centers:list<float>,boundaries:list<float>} $header
* @return list<array<string,mixed>>
*/
private function rows(array $words, array $header): array
{
$footerY = null;
foreach ($words as $word) {
if (str_contains($word['text'], '重要提示')) {
$footerY = $word['y'];
break;
}
}
$anchors = [];
foreach ($words as $word) {
if ($word['y'] <= $header['y']
|| ($footerY !== null && $word['y'] >= $footerY)
|| ! $this->isDate($word['text'])) {
continue;
}
if ($this->columnIndex($word['x'], $header['boundaries']) !== 2) {
continue;
}
$anchors[] = $word['y'];
}
$anchors = array_values(array_unique(array_map(
static fn (float $y): string => number_format($y, 3, '.', ''),
$anchors,
)));
$anchors = array_map('floatval', $anchors);
sort($anchors, SORT_NUMERIC);
if ($anchors === []) {
return [];
}
$rowHeight = count($anchors) > 1
? $anchors[1] - $anchors[0]
: 24.0;
$rows = [];
foreach ($anchors as $index => $anchor) {
$lower = $index === 0 ? $anchor - 4.0 : ($anchors[$index - 1] + $anchor) / 2;
$upper = isset($anchors[$index + 1])
? ($anchor + $anchors[$index + 1]) / 2
: min(
$anchor + $rowHeight - 2.0,
$footerY === null ? $anchor + $rowHeight - 2.0 : $footerY - 1.0,
);
$columns = array_fill(0, count(self::HEADERS), []);
foreach ($words as $word) {
if ($word['y'] < $lower || $word['y'] >= $upper) {
continue;
}
$column = $this->columnIndex($word['x'], $header['boundaries']);
if ($column >= 0 && $column < count(self::HEADERS)) {
$columns[$column][] = $word;
}
}
$values = [];
foreach (self::HEADERS as $column => $label) {
usort($columns[$column], static fn (array $left, array $right): int => (
($left['y'] <=> $right['y']) ?: ($left['x'] <=> $right['x'])
));
$values[$label] = trim(implode('', array_column($columns[$column], 'text')));
}
$rows[] = $this->row($values);
}
return $rows;
}
/**
* @param array<string,string> $values
* @return array<string,mixed>
*/
private function row(array $values): array
{
if (preg_match(
'/^(\d{4}-\d{2}-\d{2})\s*(\d{2}:\d{2}:\d{2})$/u',
$values['交易时间'],
$transaction,
) !== 1) {
throw new InvalidArgumentException('工商银行 PDF 交易明细缺少交易时间。');
}
if (! in_array($values['借贷标志'], ['借', '贷'], true)) {
throw new InvalidArgumentException('工商银行 PDF 交易明细缺少借贷标志。');
}
$values['交易时间'] = $transaction[1] . ' ' . $transaction[2];
$incoming = $this->signedAmount($values['转入金额']);
$outgoing = $this->signedAmount($values['转出金额']);
if ($incoming == 0.0 && $outgoing == 0.0) {
throw new InvalidArgumentException('工商银行 PDF 交易明细缺少发生金额。');
}
$signedAmount = $incoming != 0.0 ? $incoming : -$outgoing;
return [
'txn_at' => $transaction[1] . ' ' . $transaction[2],
'direction' => $values['借贷标志'],
'record_code' => $values['凭证号'],
'counterparty_account' => preg_replace('/\s+/u', '', $values['对方账号']) ?? '',
'counterparty_name' => $values['对方单位'],
'counterparty_bank' => $values['对方行号'],
'purpose' => $values['用途'],
'summary' => $values['摘要'],
'remark' => $values['附言'],
'income' => $signedAmount > 0 ? round($signedAmount, 2) : 0.0,
'expense' => $signedAmount < 0 ? round(abs($signedAmount), 2) : 0.0,
'balance' => $this->signedAmount($values['余额']),
'raw_data' => $values,
];
}
/**
* @param list<array{text:string,x:float,y:float}> $words
* @return list<list<array{text:string,x:float,y:float}>>
*/
private function lineGroups(array $words): array
{
$groups = [];
foreach ($words as $word) {
$key = number_format($word['y'], 1, '.', '');
$groups[$key][] = $word;
}
ksort($groups, SORT_NUMERIC);
foreach ($groups as &$group) {
usort($group, static fn (array $left, array $right): int => $left['x'] <=> $right['x']);
}
unset($group);
return array_values($groups);
}
/**
* @param list<float> $boundaries
*/
private function columnIndex(float $x, array $boundaries): int
{
foreach (array_slice($boundaries, 0, -1) as $index => $boundary) {
if ($x >= $boundary && $x < $boundaries[$index + 1]) {
return $index;
}
}
return -1;
}
private function isDate(string $value): bool
{
return preg_match('/^\d{4}-\d{2}-\d{2}$/u', $value) === 1;
}
private function signedAmount(string $value): float
{
$value = trim($value);
if ($value === '' || $value === '-') {
return 0.0;
}
$normalised = preg_replace('/[^\d.\-]/u', '', $value) ?? '';
return round((float) $normalised, 2);
}
private function compactDate(string $value): string
{
return substr($value, 0, 4)
. '-'
. substr($value, 4, 2)
. '-'
. substr($value, 6, 2);
}
}