feat(财务台账): 增加华夏非直连账单模板 (#1426)

This commit is contained in:
shanshi 2026-11-25 16:30:19 +08:00
parent 0c26491633
commit 9ab3d85a3a
3 changed files with 353 additions and 23 deletions

View File

@ -2,6 +2,7 @@
namespace Modules\EcommerceFinance\Services;
use App\Utilities\FinanceLedgerBankDirectAccounts;
use Carbon\CarbonImmutable;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
@ -70,7 +71,11 @@ final class BankBillStatementImporter
$reader = PayablesWorkbookStreamReader::forFile($path, $extension);
$metadata = [];
if ($scope === BankBillTemplateExporter::SCOPE_NON_DIRECT) {
[$headerRow, $headers] = $this->headerRow($reader);
if ($bankName === '华夏银行') {
[$headerRow, $headers, $metadata] = $this->huaxiaMonthlyHeaderAndMetadata($reader);
} else {
[$headerRow, $headers] = $this->headerRow($reader);
}
[$sourceIndexByKey, $labelBySourceIndex] = $this->genericSourceIndexes(
BankBillTemplateExporter::headers($bankName, $scope),
$headers,
@ -96,6 +101,10 @@ final class BankBillStatementImporter
$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)) {
@ -165,20 +174,24 @@ final class BankBillStatementImporter
$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;
}
$account = $accountsByNumber[$this->digits($accountNo)] ?? null;
$rowBankName = $bankName;
$companyName = $bankName === '网商银行'
? (string) ($metadata['company_name'] ?? '')
: $this->firstValue(
: (string) ($metadata['company_name'] ?? $this->firstValue(
$valuesByLabel,
['单位名称', '公司名称', '账号名称', '账户名称', '己方银行户名'],
);
));
$accountShort = (string) ($account->account_short ?? '');
if ($accountShort === '') {
$accountShort = $this->firstValue(
@ -210,7 +223,7 @@ final class BankBillStatementImporter
$balance = $balanceValue === '' ? null : $this->amount($balanceValue);
$recordCode = $this->firstValue(
$valuesByLabel,
['账务流水号', '银行流水号', '流水号', '凭证号'],
['账务流水号', '银行流水号', '核心流水号', '流水号', '凭证号', '凭证号码'],
);
$counterpartyName = $this->firstValue(
$valuesByLabel,
@ -222,7 +235,7 @@ final class BankBillStatementImporter
);
$counterpartyBank = $this->firstValue(
$valuesByLabel,
['对方机构', '对方开户行', '对手方开户行', '收(付)方开户行名'],
['对方机构', '对方开户行', '对方行名', '对手方开户行', '收(付)方开户行名'],
);
$detailParts = [];
foreach (['交易类型', '摘要', '业务摘要', '其它摘要', '交易描述', '渠道'] as $label) {
@ -233,11 +246,14 @@ final class BankBillStatementImporter
}
$paymentRemark = $this->firstValue(
$valuesByLabel,
['备注', '用途', '附言', '附言(用途)', '业务参考号'],
['备注', '用途', '附言', '附言(用途)', '明细标注', '业务参考号'],
);
$currency = $bankName === '网商银行'
? (string) ($metadata['currency'] ?? '人民币')
: ($this->firstValue($valuesByLabel, ['币种']) ?: '人民币');
: (
(string) ($metadata['currency'] ?? '')
?: ($this->firstValue($valuesByLabel, ['币种']) ?: '人民币')
);
$rowKey = hash('sha256', json_encode([
$rowBankName,
$this->digits($accountNo),
@ -311,7 +327,19 @@ final class BankBillStatementImporter
$stats['duplicate_rows'] = $this->existingRowCount($rowKeys);
}
if ($bankName === '网商银行') {
$this->validateWangshangControl(
$this->validateBillControl(
'网商银行',
$stats,
$incomeRows,
$expenseRows,
round($importedIncome, 2),
round($importedExpense, 2),
$metadata,
);
} elseif ($scope === BankBillTemplateExporter::SCOPE_NON_DIRECT
&& $bankName === '华夏银行') {
$this->validateBillControl(
'华夏银行',
$stats,
$incomeRows,
$expenseRows,
@ -489,7 +517,100 @@ final class BankBillStatementImporter
];
}
private function validateWangshangControl(
/**
* @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,
@ -513,7 +634,8 @@ final class BankBillStatementImporter
: (int) $check['actual'] === (int) $expected;
if (! $matches) {
throw new InvalidArgumentException(sprintf(
'网商银行账单%s与页面汇总不一致:页面 %s,明细 %s;未写入账单。',
'%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'],

View File

@ -93,6 +93,23 @@ final class BankBillTemplateExporter
];
private const NON_DIRECT_HEADERS = [
'华夏银行' => [
'序号',
'交易日期',
'交易时间',
'支出金额',
'收入金额',
'余额',
'对方账号',
'对方户名',
'对方行名',
'核心流水号',
'交易描述',
'摘要',
'凭证号码',
'明细标注',
'记账日期',
],
'杭州银行' => [
'序号',
'交易时间',
@ -213,17 +230,42 @@ final class BankBillTemplateExporter
throw new InvalidArgumentException('请选择支持导入的银行模板。');
}
$headers = self::headers($bank, $scope);
$displayName = $bank;
$isHuaXiaMonthly = $scope === self::SCOPE_NON_DIRECT && $bank === '华夏银行';
$displayName = $isHuaXiaMonthly ? '华夏银行月度' : $bank;
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()
->setCreator('CaiWuXiTong')
->setTitle($displayName . '账单导入模板');
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle($bank);
$headerRow = $bank === '网商银行' ? 5 : 1;
$sheet->setTitle($isHuaXiaMonthly ? '华夏月度明细' : $bank);
$headerRow = $isHuaXiaMonthly ? 12 : ($bank === '网商银行' ? 5 : 1);
if ($bank === '网商银行') {
if ($isHuaXiaMonthly) {
$sheet->fromArray([
['华夏银行交易明细'],
[],
[],
[],
[],
['币种:', '人民币', null, null, '户名:', '请填写户名'],
['查询日期:', '请填写起止日期'],
['交易方向:', '全部'],
['排序方向:', '由近及远'],
['收入总金额:', '0.00', null, null, '收入总笔数:', '0'],
['支出总金额:', '0.00', null, null, '支出总笔数:', '0'],
], null, 'A1', true);
$sheet->mergeCells('A1:O1');
$sheet->getStyle('A1:O1')->getFont()->setBold(true)->setSize(14);
$sheet->getStyle('A1:O1')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
$sheet->getStyle('A6:F11')->getFill()
->setFillType(Fill::FILL_SOLID)
->getStartColor()
->setARGB('FFF7F0DE');
foreach (['A6', 'E6', 'A7', 'A8', 'A9', 'A10', 'E10', 'A11', 'E11'] as $cell) {
$sheet->getStyle($cell)->getFont()->setBold(true);
}
} elseif ($bank === '网商银行') {
$sheet->fromArray([
['浙江网商银行企业账户交易明细'],
['企业名称', '请填写企业名称', null, null, '企业账号', '请填写企业账号(人民币)'],

View File

@ -503,14 +503,34 @@ class BankBillPageTest extends FeatureTestCase
$this->assertSame('华夏银行账单导入模板.xlsx', $template['filename']);
}
public function test_non_direct_template_uses_the_hangzhou_bank_monthly_headers(): void
public function test_non_direct_templates_use_per_bank_monthly_headers(): void
{
$templates = collect(BankBillTemplateExporter::templates(
BankBillTemplateExporter::SCOPE_NON_DIRECT,
));
$this->assertCount(1, $templates);
$this->assertSame('杭州银行', $templates[0]['bank']);
$this->assertCount(2, $templates);
$huaXia = $templates->firstWhere('bank', '华夏银行');
$hangzhou = $templates->firstWhere('bank', '杭州银行');
$this->assertIsArray($huaXia);
$this->assertIsArray($hangzhou);
$this->assertSame([
'序号',
'交易日期',
'交易时间',
'支出金额',
'收入金额',
'余额',
'对方账号',
'对方户名',
'对方行名',
'核心流水号',
'交易描述',
'摘要',
'凭证号码',
'明细标注',
'记账日期',
], $huaXia['headers']);
$this->assertSame([
'序号',
'交易时间',
@ -528,14 +548,26 @@ class BankBillPageTest extends FeatureTestCase
'对手方开户行',
'币种',
'渠道',
], $templates[0]['headers']);
], $hangzhou['headers']);
$template = app(BankBillTemplateExporter::class)->create(
$huaXiaTemplate = app(BankBillTemplateExporter::class)->create(
'华夏银行',
BankBillTemplateExporter::SCOPE_NON_DIRECT,
);
$this->assertSame('华夏银行月度账单导入模板.xlsx', $huaXiaTemplate['filename']);
$spreadsheet = IOFactory::load($huaXiaTemplate['path']);
$workbookHeaders = $spreadsheet->getActiveSheet()
->rangeToArray('A12:O12', null, true, false)[0];
$spreadsheet->disconnectWorksheets();
$this->assertSame($huaXia['headers'], $workbookHeaders);
@unlink($huaXiaTemplate['path']);
$hangzhouTemplate = app(BankBillTemplateExporter::class)->create(
'杭州银行',
BankBillTemplateExporter::SCOPE_NON_DIRECT,
);
$this->assertSame('杭州银行账单导入模板.xlsx', $template['filename']);
@unlink($template['path']);
$this->assertSame('杭州银行账单导入模板.xlsx', $hangzhouTemplate['filename']);
@unlink($hangzhouTemplate['path']);
}
public function test_hua_xia_template_route_downloads_the_workbook(): void
@ -677,7 +709,8 @@ class BankBillPageTest extends FeatureTestCase
]);
$headers = BankBillTemplateExporter::templates(
BankBillTemplateExporter::SCOPE_NON_DIRECT,
)[0]['headers'];
);
$headers = collect($headers)->firstWhere('bank', '杭州银行')['headers'];
$path = $this->workbook([
$headers,
[
@ -750,6 +783,139 @@ class BankBillPageTest extends FeatureTestCase
}
}
public function test_huaxia_non_direct_import_resolves_account_from_unique_company_and_validates_totals(): void
{
$this->user->roles()->sync([
Role::where('name', 'admin')->firstOrFail()->id,
]);
$this->user->unsetRelation('roles');
$connection = DB::connection('business_mirror');
$huaXiaAccountId = $connection->table('fin_accounts')->insertGetId([
'company_name' => '华夏非直连测试公司',
'account_short' => '华夏非直连测试',
'account_type' => '公户',
'bank_name' => '华夏银行常州分行',
'account_no' => '1315000000000088',
'account_should_keep' => '是',
'current_balance' => 1000,
]);
$connection->table('fin_accounts')->insert([
'company_name' => '华夏非直连测试公司',
'account_short' => '华夏非直连测试网商',
'account_type' => '网商银行',
'bank_name' => '浙江网商银行',
'account_no' => '8888888000000088',
'account_should_keep' => '是',
'current_balance' => 500,
]);
$connection->table('fin_flow_summary_account_sources')->insert([
[
'account_short' => '华夏非直连测试',
'data_source' => '手动',
],
[
'account_short' => '华夏非直连测试网商',
'data_source' => '手动',
],
]);
$headers = collect(BankBillTemplateExporter::templates(
BankBillTemplateExporter::SCOPE_NON_DIRECT,
))->firstWhere('bank', '华夏银行')['headers'];
$empty = array_fill(0, count($headers), null);
$path = $this->workbook([
['华夏银行交易明细'],
$empty,
$empty,
$empty,
$empty,
['币种:', '人民币', null, null, '户名:', '华夏非直连测试公司'],
['查询日期:', '2026-11-01 至 2026-11-25'],
['交易方向:', '全部'],
['排序方向:', '由近及远'],
['收入总金额:', '120.00', null, null, '收入总笔数:', '1'],
['支出总金额:', '30.00', null, null, '支出总笔数:', '1'],
$headers,
[
1,
'2026-11-25',
'10:00:00',
null,
'120.00',
'1120.00',
'6222000000000011',
'测试收入方',
'中国银行',
'HX-MONTH-IN',
'跨行收款',
'货款',
null,
'月度收入',
'2026-11-25',
],
[
2,
'2026-11-25',
'11:00:00',
'30.00',
null,
'1090.00',
'6222000000000012',
'测试支出方',
'建设银行',
'HX-MONTH-OUT',
'跨行付款',
'服务费',
'HX-VOUCHER-2',
'月度支出',
'2026-11-25',
],
]);
$payload = [
'scope' => BankBillTemplateExporter::SCOPE_NON_DIRECT,
'bank' => '华夏银行',
'file' => new UploadedFile($path, basename($path), null, null, true),
];
$previewUrl = route('business.financial-ledger.bank-bills.import.preview', [
'company_id' => $this->company->id,
]);
$importUrl = route('business.financial-ledger.bank-bills.import', [
'company_id' => $this->company->id,
]);
try {
$this->loginAs()->post($previewUrl, $payload)
->assertOk()
->assertJsonPath('result.rows', 2)
->assertJsonPath('result.accounts', 1);
$this->loginAs()->post($importUrl, $payload)
->assertOk()
->assertJsonPath('result.inserted', 2)
->assertJsonPath('result.synced_accounts', 0);
$this->assertDatabaseHas('fin_bank_direct_bills', [
'finance_account_id' => $huaXiaAccountId,
'bank_name' => '华夏银行',
'account_short' => '华夏非直连测试',
'record_code' => 'HX-MONTH-IN',
'income' => 120,
'expense' => 0,
'balance' => 1120,
'source' => 'bank-monthly',
], 'business_mirror');
$this->assertDatabaseHas('fin_bank_direct_bills', [
'finance_account_id' => $huaXiaAccountId,
'record_code' => 'HX-MONTH-OUT',
'income' => 0,
'expense' => 30,
'balance' => 1090,
'source' => 'bank-monthly',
], 'business_mirror');
} finally {
@unlink($path);
}
}
/**
* @param list<string> $headers
*/