861 lines
33 KiB
PHP
861 lines
33 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services;
|
||
|
||
use App\Utilities\FinanceLedgerBankDirectAccounts;
|
||
use Carbon\CarbonImmutable;
|
||
use Illuminate\Database\ConnectionInterface;
|
||
use Illuminate\Database\DatabaseManager;
|
||
use InvalidArgumentException;
|
||
use PhpOffice\PhpSpreadsheet\Shared\Date as ExcelDate;
|
||
use RuntimeException;
|
||
use Throwable;
|
||
|
||
final class BankBillStatementImporter
|
||
{
|
||
private const TABLE = 'fin_bank_direct_bills';
|
||
|
||
private const COLUMNS_TABLE = 'fin_bank_direct_bill_columns';
|
||
|
||
private const BATCH_SIZE = 300;
|
||
|
||
private readonly ConnectionInterface $connection;
|
||
|
||
public function __construct(
|
||
DatabaseManager $databases,
|
||
private readonly FinanceLedgerBankBalanceSynchronizer $balanceSynchronizer,
|
||
)
|
||
{
|
||
$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,
|
||
string $bankName,
|
||
bool $dryRun = false,
|
||
bool $replaceBank = false,
|
||
bool $syncBalances = true,
|
||
string $scope = BankBillTemplateExporter::SCOPE_DIRECT,
|
||
): array
|
||
{
|
||
$bankName = trim($bankName);
|
||
if (! in_array($scope, [
|
||
BankBillTemplateExporter::SCOPE_DIRECT,
|
||
BankBillTemplateExporter::SCOPE_NON_DIRECT,
|
||
], true)) {
|
||
throw new InvalidArgumentException('请选择有效的账单导入类型。');
|
||
}
|
||
if (! in_array($bankName, BankBillTemplateExporter::banks($scope), true)) {
|
||
throw new InvalidArgumentException($scope === BankBillTemplateExporter::SCOPE_DIRECT
|
||
? '请选择招商银行、华夏银行或网商银行直连账单模板。'
|
||
: '请选择已经接入的非银企直连银行模板。');
|
||
}
|
||
if (! is_file($path) || ! is_readable($path)) {
|
||
throw new InvalidArgumentException('银行账单文件不存在或不可读取。');
|
||
}
|
||
|
||
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
|
||
if (! in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
|
||
throw new InvalidArgumentException('银行账单仅支持 XLSX、XLS 或 CSV 文件。');
|
||
}
|
||
|
||
$reader = PayablesWorkbookStreamReader::forFile($path, $extension);
|
||
$metadata = [];
|
||
if ($scope === BankBillTemplateExporter::SCOPE_NON_DIRECT) {
|
||
if ($bankName === '华夏银行') {
|
||
[$headerRow, $headers, $metadata] = $this->huaxiaMonthlyHeaderAndMetadata($reader);
|
||
} else {
|
||
[$headerRow, $headers] = $this->headerRow($reader);
|
||
}
|
||
[$sourceIndexByKey, $labelBySourceIndex] = $this->genericSourceIndexes(
|
||
BankBillTemplateExporter::headers($bankName, $scope),
|
||
$headers,
|
||
);
|
||
} elseif ($bankName === '网商银行') {
|
||
[$headerRow, $headers, $metadata] = $this->wangshangHeaderAndMetadata($reader);
|
||
$sourceIndexByKey = [];
|
||
$labelBySourceIndex = [];
|
||
foreach ($headers as $sourceIndex => $label) {
|
||
$sourceIndexByKey[(int) $sourceIndex] = 'source_c' . str_pad(
|
||
(string) ((int) $sourceIndex + 1),
|
||
3,
|
||
'0',
|
||
STR_PAD_LEFT,
|
||
);
|
||
$labelBySourceIndex[(int) $sourceIndex] = $label;
|
||
}
|
||
} else {
|
||
$columns = $this->columns($bankName);
|
||
[$headerRow, $headers] = $this->headerRow($reader);
|
||
[$sourceIndexByKey, $labelBySourceIndex] = $this->configuredSourceIndexes($columns, $headers);
|
||
}
|
||
$accountsByNumber = $this->accountsByNumber(
|
||
$scope === BankBillTemplateExporter::SCOPE_DIRECT ? $bankName : '',
|
||
);
|
||
$templateAccount = $scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
||
&& $bankName === '华夏银行'
|
||
? $this->huaxiaMonthlyAccount((string) ($metadata['company_name'] ?? ''))
|
||
: null;
|
||
$sourceFileName = basename($path);
|
||
$sourceHash = hash_file('sha256', $path);
|
||
if (! is_string($sourceHash)) {
|
||
throw new RuntimeException('无法计算银行账单文件指纹。');
|
||
}
|
||
|
||
$now = now();
|
||
$batch = [];
|
||
$rowKeys = [];
|
||
$stats = [
|
||
'scope' => $scope,
|
||
'bank' => $bankName,
|
||
'rows' => 0,
|
||
'affected' => 0,
|
||
'inserted' => 0,
|
||
'updated' => 0,
|
||
'skipped' => 0,
|
||
'accounts' => 0,
|
||
'synced_accounts' => 0,
|
||
'first_date' => null,
|
||
'last_date' => null,
|
||
'duplicate_rows' => 0,
|
||
'dry_run' => $dryRun,
|
||
'account_numbers' => [],
|
||
];
|
||
$accountNumbers = [];
|
||
$incomeRows = 0;
|
||
$expenseRows = 0;
|
||
$importedIncome = 0.0;
|
||
$importedExpense = 0.0;
|
||
|
||
if (! $dryRun) {
|
||
$this->connection->beginTransaction();
|
||
if ($replaceBank) {
|
||
$this->connection->table(self::TABLE)->where('bank_name', $bankName)->delete();
|
||
}
|
||
}
|
||
|
||
try {
|
||
foreach ($reader->rows(0, $headerRow) as $cells) {
|
||
$rawData = [];
|
||
foreach ($sourceIndexByKey as $sourceIndex => $columnKey) {
|
||
$value = $this->normaliseCell($cells[$sourceIndex] ?? null);
|
||
if ($value !== '') {
|
||
$rawData[$columnKey] = $value;
|
||
}
|
||
}
|
||
if ($rawData === []) {
|
||
continue;
|
||
}
|
||
|
||
$valuesByLabel = [];
|
||
foreach ($labelBySourceIndex as $sourceIndex => $label) {
|
||
$value = $this->normaliseCell($cells[$sourceIndex] ?? null);
|
||
if ($value !== '') {
|
||
$valuesByLabel[$label] = $value;
|
||
}
|
||
}
|
||
|
||
$transaction = $this->transactionDateTime($valuesByLabel);
|
||
if ($transaction === null) {
|
||
$stats['skipped']++;
|
||
|
||
continue;
|
||
}
|
||
|
||
$accountNo = $bankName === '网商银行'
|
||
? (string) ($metadata['account_no'] ?? '')
|
||
: $this->accountNumber($valuesByLabel);
|
||
$account = $accountsByNumber[$this->digits($accountNo)] ?? null;
|
||
if ($account === null && $templateAccount !== null) {
|
||
$account = $templateAccount;
|
||
$accountNo = trim((string) ($templateAccount->account_no ?? ''));
|
||
}
|
||
if ($accountNo === '') {
|
||
$stats['skipped']++;
|
||
|
||
continue;
|
||
}
|
||
|
||
$rowBankName = $bankName;
|
||
$companyName = $bankName === '网商银行'
|
||
? (string) ($metadata['company_name'] ?? '')
|
||
: (string) ($metadata['company_name'] ?? $this->firstValue(
|
||
$valuesByLabel,
|
||
['单位名称', '公司名称', '账号名称', '账户名称', '己方银行户名'],
|
||
));
|
||
$accountShort = (string) ($account->account_short ?? '');
|
||
if ($accountShort === '') {
|
||
$accountShort = $this->firstValue(
|
||
$valuesByLabel,
|
||
['账户别名', '账户名称', '账号名称', '单位名称', '己方银行户名'],
|
||
);
|
||
}
|
||
if ($accountShort === '') {
|
||
$accountShort = $accountNo;
|
||
}
|
||
|
||
if ($bankName === '网商银行') {
|
||
$income = $this->amount($this->firstValue($valuesByLabel, ['借方金额(收)', '借方金额(收)']));
|
||
$expense = $this->amount($this->firstValue($valuesByLabel, ['贷方金额(支)', '贷方金额(支)']));
|
||
} else {
|
||
$income = $this->amount($this->firstValue(
|
||
$valuesByLabel,
|
||
['收入金额', '收入金额(元)', '贷方金额'],
|
||
));
|
||
$expense = $this->amount($this->firstValue(
|
||
$valuesByLabel,
|
||
['支出金额', '支出金额(元)', '借方金额'],
|
||
));
|
||
}
|
||
$balanceValue = $this->firstValue(
|
||
$valuesByLabel,
|
||
['账户余额', '己方账户余额(元)', '余额'],
|
||
);
|
||
$balance = $balanceValue === '' ? null : $this->amount($balanceValue);
|
||
$recordCode = $this->firstValue(
|
||
$valuesByLabel,
|
||
['账务流水号', '银行流水号', '核心流水号', '流水号', '凭证号', '凭证号码'],
|
||
);
|
||
$counterpartyName = $this->firstValue(
|
||
$valuesByLabel,
|
||
['对方户名', '对手方别名', '收(付)方名称'],
|
||
);
|
||
$counterpartyAccount = $this->firstValue(
|
||
$valuesByLabel,
|
||
['对方账号', '对手方银行账号', '收(付)方账号'],
|
||
);
|
||
$counterpartyBank = $this->firstValue(
|
||
$valuesByLabel,
|
||
['对方机构', '对方开户行', '对方行名', '对手方开户行', '收(付)方开户行名'],
|
||
);
|
||
$detailParts = [];
|
||
foreach (['交易类型', '摘要', '业务摘要', '其它摘要', '交易描述', '渠道'] as $label) {
|
||
$value = trim((string) ($valuesByLabel[$label] ?? ''));
|
||
if ($value !== '' && ! in_array($value, $detailParts, true)) {
|
||
$detailParts[] = $value;
|
||
}
|
||
}
|
||
$paymentRemark = $this->firstValue(
|
||
$valuesByLabel,
|
||
['备注', '用途', '附言', '附言(用途)', '明细标注', '业务参考号'],
|
||
);
|
||
$currency = $bankName === '网商银行'
|
||
? (string) ($metadata['currency'] ?? '人民币')
|
||
: (
|
||
(string) ($metadata['currency'] ?? '')
|
||
?: ($this->firstValue($valuesByLabel, ['币种']) ?: '人民币')
|
||
);
|
||
$rowKey = hash('sha256', json_encode([
|
||
$rowBankName,
|
||
$this->digits($accountNo),
|
||
$transaction['at'],
|
||
$recordCode,
|
||
$rawData,
|
||
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
||
$rowKeys[] = $rowKey;
|
||
|
||
$stats['rows']++;
|
||
$importedIncome += $income;
|
||
$importedExpense += $expense;
|
||
if ($income > 0) {
|
||
$incomeRows++;
|
||
}
|
||
if ($expense > 0) {
|
||
$expenseRows++;
|
||
}
|
||
$accountNumbers[$this->digits($accountNo)] = true;
|
||
$stats['first_date'] = $stats['first_date'] === null || $transaction['date'] < $stats['first_date']
|
||
? $transaction['date']
|
||
: $stats['first_date'];
|
||
$stats['last_date'] = $stats['last_date'] === null || $transaction['date'] > $stats['last_date']
|
||
? $transaction['date']
|
||
: $stats['last_date'];
|
||
|
||
if ($dryRun) {
|
||
continue;
|
||
}
|
||
|
||
$batch[] = [
|
||
'bank_name' => $rowBankName,
|
||
'finance_account_id' => $account->id ?? null,
|
||
'company_name' => $this->truncate($companyName ?: (string) ($account->company_name ?? ''), 100),
|
||
'account_short' => $this->truncate($accountShort, 100),
|
||
'account_no' => $this->truncate($accountNo, 64),
|
||
'txn_date' => $transaction['date'],
|
||
'txn_at' => $transaction['at'],
|
||
'record_code' => $this->truncate($recordCode, 128),
|
||
'counterparty_name' => $this->truncate($counterpartyName, 255),
|
||
'counterparty_account' => $this->truncate($counterpartyAccount, 100),
|
||
'counterparty_bank' => $this->truncate($counterpartyBank, 100),
|
||
'detail' => $this->truncate(implode(' · ', $detailParts), 2000),
|
||
'payment_remark' => $this->truncate($paymentRemark, 2000),
|
||
'income' => $income,
|
||
'expense' => $expense,
|
||
'balance' => $balance,
|
||
'currency' => $this->truncate($currency, 16),
|
||
'raw_data' => json_encode($rawData, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||
'source' => $scope === BankBillTemplateExporter::SCOPE_DIRECT
|
||
? 'bank-direct'
|
||
: 'bank-monthly',
|
||
'source_file_name' => $sourceFileName,
|
||
'source_file_sha256' => $sourceHash,
|
||
'row_key' => $rowKey,
|
||
'imported_at' => $now,
|
||
'created_at' => $now,
|
||
'updated_at' => $now,
|
||
];
|
||
if (count($batch) >= self::BATCH_SIZE) {
|
||
$this->flush($batch, $rowKeys, $stats);
|
||
$batch = [];
|
||
$rowKeys = [];
|
||
}
|
||
}
|
||
|
||
if ($batch !== []) {
|
||
$this->flush($batch, $rowKeys, $stats);
|
||
}
|
||
if ($dryRun && $rowKeys !== []) {
|
||
$stats['duplicate_rows'] = $this->existingRowCount($rowKeys);
|
||
}
|
||
if ($bankName === '网商银行') {
|
||
$this->validateBillControl(
|
||
'网商银行',
|
||
$stats,
|
||
$incomeRows,
|
||
$expenseRows,
|
||
round($importedIncome, 2),
|
||
round($importedExpense, 2),
|
||
$metadata,
|
||
);
|
||
} elseif ($scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
|
||
&& $bankName === '华夏银行') {
|
||
$this->validateBillControl(
|
||
'华夏银行',
|
||
$stats,
|
||
$incomeRows,
|
||
$expenseRows,
|
||
round($importedIncome, 2),
|
||
round($importedExpense, 2),
|
||
$metadata,
|
||
);
|
||
}
|
||
if (! $dryRun) {
|
||
$this->connection->commit();
|
||
}
|
||
} catch (Throwable $exception) {
|
||
if (! $dryRun) {
|
||
$this->connection->rollBack();
|
||
}
|
||
|
||
throw $exception;
|
||
}
|
||
|
||
$stats['accounts'] = count($accountNumbers);
|
||
$stats['account_numbers'] = array_keys($accountNumbers);
|
||
if (! $dryRun
|
||
&& $syncBalances
|
||
&& $scope === BankBillTemplateExporter::SCOPE_DIRECT) {
|
||
$stats['synced_accounts'] = $this->balanceSynchronizer->syncAccountNumbers(
|
||
$stats['account_numbers'],
|
||
);
|
||
}
|
||
|
||
return $stats;
|
||
}
|
||
|
||
private function existingRowCount(array $rowKeys): int
|
||
{
|
||
$count = 0;
|
||
foreach (array_chunk(array_values(array_unique($rowKeys)), 500) as $chunk) {
|
||
$count += $this->connection->table(self::TABLE)
|
||
->whereIn('row_key', $chunk)
|
||
->count();
|
||
}
|
||
|
||
return $count;
|
||
}
|
||
|
||
private function flush(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);
|
||
}
|
||
|
||
private function columns(string $bankName)
|
||
{
|
||
$columns = $this->connection->table(self::COLUMNS_TABLE)
|
||
->where('bank_name', $bankName)
|
||
->orderBy('sort_order')
|
||
->orderBy('id')
|
||
->get();
|
||
if ($columns->isEmpty()) {
|
||
throw new InvalidArgumentException('请先导入该银行的账单表头,再导入明细数据。');
|
||
}
|
||
|
||
return $columns;
|
||
}
|
||
|
||
/**
|
||
* @return array{0:int,1:array<int,string>,2:array<string,mixed>}
|
||
*/
|
||
private function wangshangHeaderAndMetadata(PayablesWorkbookStreamReader $reader): array
|
||
{
|
||
$headerRow = null;
|
||
$headers = [];
|
||
$rawMetadata = [];
|
||
$metadataLabels = [
|
||
'企业名称',
|
||
'企业账号',
|
||
'借方交易笔数',
|
||
'借方交易金额',
|
||
'贷方交易笔数',
|
||
'贷方交易金额',
|
||
];
|
||
|
||
foreach ($reader->rows(0, null, 20) as $rowNumber => $cells) {
|
||
$values = array_map(fn (mixed $value): string => $this->normaliseCell($value), $cells);
|
||
foreach ($values as $index => $value) {
|
||
if (! in_array($value, $metadataLabels, true) || array_key_exists($value, $rawMetadata)) {
|
||
continue;
|
||
}
|
||
$keys = array_keys($values);
|
||
$position = array_search($index, $keys, true);
|
||
for ($cursor = (int) $position + 1; $cursor < count($keys); $cursor++) {
|
||
$candidate = $values[$keys[$cursor]] ?? '';
|
||
if ($candidate !== '') {
|
||
$rawMetadata[$value] = $candidate;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
|
||
$candidateHeaders = [];
|
||
foreach ($values as $index => $value) {
|
||
if ($value !== '') {
|
||
$candidateHeaders[(int) $index] = $value;
|
||
}
|
||
}
|
||
if (count(array_intersect(
|
||
array_values($candidateHeaders),
|
||
['账务流水号', '交易时间', '借方金额(收)', '贷方金额(支)'],
|
||
)) === 4) {
|
||
$headerRow = $rowNumber;
|
||
$headers = $candidateHeaders;
|
||
break;
|
||
}
|
||
}
|
||
|
||
if ($headerRow === null) {
|
||
throw new InvalidArgumentException('没有找到网商银行账单明细表头。');
|
||
}
|
||
|
||
$companyName = trim((string) ($rawMetadata['企业名称'] ?? ''));
|
||
$accountValue = trim((string) ($rawMetadata['企业账号'] ?? ''));
|
||
$accountNo = $this->digits($accountValue);
|
||
if ($companyName === '' || $accountNo === '') {
|
||
throw new InvalidArgumentException('网商银行账单缺少企业名称或企业账号。');
|
||
}
|
||
preg_match('/\(([^)]+)\)/u', $accountValue, $currencyMatch);
|
||
|
||
return [
|
||
$headerRow,
|
||
$headers,
|
||
[
|
||
'company_name' => $companyName,
|
||
'account_no' => $accountNo,
|
||
'currency' => trim((string) ($currencyMatch[1] ?? '')) ?: '人民币',
|
||
'expected_income_rows' => $this->countFromText($rawMetadata['借方交易笔数'] ?? null),
|
||
'expected_expense_rows' => $this->countFromText($rawMetadata['贷方交易笔数'] ?? null),
|
||
'expected_income' => $this->moneyFromText($rawMetadata['借方交易金额'] ?? null),
|
||
'expected_expense' => $this->moneyFromText($rawMetadata['贷方交易金额'] ?? null),
|
||
],
|
||
];
|
||
}
|
||
|
||
/**
|
||
* @return array{0:int,1:array<int,string>,2:array<string,mixed>}
|
||
*/
|
||
private function huaxiaMonthlyHeaderAndMetadata(PayablesWorkbookStreamReader $reader): array
|
||
{
|
||
[$headerRow, $headers] = $this->headerRow($reader);
|
||
$labels = [
|
||
'户名:' => 'company_name',
|
||
'币种:' => 'currency',
|
||
'收入总金额:' => 'expected_income',
|
||
'支出总金额:' => 'expected_expense',
|
||
'收入总笔数:' => 'expected_income_rows',
|
||
'支出总笔数:' => 'expected_expense_rows',
|
||
];
|
||
$rawMetadata = [];
|
||
foreach ($reader->rows(0, null, $headerRow) as $cells) {
|
||
$values = array_map(fn (mixed $value): string => $this->normaliseCell($value), $cells);
|
||
$keys = array_keys($values);
|
||
foreach ($values as $index => $value) {
|
||
$metaKey = $labels[$value] ?? null;
|
||
if ($metaKey === null || array_key_exists($metaKey, $rawMetadata)) {
|
||
continue;
|
||
}
|
||
$position = array_search($index, $keys, true);
|
||
for ($cursor = (int) $position + 1; $cursor < count($keys); $cursor++) {
|
||
$candidate = trim((string) ($values[$keys[$cursor]] ?? ''));
|
||
if ($candidate !== '') {
|
||
$rawMetadata[$metaKey] = $candidate;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
$companyName = trim((string) ($rawMetadata['company_name'] ?? ''));
|
||
if ($companyName === '') {
|
||
throw new InvalidArgumentException('华夏银行非银企直连账单缺少“户名”。');
|
||
}
|
||
|
||
return [
|
||
$headerRow,
|
||
$headers,
|
||
[
|
||
'company_name' => $companyName,
|
||
'currency' => trim((string) ($rawMetadata['currency'] ?? '')) ?: '人民币',
|
||
'expected_income_rows' => $this->countFromText($rawMetadata['expected_income_rows'] ?? null),
|
||
'expected_expense_rows' => $this->countFromText($rawMetadata['expected_expense_rows'] ?? null),
|
||
'expected_income' => $this->moneyFromText($rawMetadata['expected_income'] ?? null),
|
||
'expected_expense' => $this->moneyFromText($rawMetadata['expected_expense'] ?? null),
|
||
],
|
||
];
|
||
}
|
||
|
||
private function huaxiaMonthlyAccount(string $companyName): object
|
||
{
|
||
$companyName = trim($companyName);
|
||
if ($companyName === '') {
|
||
throw new InvalidArgumentException('华夏银行非银企直连账单缺少户名,无法定位账户。');
|
||
}
|
||
|
||
$directAccounts = FinanceLedgerBankDirectAccounts::map($this->connection);
|
||
$accounts = $this->connection->table('fin_accounts')
|
||
->where('company_name', $companyName)
|
||
->get(['id', 'account_short', 'account_no', 'account_type', 'bank_name'])
|
||
->filter(function (object $account) use ($directAccounts): bool {
|
||
$accountShort = trim((string) ($account->account_short ?? ''));
|
||
$bankName = trim((string) ($account->bank_name ?? ''));
|
||
$isHuaXia = str_contains($bankName, '华夏')
|
||
|| (($bankName === '' || $bankName === '/')
|
||
&& str_contains($accountShort, '华夏'));
|
||
|
||
return $accountShort !== ''
|
||
&& ! isset($directAccounts[$accountShort])
|
||
&& $isHuaXia;
|
||
})
|
||
->values();
|
||
if ($accounts->isEmpty()) {
|
||
throw new InvalidArgumentException(sprintf(
|
||
'未找到户名“%s”对应的华夏银行非银企直连账户,请先维护账户基本信息。',
|
||
$companyName,
|
||
));
|
||
}
|
||
if ($accounts->count() > 1) {
|
||
throw new InvalidArgumentException(sprintf(
|
||
'户名“%s”对应多个华夏银行非银企直连账户,无法自动定位,请补充账户信息后再导入。',
|
||
$companyName,
|
||
));
|
||
}
|
||
|
||
return $accounts->first();
|
||
}
|
||
|
||
private function validateBillControl(
|
||
string $bankLabel,
|
||
array $stats,
|
||
int $incomeRows,
|
||
int $expenseRows,
|
||
float $income,
|
||
float $expense,
|
||
array $metadata,
|
||
): void {
|
||
$checks = [
|
||
['label' => '借方笔数', 'actual' => $incomeRows, 'expected' => $metadata['expected_income_rows'] ?? null],
|
||
['label' => '贷方笔数', 'actual' => $expenseRows, 'expected' => $metadata['expected_expense_rows'] ?? null],
|
||
['label' => '借方金额', 'actual' => $income, 'expected' => $metadata['expected_income'] ?? null],
|
||
['label' => '贷方金额', 'actual' => $expense, 'expected' => $metadata['expected_expense'] ?? null],
|
||
];
|
||
foreach ($checks as $check) {
|
||
$expected = $check['expected'];
|
||
if ($expected === null) {
|
||
continue;
|
||
}
|
||
$matches = is_float($expected)
|
||
? abs((float) $check['actual'] - (float) $expected) <= 0.01
|
||
: (int) $check['actual'] === (int) $expected;
|
||
if (! $matches) {
|
||
throw new InvalidArgumentException(sprintf(
|
||
'%s账单%s与页面汇总不一致:页面 %s,明细 %s;未写入账单。',
|
||
$bankLabel,
|
||
$check['label'],
|
||
is_float($expected) ? number_format((float) $expected, 2, '.', '') : (string) $expected,
|
||
is_float($check['actual']) ? number_format((float) $check['actual'], 2, '.', '') : (string) $check['actual'],
|
||
));
|
||
}
|
||
}
|
||
}
|
||
|
||
private function countFromText(mixed $value): ?int
|
||
{
|
||
if ($value === null || trim((string) $value) === '') {
|
||
return null;
|
||
}
|
||
$digits = preg_replace('/\D+/', '', (string) $value) ?? '';
|
||
|
||
return $digits === '' ? null : (int) $digits;
|
||
}
|
||
|
||
private function moneyFromText(mixed $value): ?float
|
||
{
|
||
if ($value === null || trim((string) $value) === '') {
|
||
return null;
|
||
}
|
||
|
||
return $this->amount((string) $value);
|
||
}
|
||
|
||
/**
|
||
* @return array{0:int,1:array<int,string>}
|
||
*/
|
||
private function headerRow(PayablesWorkbookStreamReader $reader): array
|
||
{
|
||
foreach ($reader->rows(0, null, 20) as $rowNumber => $cells) {
|
||
$headers = [];
|
||
foreach ($cells as $index => $value) {
|
||
$value = $this->normaliseCell($value);
|
||
if ($value !== '') {
|
||
$headers[(int) $index] = $value;
|
||
}
|
||
}
|
||
$keyHeaderCount = count(array_intersect(
|
||
array_values($headers),
|
||
[
|
||
'账号',
|
||
'银行账号',
|
||
'己方银行账号',
|
||
'交易时间',
|
||
'交易日',
|
||
'收入金额',
|
||
'收入金额(元)',
|
||
'支出金额',
|
||
'支出金额(元)',
|
||
'借方金额',
|
||
'贷方金额',
|
||
],
|
||
));
|
||
if (count($headers) >= 5 && $keyHeaderCount >= 2) {
|
||
return [$rowNumber, $headers];
|
||
}
|
||
}
|
||
|
||
throw new InvalidArgumentException('没有找到银行账单表头行。');
|
||
}
|
||
|
||
/**
|
||
* @return array{0:array<int,string>,1:array<int,string>}
|
||
*/
|
||
private function configuredSourceIndexes($columns, array $headers): array
|
||
{
|
||
$indexByLabel = array_flip($headers);
|
||
$sourceIndexByKey = [];
|
||
$labelBySourceIndex = [];
|
||
foreach ($columns as $column) {
|
||
$label = (string) $column->source_header;
|
||
$sourceIndex = $indexByLabel[$label] ?? null;
|
||
if ($sourceIndex === null) {
|
||
throw new InvalidArgumentException(
|
||
sprintf('文件缺少已配置的表头“%s”,请先重新导入表头。', $label),
|
||
);
|
||
}
|
||
$sourceIndexByKey[(int) $sourceIndex] = (string) $column->column_key;
|
||
$labelBySourceIndex[(int) $sourceIndex] = $label;
|
||
}
|
||
|
||
return [$sourceIndexByKey, $labelBySourceIndex];
|
||
}
|
||
|
||
/**
|
||
* @param list<string> $expectedHeaders
|
||
* @return array{0:array<int,string>,1:array<int,string>}
|
||
*/
|
||
private function genericSourceIndexes(array $expectedHeaders, array $headers): array
|
||
{
|
||
$indexByLabel = array_flip($headers);
|
||
$sourceIndexByKey = [];
|
||
$labelBySourceIndex = [];
|
||
foreach ($expectedHeaders as $index => $label) {
|
||
$sourceIndex = $indexByLabel[$label] ?? null;
|
||
if ($sourceIndex === null) {
|
||
throw new InvalidArgumentException(
|
||
sprintf('非银企直连账单缺少该银行模板表头“%s”,请重新下载对应银行模板。', $label),
|
||
);
|
||
}
|
||
$sourceIndex = (int) $sourceIndex;
|
||
$sourceIndexByKey[$sourceIndex] = 'source_c' . str_pad(
|
||
(string) ($index + 1),
|
||
3,
|
||
'0',
|
||
STR_PAD_LEFT,
|
||
);
|
||
$labelBySourceIndex[$sourceIndex] = $label;
|
||
}
|
||
|
||
return [$sourceIndexByKey, $labelBySourceIndex];
|
||
}
|
||
|
||
private function accountsByNumber(string $bankName): array
|
||
{
|
||
$accounts = $this->connection->table('fin_accounts')
|
||
->select(['id', 'company_name', 'account_short', 'account_no', 'bank_name'])
|
||
->whereNotNull('account_no')
|
||
->where('account_no', '<>', '')
|
||
->get();
|
||
$map = [];
|
||
foreach ($accounts as $account) {
|
||
$number = $this->digits((string) $account->account_no);
|
||
if ($number === '') {
|
||
continue;
|
||
}
|
||
if (! isset($map[$number])
|
||
|| (! str_contains((string) $map[$number]->bank_name, $bankName)
|
||
&& str_contains((string) $account->bank_name, $bankName))) {
|
||
$map[$number] = $account;
|
||
}
|
||
}
|
||
|
||
return $map;
|
||
}
|
||
|
||
/**
|
||
* @return array{date:string,at:string}|null
|
||
*/
|
||
private function transactionDateTime(array $values): ?array
|
||
{
|
||
$dateValue = $this->firstValue($values, ['交易日', '交易日期']);
|
||
$timeValue = $this->firstValue($values, ['交易时间']);
|
||
$candidate = trim($dateValue . ' ' . $timeValue);
|
||
if ($candidate === '') {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
if (is_numeric($candidate)) {
|
||
$date = ExcelDate::excelToDateTimeObject((float) $candidate);
|
||
|
||
return [
|
||
'date' => $date->format('Y-m-d'),
|
||
'at' => $date->format('Y-m-d H:i:s'),
|
||
];
|
||
}
|
||
$date = CarbonImmutable::parse($candidate, 'Asia/Shanghai');
|
||
} catch (Throwable) {
|
||
return null;
|
||
}
|
||
|
||
return [
|
||
'date' => $date->format('Y-m-d'),
|
||
'at' => $date->format('Y-m-d H:i:s'),
|
||
];
|
||
}
|
||
|
||
private function accountNumber(array $values): string
|
||
{
|
||
return $this->firstValue($values, ['账号', '银行账号', '己方银行账号']);
|
||
}
|
||
|
||
private function firstValue(array $values, array $labels): string
|
||
{
|
||
foreach ($labels as $label) {
|
||
$value = trim((string) ($values[$label] ?? ''));
|
||
if ($value !== '' && $value !== '-') {
|
||
return $value;
|
||
}
|
||
}
|
||
|
||
return '';
|
||
}
|
||
|
||
private function amount(string $value): float
|
||
{
|
||
$value = trim($value);
|
||
if ($value === '' || $value === '-' || $value === '—') {
|
||
return 0.0;
|
||
}
|
||
$negative = str_starts_with($value, '(') && str_ends_with($value, ')');
|
||
$normalised = preg_replace('/[^\d.\-]/u', '', $value) ?? '';
|
||
|
||
return round(abs((float) $normalised) * ($negative ? -1 : 1), 2);
|
||
}
|
||
|
||
private function digits(string $value): string
|
||
{
|
||
return preg_replace('/\D+/', '', $value) ?? '';
|
||
}
|
||
|
||
private function normaliseCell(mixed $value): string
|
||
{
|
||
if ($value === null) {
|
||
return '';
|
||
}
|
||
if ($value instanceof \DateTimeInterface) {
|
||
return $value->format('Y-m-d H:i:s');
|
||
}
|
||
|
||
return trim((string) $value);
|
||
}
|
||
|
||
private function truncate(string $value, int $length): string
|
||
{
|
||
return mb_substr($value, 0, $length);
|
||
}
|
||
}
|