按银行账号接入银企直联可用余额快照,并用于账户总览期末余额。 Co-authored-by: 92451 <924518135@qq.com> Co-committed-by: 92451 <924518135@qq.com>
470 lines
18 KiB
PHP
470 lines
18 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services;
|
||
|
||
use App\Utilities\FinanceLedgerFlowSummaryDataSource;
|
||
use Carbon\CarbonImmutable;
|
||
use Illuminate\Database\ConnectionInterface;
|
||
use Illuminate\Database\DatabaseManager;
|
||
use Illuminate\Support\Facades\Schema;
|
||
use InvalidArgumentException;
|
||
use Modules\EcommerceFinance\Repositories\BankDirectBalanceRepository;
|
||
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
|
||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
||
use RuntimeException;
|
||
use Throwable;
|
||
|
||
final class BankDirectBalanceWorkbookImporter
|
||
{
|
||
private readonly ConnectionInterface $connection;
|
||
|
||
public function __construct(DatabaseManager $database)
|
||
{
|
||
$this->connection = $database->connection(
|
||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||
);
|
||
}
|
||
|
||
/**
|
||
* @return array{
|
||
* balance_date:string,
|
||
* total:int,
|
||
* replaced:int,
|
||
* available_total:float,
|
||
* bank_count:int,
|
||
* dry_run:bool
|
||
* }
|
||
*/
|
||
public function import(string $path, ?string $balanceDate = null, bool $dryRun = false): array
|
||
{
|
||
$realPath = realpath($path);
|
||
if ($realPath === false || ! is_file($realPath) || ! is_readable($realPath)) {
|
||
throw new InvalidArgumentException('银企直联余额文件不存在或不可读取。');
|
||
}
|
||
|
||
$requestedDate = $this->validatedDate($balanceDate);
|
||
$parsed = $this->parseWorkbook($realPath, $requestedDate);
|
||
$rows = $this->matchAccounts($parsed['rows']);
|
||
$selectedDate = $parsed['balance_date'];
|
||
$bankNames = array_values(array_unique(array_column($rows, 'bank_name')));
|
||
$accountIds = array_values(array_unique(array_column($rows, 'finance_account_id')));
|
||
$snapshotTableReady = Schema::connection($this->connection->getName())
|
||
->hasTable(BankDirectBalanceRepository::TABLE);
|
||
if (! $snapshotTableReady && ! $dryRun) {
|
||
throw new RuntimeException('银企直联余额快照表尚未创建,请先执行数据库迁移。');
|
||
}
|
||
|
||
$existing = $snapshotTableReady
|
||
? $this->connection->table(BankDirectBalanceRepository::TABLE)
|
||
->where('balance_date', $selectedDate)
|
||
->where('source', BankDirectBalanceRepository::SOURCE)
|
||
->whereIn('finance_account_id', $accountIds)
|
||
->count()
|
||
: 0;
|
||
|
||
if (! $dryRun) {
|
||
$now = now();
|
||
$sourceName = mb_substr(basename($realPath), 0, 255);
|
||
$sourceSha256 = hash_file('sha256', $realPath);
|
||
if (! is_string($sourceSha256) || strlen($sourceSha256) !== 64) {
|
||
throw new RuntimeException('银企直联余额文件摘要计算失败。');
|
||
}
|
||
|
||
$this->connection->transaction(function () use (
|
||
$rows,
|
||
$selectedDate,
|
||
$accountIds,
|
||
$sourceName,
|
||
$sourceSha256,
|
||
$now,
|
||
): void {
|
||
$this->connection->table(BankDirectBalanceRepository::TABLE)
|
||
->where('balance_date', $selectedDate)
|
||
->where('source', BankDirectBalanceRepository::SOURCE)
|
||
->whereIn('finance_account_id', $accountIds)
|
||
->delete();
|
||
|
||
foreach (array_chunk($rows, 500) as $chunk) {
|
||
$this->connection->table(BankDirectBalanceRepository::TABLE)->insert(array_map(
|
||
static fn (array $row): array => $row + [
|
||
'balance_date' => $selectedDate,
|
||
'source' => BankDirectBalanceRepository::SOURCE,
|
||
'source_file_name' => $sourceName,
|
||
'source_sha256' => $sourceSha256,
|
||
'imported_at' => $now,
|
||
'created_at' => $now,
|
||
'updated_at' => $now,
|
||
],
|
||
$chunk,
|
||
));
|
||
}
|
||
|
||
foreach ($rows as $row) {
|
||
$source = $this->connection->table('fin_flow_summary_account_sources')
|
||
->where('account_short', $row['account_short'])
|
||
->first();
|
||
if ($source === null) {
|
||
$this->connection->table('fin_flow_summary_account_sources')->insert([
|
||
'account_short' => $row['account_short'],
|
||
'data_source' => FinanceLedgerFlowSummaryDataSource::DIRECT,
|
||
'updated_by' => '银企直联余额导入',
|
||
'created_at' => $now,
|
||
'updated_at' => $now,
|
||
]);
|
||
} else {
|
||
$this->connection->table('fin_flow_summary_account_sources')
|
||
->where('account_short', $row['account_short'])
|
||
->update([
|
||
'data_source' => FinanceLedgerFlowSummaryDataSource::DIRECT,
|
||
'updated_by' => '银企直联余额导入',
|
||
'updated_at' => $now,
|
||
]);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
return [
|
||
'balance_date' => $selectedDate,
|
||
'total' => count($rows),
|
||
'replaced' => $existing,
|
||
'available_total' => round(array_sum(array_column($rows, 'available_balance')), 2),
|
||
'bank_count' => count($bankNames),
|
||
'dry_run' => $dryRun,
|
||
];
|
||
}
|
||
|
||
/**
|
||
* @return array{
|
||
* balance_date:string,
|
||
* rows:list<array{
|
||
* account_no:string,
|
||
* account_name:string,
|
||
* company_name:string,
|
||
* bank_name:string,
|
||
* currency:string,
|
||
* account_balance:?float,
|
||
* available_balance:float,
|
||
* balance_at:string
|
||
* }>
|
||
* }
|
||
*/
|
||
private function parseWorkbook(string $path, ?string $requestedDate): array
|
||
{
|
||
try {
|
||
$spreadsheet = IOFactory::load($path);
|
||
} catch (Throwable) {
|
||
throw new InvalidArgumentException('银企直联余额文件无法读取,请确认文件未损坏并使用 XLSX/XLS 格式。');
|
||
}
|
||
|
||
try {
|
||
$sheet = $spreadsheet->getSheetByName('sheet1') ?? $spreadsheet->getActiveSheet();
|
||
[$headerRow, $columns] = $this->columns($sheet);
|
||
$rows = [];
|
||
$errors = [];
|
||
$dates = [];
|
||
$seen = [];
|
||
|
||
for ($rowNumber = $headerRow + 1; $rowNumber <= $sheet->getHighestDataRow(); $rowNumber++) {
|
||
$accountNo = $this->normalizeAccountNo($this->cell($sheet, $columns['account_no'], $rowNumber));
|
||
$availableText = $this->cell($sheet, $columns['available_balance'], $rowNumber);
|
||
$balanceAtText = $this->cell($sheet, $columns['balance_at'], $rowNumber);
|
||
if ($accountNo === '' && $availableText === '' && $balanceAtText === '') {
|
||
continue;
|
||
}
|
||
if ($accountNo === '') {
|
||
$errors[] = "第 {$rowNumber} 行缺少银行账号";
|
||
continue;
|
||
}
|
||
if (isset($seen[$accountNo])) {
|
||
$errors[] = "第 {$rowNumber} 行银行账号重复";
|
||
continue;
|
||
}
|
||
$seen[$accountNo] = true;
|
||
|
||
$availableBalance = $this->amount($availableText);
|
||
if ($availableBalance === null) {
|
||
$errors[] = "第 {$rowNumber} 行可用余额不是有效金额";
|
||
continue;
|
||
}
|
||
|
||
$accountBalance = isset($columns['account_balance'])
|
||
? $this->amount($this->cell($sheet, $columns['account_balance'], $rowNumber))
|
||
: null;
|
||
$balanceAt = $this->dateTime($balanceAtText);
|
||
if ($balanceAt === null) {
|
||
$errors[] = "第 {$rowNumber} 行余额更新日期无效";
|
||
continue;
|
||
}
|
||
$date = substr($balanceAt, 0, 10);
|
||
$dates[$date] = true;
|
||
if ($requestedDate !== null && $date !== $requestedDate) {
|
||
$errors[] = "第 {$rowNumber} 行余额日期与指定日期不一致";
|
||
continue;
|
||
}
|
||
|
||
$rows[] = [
|
||
'account_no' => $accountNo,
|
||
'account_name' => $this->cell($sheet, $columns['account_name'], $rowNumber),
|
||
'company_name' => isset($columns['company_name'])
|
||
? $this->cell($sheet, $columns['company_name'], $rowNumber)
|
||
: '',
|
||
'bank_name' => $this->cell($sheet, $columns['bank_name'], $rowNumber),
|
||
'currency' => isset($columns['currency'])
|
||
? $this->cell($sheet, $columns['currency'], $rowNumber)
|
||
: '',
|
||
'account_balance' => $accountBalance,
|
||
'available_balance' => $availableBalance,
|
||
'balance_at' => $balanceAt,
|
||
];
|
||
}
|
||
|
||
if ($rows === [] && $errors === []) {
|
||
throw new InvalidArgumentException('银企直联余额文件中没有可导入的数据行。');
|
||
}
|
||
if ($errors !== []) {
|
||
throw new InvalidArgumentException(
|
||
'银企直联余额文件校验失败:' . implode(';', array_slice($errors, 0, 10)),
|
||
);
|
||
}
|
||
if (count($dates) !== 1) {
|
||
throw new InvalidArgumentException('一个银企直联余额文件只能包含一个余额日期。');
|
||
}
|
||
|
||
$selectedDate = (string) array_key_first($dates);
|
||
if ($requestedDate !== null && $selectedDate !== $requestedDate) {
|
||
throw new InvalidArgumentException('银企直联余额文件日期与指定日期不一致。');
|
||
}
|
||
|
||
return ['balance_date' => $selectedDate, 'rows' => $rows];
|
||
} finally {
|
||
$spreadsheet->disconnectWorksheets();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* @return array{0:int,1:array<string,int>}
|
||
*/
|
||
private function columns(Worksheet $sheet): array
|
||
{
|
||
$headerNames = [
|
||
'account_no' => ['银行账号', '账号', '银行账户'],
|
||
'account_name' => ['账户名称'],
|
||
'company_name' => ['所属企业'],
|
||
'bank_name' => ['所属银行'],
|
||
'currency' => ['币种'],
|
||
'account_balance' => ['账户余额'],
|
||
'available_balance' => ['可用余额'],
|
||
'balance_at' => ['余额更新日期'],
|
||
];
|
||
|
||
for ($rowNumber = 1; $rowNumber <= min(20, $sheet->getHighestDataRow()); $rowNumber++) {
|
||
$byColumn = [];
|
||
$byName = [];
|
||
$duplicateHeader = null;
|
||
$highestColumn = Coordinate::columnIndexFromString(
|
||
$sheet->getHighestDataColumn($rowNumber),
|
||
);
|
||
for ($column = 1; $column <= $highestColumn; $column++) {
|
||
$name = trim((string) $sheet->getCell([$column, $rowNumber])->getFormattedValue());
|
||
if ($name === '') {
|
||
continue;
|
||
}
|
||
if (isset($byName[$name])) {
|
||
$duplicateHeader ??= $name;
|
||
continue;
|
||
}
|
||
$byName[$name] = $column;
|
||
$byColumn[$column] = $name;
|
||
}
|
||
|
||
$accountNoColumn = null;
|
||
foreach ($headerNames['account_no'] as $name) {
|
||
if (isset($byName[$name])) {
|
||
$accountNoColumn = $byName[$name];
|
||
break;
|
||
}
|
||
}
|
||
$accountNameColumn = $byName['账户名称'] ?? null;
|
||
if ($accountNoColumn === null
|
||
&& $accountNameColumn !== null
|
||
&& $accountNameColumn > 1
|
||
&& ($byColumn[$accountNameColumn - 1] ?? null) === null) {
|
||
$accountNoColumn = $accountNameColumn - 1;
|
||
}
|
||
|
||
if ($accountNoColumn === null
|
||
|| ! isset($byName['可用余额'], $byName['余额更新日期'], $byName['所属银行'])) {
|
||
continue;
|
||
}
|
||
if ($duplicateHeader !== null) {
|
||
throw new InvalidArgumentException("银企直联余额表头“{$duplicateHeader}”重复。");
|
||
}
|
||
|
||
$columns = [
|
||
'account_no' => $accountNoColumn,
|
||
'account_name' => $accountNameColumn ?? $this->requiredColumn($byName, '账户名称'),
|
||
'bank_name' => $byName['所属银行'],
|
||
'available_balance' => $byName['可用余额'],
|
||
'balance_at' => $byName['余额更新日期'],
|
||
];
|
||
foreach (['company_name', 'currency', 'account_balance'] as $key) {
|
||
foreach ($headerNames[$key] as $name) {
|
||
if (isset($byName[$name])) {
|
||
$columns[$key] = $byName[$name];
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
return [$rowNumber, $columns];
|
||
}
|
||
|
||
throw new InvalidArgumentException(
|
||
'银企直联余额文件缺少“银行账号、账户名称、所属银行、可用余额、余额更新日期”表头。',
|
||
);
|
||
}
|
||
|
||
/**
|
||
* @param array<string,int> $byName
|
||
*/
|
||
private function requiredColumn(array $byName, string $name): int
|
||
{
|
||
if (! isset($byName[$name])) {
|
||
throw new InvalidArgumentException("银企直联余额文件缺少“{$name}”列。");
|
||
}
|
||
|
||
return $byName[$name];
|
||
}
|
||
|
||
/**
|
||
* @param list<array<string,mixed>> $rows
|
||
* @return list<array<string,mixed>>
|
||
*/
|
||
private function matchAccounts(array $rows): array
|
||
{
|
||
$accounts = $this->connection->table('fin_accounts')
|
||
->whereNotNull('account_no')
|
||
->get(['id', 'account_no', 'account_short', 'company_name']);
|
||
$accountShortCounts = $accounts
|
||
->groupBy(static fn (object $account): string => trim((string) $account->account_short))
|
||
->map(static fn ($group): int => $group->count());
|
||
$byAccountNo = $accounts->groupBy(
|
||
fn (object $account): string => $this->normalizeAccountNo((string) $account->account_no),
|
||
);
|
||
$ambiguousRows = [];
|
||
$missingRows = [];
|
||
$columnRows = [];
|
||
$matched = [];
|
||
|
||
foreach ($rows as $index => $row) {
|
||
$matches = $byAccountNo->get($row['account_no'], collect());
|
||
if ($matches->count() !== 1) {
|
||
if ($matches->count() === 0) {
|
||
$missingRows[] = $index + 2;
|
||
} else {
|
||
$ambiguousRows[] = $index + 2;
|
||
}
|
||
continue;
|
||
}
|
||
|
||
$account = $matches->first();
|
||
$accountShort = trim((string) $account->account_short);
|
||
if ($accountShort === '' || (int) $accountShortCounts->get($accountShort, 0) !== 1) {
|
||
$columnRows[] = $index + 2;
|
||
continue;
|
||
}
|
||
|
||
$matched[] = $row + [
|
||
'finance_account_id' => (int) $account->id,
|
||
'account_short' => $accountShort,
|
||
'company_name' => trim((string) ($row['company_name'] !== ''
|
||
? $row['company_name']
|
||
: $account->company_name)),
|
||
];
|
||
}
|
||
|
||
if ($missingRows !== [] || $ambiguousRows !== [] || $columnRows !== []) {
|
||
$parts = [];
|
||
if ($missingRows !== []) {
|
||
$parts[] = '未匹配 ' . count($missingRows) . ' 个银行账号';
|
||
}
|
||
if ($ambiguousRows !== []) {
|
||
$parts[] = '匹配到多个账户 ' . count($ambiguousRows) . ' 个银行账号';
|
||
}
|
||
if ($columnRows !== []) {
|
||
$parts[] = '账户简称缺失或重复 ' . count($columnRows) . ' 个银行账号';
|
||
}
|
||
|
||
throw new InvalidArgumentException(
|
||
'银企直联余额账户校验失败:' . implode(',', $parts) . ';请先核对账户总表,未写入任何余额。',
|
||
);
|
||
}
|
||
|
||
if ($matched === []) {
|
||
throw new InvalidArgumentException('银企直联余额文件没有匹配到账户总表中的银行账户。');
|
||
}
|
||
|
||
return $matched;
|
||
}
|
||
|
||
private function cell(Worksheet $sheet, int $column, int $row): string
|
||
{
|
||
return trim((string) $sheet->getCell([$column, $row])->getFormattedValue());
|
||
}
|
||
|
||
private function normalizeAccountNo(string $value): string
|
||
{
|
||
return trim((string) preg_replace('/\s+/u', '', ltrim(trim($value), "'")));
|
||
}
|
||
|
||
private function amount(string $value): ?float
|
||
{
|
||
$normalized = trim(str_replace(
|
||
[' ', ',', ',', '¥', '¥', '元'],
|
||
'',
|
||
$value,
|
||
));
|
||
$negative = str_starts_with($normalized, '(') && str_ends_with($normalized, ')');
|
||
if ($negative) {
|
||
$normalized = substr($normalized, 1, -1);
|
||
}
|
||
if ($normalized === '' || ! is_numeric($normalized)) {
|
||
return null;
|
||
}
|
||
|
||
$amount = round((float) $normalized, 2);
|
||
|
||
return $negative ? -$amount : $amount;
|
||
}
|
||
|
||
private function dateTime(string $value): ?string
|
||
{
|
||
$value = trim($value);
|
||
if ($value === '') {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
return CarbonImmutable::parse($value, 'Asia/Shanghai')->format('Y-m-d H:i:s');
|
||
} catch (Throwable) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
private function validatedDate(?string $value): ?string
|
||
{
|
||
$value = trim((string) $value);
|
||
if ($value === '') {
|
||
return null;
|
||
}
|
||
$date = CarbonImmutable::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai');
|
||
if (! $date instanceof CarbonImmutable || $date->format('Y-m-d') !== $value) {
|
||
throw new InvalidArgumentException('余额日期格式应为 YYYY-MM-DD。');
|
||
}
|
||
|
||
return $value;
|
||
}
|
||
}
|