261 lines
9.5 KiB
PHP
261 lines
9.5 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services;
|
||
|
||
use Illuminate\Database\ConnectionInterface;
|
||
use Illuminate\Database\DatabaseManager;
|
||
use InvalidArgumentException;
|
||
use RuntimeException;
|
||
use Symfony\Component\Process\Process;
|
||
use Throwable;
|
||
|
||
final class IcbcBankStatementPdfImporter
|
||
{
|
||
private const TABLE = 'fin_bank_direct_bills';
|
||
|
||
private readonly ConnectionInterface $connection;
|
||
|
||
public function __construct(
|
||
DatabaseManager $databases,
|
||
private readonly IcbcBankStatementPdfParser $parser,
|
||
) {
|
||
$this->connection = $databases->connection(
|
||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||
);
|
||
}
|
||
|
||
/**
|
||
* @return array{
|
||
* scope:string,bank:string,rows:int,affected:int,inserted:int,updated:int,skipped:int,
|
||
* accounts:int,synced_accounts:int,first_date:?string,last_date:?string,
|
||
* duplicate_rows:int,dry_run:bool,account_numbers:list<string>
|
||
* }
|
||
*/
|
||
public function import(
|
||
string $path,
|
||
bool $dryRun = false,
|
||
?string $sourceFileName = null,
|
||
): array {
|
||
if (! is_file($path) || ! is_readable($path)) {
|
||
throw new InvalidArgumentException('工商银行 PDF 文件不存在或不可读取。');
|
||
}
|
||
if (strtolower(pathinfo($path, PATHINFO_EXTENSION)) !== 'pdf') {
|
||
throw new InvalidArgumentException('中国工商银行模板仅支持 PDF 文件。');
|
||
}
|
||
|
||
$parsed = $this->parser->parse($this->extractBbox($path));
|
||
$accountNo = preg_replace('/\D+/', '', $parsed['account_no']) ?? '';
|
||
$account = $this->account($accountNo);
|
||
$now = now();
|
||
$sourceHash = hash_file('sha256', $path);
|
||
if (! is_string($sourceHash)) {
|
||
throw new RuntimeException('无法计算工商银行 PDF 文件指纹。');
|
||
}
|
||
|
||
$batch = [];
|
||
$rowKeys = [];
|
||
$stats = [
|
||
'scope' => BankBillTemplateExporter::SCOPE_NON_DIRECT,
|
||
'bank' => '中国工商银行',
|
||
'rows' => 0,
|
||
'affected' => 0,
|
||
'inserted' => 0,
|
||
'updated' => 0,
|
||
'skipped' => 0,
|
||
'accounts' => 1,
|
||
'synced_accounts' => 0,
|
||
'first_date' => null,
|
||
'last_date' => null,
|
||
'duplicate_rows' => 0,
|
||
'dry_run' => $dryRun,
|
||
'account_numbers' => [$accountNo],
|
||
];
|
||
foreach ($parsed['rows'] as $row) {
|
||
$rawData = $row['raw_data'];
|
||
$rowKey = hash('sha256', json_encode([
|
||
'中国工商银行',
|
||
$accountNo,
|
||
$row['txn_at'],
|
||
$row['record_code'],
|
||
$rawData,
|
||
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||
$rowKeys[] = $rowKey;
|
||
$date = substr((string) $row['txn_at'], 0, 10);
|
||
$stats['rows']++;
|
||
$stats['first_date'] = $stats['first_date'] === null || $date < $stats['first_date']
|
||
? $date
|
||
: $stats['first_date'];
|
||
$stats['last_date'] = $stats['last_date'] === null || $date > $stats['last_date']
|
||
? $date
|
||
: $stats['last_date'];
|
||
if ($dryRun) {
|
||
continue;
|
||
}
|
||
|
||
$detail = implode(' · ', array_values(array_unique(array_filter([
|
||
trim((string) ($row['purpose'] ?? '')),
|
||
trim((string) ($row['summary'] ?? '')),
|
||
], static fn (string $value): bool => $value !== ''))));
|
||
$batch[] = [
|
||
'bank_name' => '中国工商银行',
|
||
'finance_account_id' => $account->id,
|
||
'company_name' => mb_substr((string) $account->company_name, 0, 100),
|
||
'account_short' => mb_substr((string) $account->account_short, 0, 100),
|
||
'account_no' => mb_substr($accountNo, 0, 64),
|
||
'txn_date' => $date,
|
||
'txn_at' => (string) $row['txn_at'],
|
||
'record_code' => mb_substr((string) $row['record_code'], 0, 128),
|
||
'counterparty_name' => mb_substr((string) $row['counterparty_name'], 0, 255),
|
||
'counterparty_account' => mb_substr((string) $row['counterparty_account'], 0, 100),
|
||
'counterparty_bank' => mb_substr((string) $row['counterparty_bank'], 0, 100),
|
||
'detail' => mb_substr($detail, 0, 2000),
|
||
'payment_remark' => mb_substr((string) $row['remark'], 0, 2000),
|
||
'income' => (float) $row['income'],
|
||
'expense' => (float) $row['expense'],
|
||
'balance' => (float) $row['balance'],
|
||
'currency' => mb_substr($parsed['currency'], 0, 16),
|
||
'raw_data' => json_encode($rawData, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||
'source' => 'bank-monthly',
|
||
'source_file_name' => mb_substr($sourceFileName ?: basename($path), 0, 255),
|
||
'source_file_sha256' => $sourceHash,
|
||
'row_key' => $rowKey,
|
||
'imported_at' => $now,
|
||
'created_at' => $now,
|
||
'updated_at' => $now,
|
||
];
|
||
}
|
||
if ($stats['rows'] === 0) {
|
||
throw new InvalidArgumentException('工商银行 PDF 中未识别到有效流水。');
|
||
}
|
||
if ($dryRun) {
|
||
$stats['duplicate_rows'] = $this->existingRowCount($rowKeys);
|
||
|
||
return $stats;
|
||
}
|
||
|
||
$this->connection->beginTransaction();
|
||
try {
|
||
$this->write($batch, $rowKeys, $stats);
|
||
$this->connection->commit();
|
||
} catch (Throwable $exception) {
|
||
$this->connection->rollBack();
|
||
|
||
throw $exception;
|
||
}
|
||
|
||
return $stats;
|
||
}
|
||
|
||
private function extractBbox(string $path): string
|
||
{
|
||
$temporary = tempnam(sys_get_temp_dir(), 'caiwu-icbc-pdf-');
|
||
if ($temporary === false) {
|
||
throw new RuntimeException('无法创建工商银行 PDF 解析临时文件。');
|
||
}
|
||
@unlink($temporary);
|
||
$output = $temporary . '.xml';
|
||
|
||
try {
|
||
$process = new Process([
|
||
'pdftotext',
|
||
'-bbox-layout',
|
||
'-enc',
|
||
'UTF-8',
|
||
$path,
|
||
$output,
|
||
]);
|
||
$process->setTimeout(60);
|
||
$process->run();
|
||
if (! $process->isSuccessful() || ! is_file($output)) {
|
||
throw new InvalidArgumentException(
|
||
'工商银行 PDF 解析失败,请确认文件未加密且包含可复制的文字。',
|
||
);
|
||
}
|
||
$content = file_get_contents($output);
|
||
if (! is_string($content) || trim($content) === '') {
|
||
throw new InvalidArgumentException('工商银行 PDF 没有可读取的文字层。');
|
||
}
|
||
|
||
return $content;
|
||
} finally {
|
||
@unlink($output);
|
||
}
|
||
}
|
||
|
||
private function account(string $accountNo): object
|
||
{
|
||
$matches = $this->connection->table('fin_accounts')
|
||
->whereNotNull('account_no')
|
||
->where('account_no', '<>', '')
|
||
->get(['id', 'company_name', 'account_short', 'account_no', 'bank_name'])
|
||
->filter(static fn (object $account): bool => (
|
||
preg_replace('/\D+/', '', (string) $account->account_no) ?? ''
|
||
) === $accountNo)
|
||
->values();
|
||
if ($matches->isEmpty()) {
|
||
throw new InvalidArgumentException(sprintf(
|
||
'未找到账号“%s”对应的账户,请先在账户基本信息中维护。',
|
||
$accountNo,
|
||
));
|
||
}
|
||
$preferred = $matches->first(static fn (object $account): bool => (
|
||
str_contains((string) $account->bank_name, '工商')
|
||
|| str_contains((string) $account->bank_name, '工行')
|
||
));
|
||
|
||
return $preferred ?: $matches->first();
|
||
}
|
||
|
||
private function existingRowCount(array $rowKeys): int
|
||
{
|
||
return $this->connection->table(self::TABLE)
|
||
->whereIn('row_key', array_values(array_unique($rowKeys)))
|
||
->count();
|
||
}
|
||
|
||
private function write(array $batch, array $rowKeys, array &$stats): void
|
||
{
|
||
$existing = $this->connection->table(self::TABLE)
|
||
->whereIn('row_key', $rowKeys)
|
||
->pluck('row_key')
|
||
->all();
|
||
$existing = array_fill_keys($existing, true);
|
||
$inserted = count(array_filter(
|
||
$rowKeys,
|
||
static fn (string $key): bool => ! isset($existing[$key]),
|
||
));
|
||
$this->connection->table(self::TABLE)->upsert(
|
||
$batch,
|
||
['row_key'],
|
||
[
|
||
'bank_name',
|
||
'finance_account_id',
|
||
'company_name',
|
||
'account_short',
|
||
'account_no',
|
||
'txn_date',
|
||
'txn_at',
|
||
'record_code',
|
||
'counterparty_name',
|
||
'counterparty_account',
|
||
'counterparty_bank',
|
||
'detail',
|
||
'payment_remark',
|
||
'income',
|
||
'expense',
|
||
'balance',
|
||
'currency',
|
||
'raw_data',
|
||
'source',
|
||
'source_file_name',
|
||
'source_file_sha256',
|
||
'imported_at',
|
||
'updated_at',
|
||
],
|
||
);
|
||
$stats['inserted'] = $inserted;
|
||
$stats['updated'] = count($batch) - $inserted;
|
||
$stats['affected'] = count($batch);
|
||
}
|
||
}
|