feat(账户总览): 接入银企直联期末余额 #1285
48
app/Console/Commands/ImportBankDirectBalances.php
Normal file
48
app/Console/Commands/ImportBankDirectBalances.php
Normal file
@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\BankDirectBalanceWorkbookImporter;
|
||||
use Throwable;
|
||||
|
||||
class ImportBankDirectBalances extends Command
|
||||
{
|
||||
protected $signature = 'finance-ledger:import-bank-direct-balances
|
||||
{path : 银企直联余额 XLSX/XLS 文件}
|
||||
{--balance-date= : 指定余额日期,格式 YYYY-MM-DD}
|
||||
{--dry-run : 只校验和统计,不写入共享业务库}';
|
||||
|
||||
protected $description = '导入银企直联账户可用余额及期末余额快照';
|
||||
|
||||
public function handle(BankDirectBalanceWorkbookImporter $importer): int
|
||||
{
|
||||
try {
|
||||
$result = $importer->import(
|
||||
(string) $this->argument('path'),
|
||||
$this->option('balance-date') === null
|
||||
? null
|
||||
: (string) $this->option('balance-date'),
|
||||
(bool) $this->option('dry-run'),
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->table(['项目', '值'], [
|
||||
['余额日期', $result['balance_date']],
|
||||
['账户数', $result['total']],
|
||||
['银行数', $result['bank_count']],
|
||||
['可用余额合计', number_format($result['available_total'], 2, '.', '')],
|
||||
['替换原快照', $result['replaced']],
|
||||
['模式', $result['dry_run'] ? '校验' : '写入'],
|
||||
]);
|
||||
$this->info($result['dry_run']
|
||||
? '银企直联余额校验完成,未写入共享业务库。'
|
||||
: '银企直联余额导入完成,期末余额已接入账户总览。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$schema = Schema::connection($this->connection());
|
||||
|
||||
if ($schema->hasTable('fin_bank_direct_balance_snapshots')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$schema->create('fin_bank_direct_balance_snapshots', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('finance_account_id');
|
||||
$table->string('bank_name', 100);
|
||||
$table->string('account_no', 64);
|
||||
$table->string('account_name', 255)->nullable();
|
||||
$table->string('account_short', 100);
|
||||
$table->string('company_name', 255)->nullable();
|
||||
$table->string('currency', 32)->default('人民币');
|
||||
$table->decimal('account_balance', 20, 6)->nullable();
|
||||
$table->decimal('available_balance', 20, 6);
|
||||
$table->date('balance_date');
|
||||
$table->dateTime('balance_at', 6);
|
||||
$table->string('source', 32)->default('bank-direct');
|
||||
$table->string('source_file_name', 255);
|
||||
$table->char('source_sha256', 64);
|
||||
$table->dateTime('imported_at', 6);
|
||||
$table->timestamps(6);
|
||||
|
||||
$table->unique(
|
||||
['finance_account_id', 'balance_date', 'source'],
|
||||
'fin_bank_direct_account_date_source_unique',
|
||||
);
|
||||
$table->index(
|
||||
['finance_account_id', 'balance_date'],
|
||||
'fin_bank_direct_account_date_index',
|
||||
);
|
||||
$table->index(
|
||||
['bank_name', 'balance_date'],
|
||||
'fin_bank_direct_bank_date_index',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::connection($this->connection())->dropIfExists('fin_bank_direct_balance_snapshots');
|
||||
}
|
||||
|
||||
private function connection(): string
|
||||
{
|
||||
return (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
}
|
||||
};
|
||||
@ -18,6 +18,7 @@
|
||||
"business-mirror:import-kuka-posting-material-source",
|
||||
"business-mirror:import-kuka-posting-quotation",
|
||||
"finance-ledger:import-company-alipay",
|
||||
"finance-ledger:import-bank-direct-balances",
|
||||
"finance-ledger:import-wangshang-bank",
|
||||
"finance-ledger:import-base",
|
||||
"finance-ledger:import-snapshot",
|
||||
|
||||
@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Repositories;
|
||||
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
|
||||
final class BankDirectBalanceRepository
|
||||
{
|
||||
public const TABLE = 'fin_bank_direct_balance_snapshots';
|
||||
|
||||
public const SOURCE = 'bank-direct';
|
||||
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct(DatabaseManager $database)
|
||||
{
|
||||
$this->connection = $database->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $accountIds
|
||||
* @return array<int,array{available_balance:float,balance_date:string,balance_at:string}>
|
||||
*/
|
||||
public function latestForAccounts(array $accountIds, string $periodTo): array
|
||||
{
|
||||
$accountIds = array_values(array_unique(array_filter(
|
||||
array_map(static fn (mixed $id): int => (int) $id, $accountIds),
|
||||
static fn (int $id): bool => $id > 0,
|
||||
)));
|
||||
if ($accountIds === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = $this->connection->table(self::TABLE)
|
||||
->whereIn('finance_account_id', $accountIds)
|
||||
->where('balance_date', '<=', $periodTo)
|
||||
->orderBy('finance_account_id')
|
||||
->orderBy('balance_date')
|
||||
->orderBy('balance_at')
|
||||
->orderBy('id')
|
||||
->get([
|
||||
'finance_account_id',
|
||||
'available_balance',
|
||||
'balance_date',
|
||||
'balance_at',
|
||||
]);
|
||||
|
||||
$latest = [];
|
||||
foreach ($rows as $row) {
|
||||
$latest[(int) $row->finance_account_id] = [
|
||||
'available_balance' => round((float) $row->available_balance, 2),
|
||||
'balance_date' => substr((string) $row->balance_date, 0, 10),
|
||||
'balance_at' => (string) $row->balance_at,
|
||||
];
|
||||
}
|
||||
|
||||
return $latest;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,469 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
@ -10,6 +10,7 @@ use App\Utilities\FinanceLedgerIndependentAccounts;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\EcommerceFinance\Repositories\BankDirectBalanceRepository;
|
||||
|
||||
final class NonStoreAccountMonitorPageData
|
||||
{
|
||||
@ -86,6 +87,11 @@ final class NonStoreAccountMonitorPageData
|
||||
'remark',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly BankDirectBalanceRepository $bankDirectBalances,
|
||||
) {
|
||||
}
|
||||
|
||||
public function page(): array
|
||||
{
|
||||
$period = $this->period();
|
||||
@ -1125,8 +1131,23 @@ final class NonStoreAccountMonitorPageData
|
||||
];
|
||||
}
|
||||
|
||||
$directAccountIds = array_values(array_unique(array_map(
|
||||
static fn (array $row): int => (int) $row['id'],
|
||||
array_filter($rows, static fn (array $row): bool => (bool) ($row['is_direct'] ?? false)),
|
||||
)));
|
||||
$bankDirectBalances = $this->bankDirectBalances->latestForAccounts(
|
||||
$directAccountIds,
|
||||
$period['to'],
|
||||
);
|
||||
|
||||
foreach ($rows as &$row) {
|
||||
$row = array_merge($row, $metrics[$row['account_short']] ?? []);
|
||||
$snapshot = $bankDirectBalances[(int) $row['id']] ?? null;
|
||||
if (($row['is_direct'] ?? false) && $snapshot !== null) {
|
||||
$row['closing_balance'] = $snapshot['available_balance'];
|
||||
$row['bank_direct_balance_date'] = $snapshot['balance_date'];
|
||||
$row['bank_direct_balance_at'] = $snapshot['balance_at'];
|
||||
}
|
||||
}
|
||||
unset($row);
|
||||
}
|
||||
|
||||
@ -522,6 +522,53 @@ class NonStoreAccountMonitorTest extends FeatureTestCase
|
||||
$this->assertStringNotContainsString('95,000.00', $firstDayHtml);
|
||||
}
|
||||
|
||||
public function test_bank_direct_available_balance_overrides_closing_balance_up_to_period_end(): void
|
||||
{
|
||||
$connection = DB::connection('business_mirror');
|
||||
$accountId = (int) $connection->table('fin_accounts')
|
||||
->where('account_short', '保留直连工行')
|
||||
->value('id');
|
||||
foreach ([
|
||||
['balance_date' => '2026-11-10', 'balance_at' => '2026-11-10 17:00:00', 'available_balance' => 110000],
|
||||
['balance_date' => '2026-11-19', 'balance_at' => '2026-11-19 17:08:04', 'available_balance' => 123456.78],
|
||||
] as $snapshot) {
|
||||
$connection->table('fin_bank_direct_balance_snapshots')->insert($snapshot + [
|
||||
'finance_account_id' => $accountId,
|
||||
'bank_name' => '华夏银行',
|
||||
'account_no' => '100200300400',
|
||||
'account_name' => '保留直连工行',
|
||||
'account_short' => '保留直连工行',
|
||||
'company_name' => '保留直连公司',
|
||||
'currency' => '人民币',
|
||||
'account_balance' => $snapshot['available_balance'],
|
||||
'source' => 'bank-direct',
|
||||
'source_file_name' => '银行余额.xlsx',
|
||||
'source_sha256' => str_repeat('a', 64),
|
||||
'imported_at' => '2026-11-19 18:00:00',
|
||||
'created_at' => '2026-11-19 18:00:00',
|
||||
'updated_at' => '2026-11-19 18:00:00',
|
||||
]);
|
||||
}
|
||||
|
||||
$beforeLatestSnapshot = $this->loginAs()->get($this->pageUrl([
|
||||
'view' => 'accounts',
|
||||
'keep' => 'retained',
|
||||
'account_category' => 'bank',
|
||||
'period_from' => '2026-11-01',
|
||||
'period_to' => '2026-11-18',
|
||||
]))->assertOk()->getContent();
|
||||
$this->assertStringContainsString('110,000.00', $beforeLatestSnapshot);
|
||||
|
||||
$throughLatestSnapshot = $this->loginAs()->get($this->pageUrl([
|
||||
'view' => 'accounts',
|
||||
'keep' => 'retained',
|
||||
'account_category' => 'bank',
|
||||
'period_from' => '2026-11-01',
|
||||
'period_to' => '2026-11-30',
|
||||
]))->assertOk()->getContent();
|
||||
$this->assertStringContainsString('123,456.78', $throughLatestSnapshot);
|
||||
}
|
||||
|
||||
public function test_unretained_tasks_have_a_standalone_processing_page(): void
|
||||
{
|
||||
$html = $this->loginAs()->get($this->pageUrl([
|
||||
|
||||
@ -0,0 +1,249 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\EcommerceFinance;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Modules\EcommerceFinance\Repositories\BankDirectBalanceRepository;
|
||||
use Modules\EcommerceFinance\Services\BankDirectBalanceWorkbookImporter;
|
||||
use PhpOffice\PhpSpreadsheet\Cell\DataType;
|
||||
use PhpOffice\PhpSpreadsheet\Spreadsheet;
|
||||
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
||||
use Tests\TestCase;
|
||||
|
||||
class BankDirectBalanceWorkbookImporterTest extends TestCase
|
||||
{
|
||||
private string $workbookPath;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
config([
|
||||
'database.connections.business_mirror' => [
|
||||
'driver' => 'sqlite',
|
||||
'database' => ':memory:',
|
||||
'prefix' => '',
|
||||
],
|
||||
'upstream_mirrors.connection' => 'business_mirror',
|
||||
]);
|
||||
DB::purge('business_mirror');
|
||||
|
||||
Schema::connection('business_mirror')->create('fin_accounts', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('account_no')->nullable();
|
||||
$table->string('account_short')->nullable();
|
||||
$table->string('company_name')->nullable();
|
||||
});
|
||||
Schema::connection('business_mirror')->create('fin_flow_summary_account_sources', function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->string('account_short')->unique();
|
||||
$table->string('data_source')->nullable();
|
||||
$table->string('updated_by')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
Schema::connection('business_mirror')->create(BankDirectBalanceRepository::TABLE, function (Blueprint $table): void {
|
||||
$table->id();
|
||||
$table->unsignedBigInteger('finance_account_id');
|
||||
$table->string('bank_name');
|
||||
$table->string('account_no');
|
||||
$table->string('account_name')->nullable();
|
||||
$table->string('account_short');
|
||||
$table->string('company_name')->nullable();
|
||||
$table->string('currency')->default('人民币');
|
||||
$table->decimal('account_balance', 20, 6)->nullable();
|
||||
$table->decimal('available_balance', 20, 6);
|
||||
$table->date('balance_date');
|
||||
$table->dateTime('balance_at');
|
||||
$table->string('source');
|
||||
$table->string('source_file_name');
|
||||
$table->char('source_sha256', 64);
|
||||
$table->dateTime('imported_at');
|
||||
$table->timestamps();
|
||||
$table->unique(['finance_account_id', 'balance_date', 'source']);
|
||||
});
|
||||
|
||||
$this->workbookPath = sys_get_temp_dir() . '/bank-direct-' . uniqid('', true) . '.xlsx';
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
if (isset($this->workbookPath) && is_file($this->workbookPath)) {
|
||||
unlink($this->workbookPath);
|
||||
}
|
||||
DB::purge('business_mirror');
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function testImportsAvailableBalanceByExactBankAccountAndMarksSourceDirect(): void
|
||||
{
|
||||
$firstId = DB::connection('business_mirror')->table('fin_accounts')->insertGetId([
|
||||
'account_no' => '12345678901234567',
|
||||
'account_short' => '华夏基本户',
|
||||
'company_name' => '测试公司甲',
|
||||
]);
|
||||
$secondId = DB::connection('business_mirror')->table('fin_accounts')->insertGetId([
|
||||
'account_no' => '76543210987654321',
|
||||
'account_short' => '华夏一般户',
|
||||
'company_name' => '测试公司乙',
|
||||
]);
|
||||
DB::connection('business_mirror')->table('fin_flow_summary_account_sources')->insert([
|
||||
'account_short' => '华夏基本户',
|
||||
'data_source' => '手动',
|
||||
'updated_by' => '原配置',
|
||||
]);
|
||||
|
||||
$this->writeWorkbook([
|
||||
['1234 5678 9012 34567', '华夏甲账号', '基本户', '测试公司甲', '华夏银行', '人民币', '基本户', 1000.50, 900.25, '2026-11-19 17:08:04'],
|
||||
['76543210987654321', '华夏乙账号', '一般户', '测试公司乙', '华夏银行', '人民币', '一般户', 2000.75, 1500.60, '2026-11-19 17:08:04'],
|
||||
], accountHeader: '');
|
||||
|
||||
$result = app(BankDirectBalanceWorkbookImporter::class)->import(
|
||||
$this->workbookPath,
|
||||
'2026-11-19',
|
||||
);
|
||||
|
||||
$this->assertSame(2, $result['total']);
|
||||
$this->assertSame(0, $result['replaced']);
|
||||
$this->assertSame(2400.85, $result['available_total']);
|
||||
$this->assertDatabaseHas(BankDirectBalanceRepository::TABLE, [
|
||||
'finance_account_id' => $firstId,
|
||||
'account_short' => '华夏基本户',
|
||||
'available_balance' => 900.25,
|
||||
'balance_date' => '2026-11-19',
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas(BankDirectBalanceRepository::TABLE, [
|
||||
'finance_account_id' => $secondId,
|
||||
'account_short' => '华夏一般户',
|
||||
'available_balance' => 1500.60,
|
||||
'balance_date' => '2026-11-19',
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('fin_flow_summary_account_sources', [
|
||||
'account_short' => '华夏基本户',
|
||||
'data_source' => '银企直连',
|
||||
], 'business_mirror');
|
||||
$this->assertDatabaseHas('fin_flow_summary_account_sources', [
|
||||
'account_short' => '华夏一般户',
|
||||
'data_source' => '银企直连',
|
||||
], 'business_mirror');
|
||||
}
|
||||
|
||||
public function testReimportAtomicallyReplacesTheSameBankAndDate(): void
|
||||
{
|
||||
$accountId = DB::connection('business_mirror')->table('fin_accounts')->insertGetId([
|
||||
'account_no' => '12345678901234567',
|
||||
'account_short' => '华夏基本户',
|
||||
'company_name' => '测试公司甲',
|
||||
]);
|
||||
$this->writeWorkbook([
|
||||
['12345678901234567', '华夏账号', '基本户', '测试公司甲', '华夏银行', '人民币', '基本户', 1000, 900, '2026-11-19 16:00:00'],
|
||||
]);
|
||||
$importer = app(BankDirectBalanceWorkbookImporter::class);
|
||||
$importer->import($this->workbookPath, '2026-11-19');
|
||||
|
||||
$this->writeWorkbook([
|
||||
['12345678901234567', '华夏账号', '基本户', '测试公司甲', '华夏银行', '人民币', '基本户', 1100, 950.88, '2026-11-19 18:00:00'],
|
||||
], overwrite: false);
|
||||
$result = $importer->import($this->workbookPath, '2026-11-19');
|
||||
|
||||
$this->assertSame(1, $result['replaced']);
|
||||
$this->assertSame(1, DB::connection('business_mirror')->table(BankDirectBalanceRepository::TABLE)
|
||||
->where('finance_account_id', $accountId)
|
||||
->where('balance_date', '2026-11-19')
|
||||
->count());
|
||||
$this->assertDatabaseHas(BankDirectBalanceRepository::TABLE, [
|
||||
'finance_account_id' => $accountId,
|
||||
'available_balance' => 950.88,
|
||||
'balance_at' => '2026-11-19 18:00:00',
|
||||
], 'business_mirror');
|
||||
}
|
||||
|
||||
public function testUnmatchedAccountKeepsExistingSnapshotsAndSourcesUntouched(): void
|
||||
{
|
||||
DB::connection('business_mirror')->table('fin_accounts')->insert([
|
||||
'account_no' => '12345678901234567',
|
||||
'account_short' => '华夏基本户',
|
||||
'company_name' => '测试公司甲',
|
||||
]);
|
||||
DB::connection('business_mirror')->table('fin_flow_summary_account_sources')->insert([
|
||||
'account_short' => '华夏基本户',
|
||||
'data_source' => '手动',
|
||||
'updated_by' => '原配置',
|
||||
]);
|
||||
$this->writeWorkbook([
|
||||
['99999999999999999', '未知账号', '未知户', '测试公司甲', '华夏银行', '人民币', '基本户', 1000, 900, '2026-11-19 17:08:04'],
|
||||
]);
|
||||
|
||||
try {
|
||||
app(BankDirectBalanceWorkbookImporter::class)->import($this->workbookPath);
|
||||
$this->fail('未匹配账号应阻止导入。');
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
$this->assertStringContainsString('未匹配 1 个银行账号', $exception->getMessage());
|
||||
}
|
||||
|
||||
$this->assertDatabaseCount(BankDirectBalanceRepository::TABLE, 0, 'business_mirror');
|
||||
$this->assertDatabaseHas('fin_flow_summary_account_sources', [
|
||||
'account_short' => '华夏基本户',
|
||||
'data_source' => '手动',
|
||||
'updated_by' => '原配置',
|
||||
], 'business_mirror');
|
||||
}
|
||||
|
||||
public function testDryRunValidatesWithoutWriting(): void
|
||||
{
|
||||
DB::connection('business_mirror')->table('fin_accounts')->insert([
|
||||
'account_no' => '12345678901234567',
|
||||
'account_short' => '华夏基本户',
|
||||
'company_name' => '测试公司甲',
|
||||
]);
|
||||
$this->writeWorkbook([
|
||||
['12345678901234567', '华夏账号', '基本户', '测试公司甲', '华夏银行', '人民币', '基本户', 1000, 900, '2026-11-19 17:08:04'],
|
||||
]);
|
||||
|
||||
$result = app(BankDirectBalanceWorkbookImporter::class)->import(
|
||||
$this->workbookPath,
|
||||
null,
|
||||
true,
|
||||
);
|
||||
|
||||
$this->assertTrue($result['dry_run']);
|
||||
$this->assertSame('2026-11-19', $result['balance_date']);
|
||||
$this->assertDatabaseCount(BankDirectBalanceRepository::TABLE, 0, 'business_mirror');
|
||||
$this->assertDatabaseCount('fin_flow_summary_account_sources', 0, 'business_mirror');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array<int,mixed>> $rows
|
||||
*/
|
||||
private function writeWorkbook(array $rows, string $accountHeader = '银行账号', bool $overwrite = true): void
|
||||
{
|
||||
if (! $overwrite && is_file($this->workbookPath)) {
|
||||
unlink($this->workbookPath);
|
||||
}
|
||||
|
||||
$spreadsheet = new Spreadsheet();
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
$sheet->setTitle('sheet1');
|
||||
$sheet->fromArray([[
|
||||
$accountHeader,
|
||||
'账户名称',
|
||||
'账户别名',
|
||||
'所属企业',
|
||||
'所属银行',
|
||||
'币种',
|
||||
'账户类型',
|
||||
'账户余额',
|
||||
'可用余额',
|
||||
'余额更新日期',
|
||||
], ...$rows]);
|
||||
foreach ($rows as $index => $row) {
|
||||
$sheet->getCell('A' . ($index + 2))->setValueExplicit(
|
||||
(string) $row[0],
|
||||
DataType::TYPE_STRING,
|
||||
);
|
||||
}
|
||||
(new Xlsx($spreadsheet))->save($this->workbookPath);
|
||||
$spreadsheet->disconnectWorksheets();
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user