From 02d298a6723f2576af74719c9a74af2b6d86a3b6 Mon Sep 17 00:00:00 2001 From: shanshi <3316401569@qq.com> Date: Wed, 25 Nov 2026 11:52:05 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E8=B4=A2=E5=8A=A1=E5=8F=B0=E8=B4=A6):=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E9=93=B6=E8=A1=8C=E4=BD=99=E9=A2=9D=E9=A1=B5?= =?UTF-8?q?=E4=B8=8E=E7=9B=B4=E8=BF=9E=E4=BD=99=E9=A2=9D=E6=BB=9A=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/Business/FinanceLedger.php | 30 + app/Http/Controllers/Business/Pages.php | 12 + app/Utilities/FinanceLedgerAccess.php | 30 + .../FinanceLedgerBankDirectAccounts.php | 62 ++ config/finance_ledger.php | 4 + ...edger_bank_balance_current_adjustments.php | 35 + ...anceLedgerBankBalanceCurrentCalculator.php | 170 ++++ .../FinanceLedgerBankBalanceCurrentEditor.php | 146 +++ .../Services/FinanceLedgerCalculator.php | 48 +- .../View/FinanceLedgerPageData.php | 332 ++++++- .../View/NonStoreAccountMonitorPageData.php | 50 + .../pages/financial-ledger/ledger.blade.php | 130 ++- .../partials/bank-balance-panel.blade.php | 912 ++++++++++++++++++ routes/admin.php | 4 + .../Business/FinanceLedgerNavigationTest.php | 444 ++++++++- .../Business/NonStoreAccountMonitorTest.php | 125 +++ 16 files changed, 2461 insertions(+), 73 deletions(-) create mode 100644 app/Utilities/FinanceLedgerBankDirectAccounts.php create mode 100644 database/migrations/2026_11_25_120000_create_finance_ledger_bank_balance_current_adjustments.php create mode 100644 modules/EcommerceFinance/Services/FinanceLedgerBankBalanceCurrentCalculator.php create mode 100644 modules/EcommerceFinance/Services/FinanceLedgerBankBalanceCurrentEditor.php create mode 100644 resources/views/business/pages/financial-ledger/partials/bank-balance-panel.blade.php diff --git a/app/Http/Controllers/Business/FinanceLedger.php b/app/Http/Controllers/Business/FinanceLedger.php index 40c3090e..3c9b4268 100644 --- a/app/Http/Controllers/Business/FinanceLedger.php +++ b/app/Http/Controllers/Business/FinanceLedger.php @@ -24,6 +24,7 @@ use Modules\EcommerceFinance\Services\FinanceLedgerAccountCreator; use Modules\EcommerceFinance\Services\FinanceLedgerAccountEditor; use Modules\EcommerceFinance\Services\FinanceLedgerAccountTemplate; use Modules\EcommerceFinance\Services\FinanceLedgerAlipayBasicImporter; +use Modules\EcommerceFinance\Services\FinanceLedgerBankBalanceCurrentEditor; use Modules\EcommerceFinance\Services\FinanceLedgerCalculator; use Modules\EcommerceFinance\Services\FinanceLedgerFlowEditor; use Modules\EcommerceFinance\Services\FinanceLedgerFlowSummaryEditor; @@ -84,6 +85,35 @@ class FinanceLedger extends Controller return response()->json($bankBills->filterOptions((string) $data['column_key'])); } + public function updateBankBalanceCurrent( + Request $request, + FinanceLedgerBankBalanceCurrentEditor $editor, + ): JsonResponse { + abort_unless( + FinanceLedgerAccess::canEditBankBalance(user()), + 403, + '当前账号没有修改银行余额的权限。', + ); + + $data = $request->validate([ + 'account_short' => ['required', 'string', 'max:100'], + 'current_balance' => [ + 'required', + 'numeric', + 'between:-9999999999999999.99,9999999999999999.99', + ], + ]); + + return response()->json([ + 'ok' => true, + 'message' => '当前余额已保存,仅用于银行余额页。', + ...$editor->save( + (string) $data['account_short'], + round((float) $data['current_balance'], 2), + ), + ], 200, ['Cache-Control' => 'private, no-store']); + } + public function accountBasicPage(FinanceLedgerPageData $pageData, string $view): View { $definition = FinanceLedgerPageData::ACCOUNT_TYPE_VIEWS[$view] ?? null; diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 7c8d929a..35a94063 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -1029,6 +1029,18 @@ class Pages extends Controller ); } + if ($section === 'financial-operations' + && $page === 'fund-ledger' + && request()->boolean('ledger_bank_balance_partial')) { + $bankBalancePage = app(\Modules\EcommerceFinance\View\FinanceLedgerPageData::class) + ->bankBalancePage(); + + return response()->view( + 'business.pages.financial-ledger.partials.bank-balance-panel', + ['ledgerBankBalancePage' => $bankBalancePage], + ); + } + if ($section === 'financial-operations' && $page === 'ledger' && in_array($tab ?? request('tab'), ['transactions'], true)) { diff --git a/app/Utilities/FinanceLedgerAccess.php b/app/Utilities/FinanceLedgerAccess.php index f04e9052..91a5547b 100644 --- a/app/Utilities/FinanceLedgerAccess.php +++ b/app/Utilities/FinanceLedgerAccess.php @@ -68,4 +68,34 @@ class FinanceLedgerAccess return in_array(trim((string) $user->name), $userNames, true); } + + /** + * 银行余额页当前余额维护权限:财务台账管理员、出纳角色或指定账号。 + */ + public static function canEditBankBalance(?User $user = null): bool + { + if (self::canEditMapping($user)) { + return true; + } + + $user ??= user(); + if (! $user) { + return false; + } + + $roles = array_values(array_filter(array_map( + 'trim', + explode(',', (string) config('finance_ledger.bank_balance_editor_roles', '出纳')), + ))); + if (in_array(SystemAccess::roleName($user), $roles, true)) { + return true; + } + + $userNames = array_values(array_filter(array_map( + 'trim', + explode(',', (string) config('finance_ledger.bank_balance_editor_user_names', '')), + ))); + + return in_array(trim((string) $user->name), $userNames, true); + } } diff --git a/app/Utilities/FinanceLedgerBankDirectAccounts.php b/app/Utilities/FinanceLedgerBankDirectAccounts.php new file mode 100644 index 00000000..df15748b --- /dev/null +++ b/app/Utilities/FinanceLedgerBankDirectAccounts.php @@ -0,0 +1,62 @@ + */ + public static function map(ConnectionInterface $connection): array + { + $accounts = $connection->table('fin_accounts') + ->whereNotNull('account_short') + ->where('account_short', '<>', '') + ->orderBy('id') + ->get(['account_short', 'account_type', 'bank_name']); + if ($accounts->isEmpty()) { + return []; + } + + $accountShorts = $accounts->pluck('account_short')->unique()->values()->all(); + $typeOverrides = $connection->getSchemaBuilder()->hasTable('fin_account_type_overrides') + ? $connection->table('fin_account_type_overrides') + ->whereIn('account_short', $accountShorts) + ->pluck('account_type', 'account_short') + : collect(); + $sources = $connection->getSchemaBuilder()->hasTable('fin_flow_summary_account_sources') + ? $connection->table('fin_flow_summary_account_sources') + ->whereIn('account_short', $accountShorts) + ->pluck('data_source', 'account_short') + : collect(); + + $direct = []; + foreach ($accounts as $account) { + $accountShort = trim((string) $account->account_short); + $accountType = trim((string) ( + $typeOverrides[$accountShort] + ?? $account->account_type + ?? '' + )); + if ($accountShort === '' || $accountType === '个人卡') { + continue; + } + + if (FinanceLedgerFlowSummaryDataSource::normalize($sources[$accountShort] ?? null) + === FinanceLedgerFlowSummaryDataSource::DIRECT) { + $direct[$accountShort] = true; + continue; + } + + $bank = trim((string) ($account->bank_name ?? '')); + if (str_contains($accountShort, '招商') + || str_contains($accountShort, '招行') + || str_contains($bank, '招商') + || str_contains($bank, '招行')) { + $direct[$accountShort] = true; + } + } + + return $direct; + } +} diff --git a/config/finance_ledger.php b/config/finance_ledger.php index 792a785c..08215f5a 100644 --- a/config/finance_ledger.php +++ b/config/finance_ledger.php @@ -21,6 +21,10 @@ return [ // 额外允许维护动账明细的账号;不授予账户、资金流水或映射管理权限。 'transaction_editor_user_names' => env('FINANCE_LEDGER_TRANSACTION_EDITOR_USER_NAMES', '玉兔'), + // 银行余额页“当前余额”校正权限;校正结果只用于该页,不回写账户资金管理。 + 'bank_balance_editor_roles' => env('FINANCE_LEDGER_BANK_BALANCE_EDITOR_ROLES', '出纳'), + 'bank_balance_editor_user_names' => env('FINANCE_LEDGER_BANK_BALANCE_EDITOR_USER_NAMES', ''), + // 账户异常待办开始超过该天数仍未完成时进入逾期预警。 'account_todo_overdue_days' => (int) env('FINANCE_LEDGER_ACCOUNT_TODO_OVERDUE_DAYS', 7), diff --git a/database/migrations/2026_11_25_120000_create_finance_ledger_bank_balance_current_adjustments.php b/database/migrations/2026_11_25_120000_create_finance_ledger_bank_balance_current_adjustments.php new file mode 100644 index 00000000..84fd9714 --- /dev/null +++ b/database/migrations/2026_11_25_120000_create_finance_ledger_bank_balance_current_adjustments.php @@ -0,0 +1,35 @@ +connection()); + if ($schema->hasTable('fin_bank_balance_current_adjustments')) { + return; + } + + $schema->create('fin_bank_balance_current_adjustments', function (Blueprint $table): void { + $table->id(); + $table->string('account_short', 100)->unique('fin_bank_balance_current_adjustment_account'); + $table->decimal('adjustment_amount', 18, 2)->default(0); + $table->string('updated_by', 100)->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::connection($this->connection()) + ->dropIfExists('fin_bank_balance_current_adjustments'); + } +}; diff --git a/modules/EcommerceFinance/Services/FinanceLedgerBankBalanceCurrentCalculator.php b/modules/EcommerceFinance/Services/FinanceLedgerBankBalanceCurrentCalculator.php new file mode 100644 index 00000000..dd58c10a --- /dev/null +++ b/modules/EcommerceFinance/Services/FinanceLedgerBankBalanceCurrentCalculator.php @@ -0,0 +1,170 @@ +connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * 按账户期初和未删除动账明细计算滚动余额。 + * 该计算不读取 fin_accounts.current_balance 或 fin_daily_flows。 + * + * @param list $accountShorts + * @return array + */ + public function balances(array $accountShorts, ?string $asOf = null): array + { + $accountShorts = $this->normalizeAccountShorts($accountShorts); + if ($accountShorts === []) { + return []; + } + + $openingDate = (string) config('finance_ledger.opening_date', '2026-10-17'); + $openingRows = $this->connection->table('fin_account_opening') + ->whereIn('account_short', $accountShorts) + ->orderBy('opening_date') + ->orderBy('id') + ->get(['account_short', 'opening_date', 'opening_balance']) + ->groupBy('account_short') + ->map(static fn ($rows) => $rows->last()); + $mappings = $this->connection->table('fin_account_map') + ->whereIn('account_short', $accountShorts) + ->get(['source', 'source_value', 'account_short']); + $mappingByKey = $mappings->keyBy( + static fn (object $row): string => (string) $row->source . "\0" . (string) $row->source_value, + ); + $balances = []; + $starts = []; + foreach ($accountShorts as $accountShort) { + $opening = $openingRows->get($accountShort); + $balances[$accountShort] = round((float) ($opening->opening_balance ?? 0), 2); + $starts[$accountShort] = $opening !== null + ? substr((string) $opening->opening_date, 0, 10) + : $openingDate; + } + $earliestStart = min($starts); + + $transactionQuery = $this->connection->table('fin_transactions') + ->whereNull('deleted_at') + ->where('txn_date', '>=', $earliestStart) + ->where(function ($query) use ($accountShorts, $mappings): void { + $query->whereIn('account_short', $accountShorts); + foreach ($mappings as $mapping) { + $query->orWhere(function ($pair) use ($mapping): void { + $pair->where('source', (string) $mapping->source) + ->where('source_value', (string) $mapping->source_value); + }); + } + }); + if ($asOf !== null && preg_match('/^\d{4}-\d{2}-\d{2}$/', $asOf) === 1) { + $transactionQuery->whereDate('txn_date', '<=', $asOf); + } + $transactions = $transactionQuery + ->orderBy('txn_date') + ->orderBy('id') + ->get(['txn_date', 'account_short', 'source', 'source_value', 'income', 'expense']); + + foreach ($transactions as $transaction) { + $mappingKey = (string) $transaction->source . "\0" . (string) $transaction->source_value; + $accountShort = (string) ( + $mappingByKey->get($mappingKey)?->account_short + ?? $transaction->account_short + ?? '' + ); + if (! array_key_exists($accountShort, $balances)) { + continue; + } + $date = substr((string) $transaction->txn_date, 0, 10); + if ($date < $starts[$accountShort]) { + continue; + } + + $balances[$accountShort] = round( + $balances[$accountShort] + + (float) $transaction->income + - (float) $transaction->expense, + 2, + ); + } + + return $balances; + } + + /** + * 计算指定日期的净动账。 + * + * @param list $accountShorts + * @return array + */ + public function movementsOnDate(array $accountShorts, string $date): array + { + $accountShorts = $this->normalizeAccountShorts($accountShorts); + if ($accountShorts === [] || preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) !== 1) { + return []; + } + + $mappings = $this->connection->table('fin_account_map') + ->whereIn('account_short', $accountShorts) + ->get(['source', 'source_value', 'account_short']); + $mappingByKey = $mappings->keyBy( + static fn (object $row): string => (string) $row->source . "\0" . (string) $row->source_value, + ); + $transactionQuery = $this->connection->table('fin_transactions') + ->whereNull('deleted_at') + ->where('txn_date', $date) + ->where(function ($query) use ($accountShorts, $mappings): void { + $query->whereIn('account_short', $accountShorts); + foreach ($mappings as $mapping) { + $query->orWhere(function ($pair) use ($mapping): void { + $pair->where('source', (string) $mapping->source) + ->where('source_value', (string) $mapping->source_value); + }); + } + }); + $transactions = $transactionQuery + ->orderBy('txn_date') + ->orderBy('id') + ->get(['txn_date', 'account_short', 'source', 'source_value', 'income', 'expense']); + + $movements = array_fill_keys($accountShorts, 0.0); + foreach ($transactions as $transaction) { + $mappingKey = (string) $transaction->source . "\0" . (string) $transaction->source_value; + $accountShort = (string) ( + $mappingByKey->get($mappingKey)?->account_short + ?? $transaction->account_short + ?? '' + ); + if (! array_key_exists($accountShort, $movements)) { + continue; + } + $movements[$accountShort] = round( + $movements[$accountShort] + + (float) $transaction->income + - (float) $transaction->expense, + 2, + ); + } + + return $movements; + } + + /** @return list */ + private function normalizeAccountShorts(array $accountShorts): array + { + return array_values(array_unique(array_filter(array_map( + static fn (mixed $accountShort): string => trim((string) $accountShort), + $accountShorts, + )))); + } +} diff --git a/modules/EcommerceFinance/Services/FinanceLedgerBankBalanceCurrentEditor.php b/modules/EcommerceFinance/Services/FinanceLedgerBankBalanceCurrentEditor.php new file mode 100644 index 00000000..55cceb71 --- /dev/null +++ b/modules/EcommerceFinance/Services/FinanceLedgerBankBalanceCurrentEditor.php @@ -0,0 +1,146 @@ +connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** @return array */ + public function adjustments(array $accountShorts): array + { + $accountShorts = array_values(array_unique(array_filter(array_map( + static fn (mixed $accountShort): string => trim((string) $accountShort), + $accountShorts, + )))); + if ($accountShorts === [] || ! $this->connection->getSchemaBuilder() + ->hasTable('fin_bank_balance_current_adjustments')) { + return []; + } + + return $this->connection->table('fin_bank_balance_current_adjustments') + ->whereIn('account_short', $accountShorts) + ->pluck('adjustment_amount', 'account_short') + ->map(static fn (mixed $amount): float => round((float) $amount, 2)) + ->all(); + } + + /** + * @return array{ + * account_short:string, + * current_balance:float, + * base_balance:float, + * adjustment_amount:float, + * is_direct:bool + * } + */ + public function save(string $accountShort, float $currentBalance): array + { + $accountShort = trim($accountShort); + if ($accountShort === '' || ! $this->connection->table('fin_accounts') + ->where('account_short', $accountShort) + ->exists()) { + throw new NotFoundHttpException('银行账户不存在。'); + } + if (FinanceLedgerIndependentAccounts::contains($accountShort)) { + throw ValidationException::withMessages([ + 'account_short' => '独立账单账户不参与银行余额调整。', + ]); + } + + $isDirect = isset(FinanceLedgerBankDirectAccounts::map($this->connection)[$accountShort]); + $baseBalance = $this->baseBalance($accountShort, $isDirect); + $adjustment = round($currentBalance - $baseBalance, 2); + + $this->connection->transaction(function () use ( + $accountShort, + $currentBalance, + $baseBalance, + $adjustment, + $isDirect, + ): void { + $now = now(); + $before = $this->connection->table('fin_bank_balance_current_adjustments') + ->where('account_short', $accountShort) + ->first(); + $values = [ + 'adjustment_amount' => $adjustment, + 'updated_by' => (string) (user()?->name ?? ''), + 'updated_at' => $now, + ]; + if ($before === null) { + $this->connection->table('fin_bank_balance_current_adjustments')->insert([ + 'account_short' => $accountShort, + ...$values, + 'created_at' => $now, + ]); + } else { + $this->connection->table('fin_bank_balance_current_adjustments') + ->where('account_short', $accountShort) + ->update($values); + } + + $this->connection->table('fin_ledger_edit_events')->insert([ + 'entity_type' => 'bank_balance_update', + 'entity_key' => 'account|' . $accountShort, + 'changes' => json_encode([ + 'base_balance' => $baseBalance, + 'current_balance' => $currentBalance, + 'adjustment_amount' => $adjustment, + 'is_direct' => $isDirect, + ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'user_id' => user()?->id, + 'user_name' => (string) (user()?->name ?? ''), + 'created_at' => $now, + ]); + + }); + + return [ + 'account_short' => $accountShort, + 'current_balance' => round($currentBalance, 2), + 'base_balance' => $baseBalance, + 'adjustment_amount' => $adjustment, + 'is_direct' => $isDirect, + ]; + } + + private function baseBalance(string $accountShort, bool $isDirect): float + { + $row = collect($this->accountMonitor->page()['fundOverview']['bank_accounts'] ?? []) + ->first(static fn (array $account): bool => (string) ($account['account_short'] ?? '') === $accountShort); + if ($row === null) { + throw new NotFoundHttpException('银行余额账户不存在。'); + } + + if (! $isDirect) { + return round((float) ($row['current_balance'] ?? 0), 2); + } + + $directBalance = round((float) ($row['current_balance'] ?? 0), 2); + $movement = (float) ($this->currentCalculator->movementsOnDate( + [$accountShort], + now()->toDateString(), + )[$accountShort] ?? 0); + + return round($directBalance + $movement, 2); + } +} diff --git a/modules/EcommerceFinance/Services/FinanceLedgerCalculator.php b/modules/EcommerceFinance/Services/FinanceLedgerCalculator.php index 445a1952..df453b5d 100644 --- a/modules/EcommerceFinance/Services/FinanceLedgerCalculator.php +++ b/modules/EcommerceFinance/Services/FinanceLedgerCalculator.php @@ -3,7 +3,7 @@ namespace Modules\EcommerceFinance\Services; use App\Utilities\FinanceLedgerAccountStatus; -use App\Utilities\FinanceLedgerFlowSummaryDataSource; +use App\Utilities\FinanceLedgerBankDirectAccounts; use App\Utilities\FinanceLedgerIndependentAccounts; use Illuminate\Support\Facades\DB; @@ -32,7 +32,6 @@ class FinanceLedgerCalculator ->groupBy('account_short') ->map(static fn ($rows) => $rows->last()); $directAccountShorts = $this->directAccountShorts($connection); - $accountCompanies = FinanceLedgerIndependentAccounts::exclude( $connection->table('fin_accounts'), ) @@ -353,50 +352,7 @@ class FinanceLedgerCalculator */ private function directAccountShorts($connection): array { - $schema = $connection->getSchemaBuilder(); - $accountShorts = []; - if ($schema->hasTable('fin_flow_summary_account_sources')) { - $accountShorts = $connection->table('fin_flow_summary_account_sources') - ->where('data_source', FinanceLedgerFlowSummaryDataSource::DIRECT) - ->pluck('account_short') - ->all(); - } - - // 招商银行默认按银企直连处理;网商银行余额由网商账单同步。 - if ($schema->hasTable('fin_accounts') - && $schema->hasColumn('fin_accounts', 'account_type') - && $schema->hasColumn('fin_accounts', 'bank_name')) { - $bankSyncedAccounts = $connection->table('fin_accounts') - ->whereNotNull('account_short') - ->where('account_short', '<>', '') - ->where(function ($query): void { - $query->where('account_type', '网商银行') - ->orWhere('account_short', 'like', '%网商%') - ->orWhere('bank_name', 'like', '%网商%') - ->orWhere(function ($merchant): void { - $merchant - ->where(function ($type): void { - $type->whereNull('account_type') - ->orWhere('account_type', '<>', '个人卡'); - }) - ->where(function ($bank): void { - $bank->where('account_short', 'like', '%招行%') - ->orWhere('account_short', 'like', '%招商%') - ->orWhere('bank_name', 'like', '%招商%'); - }); - }); - }) - ->pluck('account_short') - ->all(); - $accountShorts = [...$accountShorts, ...$bankSyncedAccounts]; - } - - $accountShorts = array_values(array_unique(array_filter(array_map( - static fn (mixed $accountShort): string => trim((string) $accountShort), - $accountShorts, - )))); - - return array_fill_keys($accountShorts, true); + return FinanceLedgerBankDirectAccounts::map($connection); } private function updateBalances( diff --git a/modules/EcommerceFinance/View/FinanceLedgerPageData.php b/modules/EcommerceFinance/View/FinanceLedgerPageData.php index 8d28ddae..86e069bc 100644 --- a/modules/EcommerceFinance/View/FinanceLedgerPageData.php +++ b/modules/EcommerceFinance/View/FinanceLedgerPageData.php @@ -17,6 +17,8 @@ use Illuminate\Pagination\Paginator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository; +use Modules\EcommerceFinance\Services\FinanceLedgerBankBalanceCurrentCalculator; +use Modules\EcommerceFinance\Services\FinanceLedgerBankBalanceCurrentEditor; use Modules\EcommerceFinance\Services\FinanceLedgerShopDirectory; use Modules\EcommerceFinance\Services\FinanceLedgerTransactionWriter; use Modules\EcommerceFinance\Services\StoreReceivingBillBalanceSnapshotSynchronizer; @@ -48,6 +50,7 @@ class FinanceLedgerPageData ]; public const FUND_LEDGER_TABS = [ + 'bank_balance' => ['title' => '银行余额', 'icon' => 'account_balance'], 'transactions' => ['title' => '动账明细', 'icon' => 'receipt_long'], ]; @@ -148,6 +151,8 @@ class FinanceLedgerPageData private readonly JushuitanShopBalanceRepository $shopBalances, private readonly NonStoreAccountMonitorPageData $nonStoreAccountMonitor, private readonly BankBillPageData $bankBills, + private readonly FinanceLedgerBankBalanceCurrentCalculator $bankBalanceCurrentCalculator, + private readonly FinanceLedgerBankBalanceCurrentEditor $bankBalanceCurrentEditor, ) { } @@ -178,31 +183,77 @@ class FinanceLedgerPageData $transactionPeriod = $this->dateRange('txns'); $mappingPeriod = $this->dateRange('mapping'); $sourcePeriod = $this->dateRange('sources'); - $accountDisplayLabels = $this->accountDisplayLabels(); + $emptyPage = static fn (): LengthAwarePaginator => new LengthAwarePaginator( + [], + 0, + 100, + 1, + ['path' => request()->url(), 'query' => request()->query()], + ); + $isAccountFunds = $pageMode === 'account-funds'; + $accountDisplayLabels = $isAccountFunds ? $this->accountDisplayLabels() : []; - $accounts = $this->accounts($accountView, $accountDisplayLabels); - $shops = $this->shops(); - $availableBreakdown = $this->availableBreakdown($shops); - $flows = $flowView === 'basic' - ? [ - 'rows' => collect(), + $accounts = $isAccountFunds + ? $this->accounts($accountView, $accountDisplayLabels) + : [ + 'rows' => $emptyPage(), + 'summary' => [ + 'count' => 0, + 'unretained' => 0, + 'current_balance' => 0, + 'balance' => 0, + 'blocked' => 0, + ], + ]; + $shops = $isAccountFunds + ? $this->shops() + : [ + 'rows' => $emptyPage(), + 'summary' => [ + 'count' => 0, + 'balance' => 0, + 'alert_count' => 0, + ], + 'balance_date' => null, + 'balance_dates' => [], + ]; + $availableBreakdown = $isAccountFunds ? $this->availableBreakdown($shops) : []; + $flows = $isAccountFunds + ? ($flowView === 'basic' + ? [ + 'rows' => $emptyPage(), + 'summary' => ['count' => 0, 'opening' => 0, 'inflow' => 0, 'outflow' => 0, 'closing' => 0], + 'custom_fields' => [], + ] + : $this->flows($flowPeriod, $flowView, $accountDisplayLabels)) + : [ + 'rows' => $emptyPage(), 'summary' => ['count' => 0, 'opening' => 0, 'inflow' => 0, 'outflow' => 0, 'closing' => 0], 'custom_fields' => [], - ] - : $this->flows($flowPeriod, $flowView, $accountDisplayLabels); - $transactions = $this->transactions($transactionView['account_short'], $transactionPeriod); + ]; + $transactions = $pageMode === 'fund-ledger' + ? $this->transactions($transactionView['account_short'], $transactionPeriod) + : [ + 'rows' => $emptyPage(), + 'summary' => ['count' => 0, 'income' => 0, 'expense' => 0, 'current_balance' => 0], + 'custom_fields' => [], + ]; $transactionViewIsIndependent = (bool) ($transactionView['independent'] ?? false); $transactionViewAccountExists = $transactionViewIsIndependent || $transactionView['account_short'] === null || $this->db()->table('fin_accounts') ->where('account_short', $transactionView['account_short']) ->exists(); - $ledgerOverview = $tab === 'overview' + $overviewData = $pageMode === 'fund-ledger' && $tab === 'bank_balance' ? $this->nonStoreAccountMonitor->page() - : null; + : ($tab === 'overview' ? $this->nonStoreAccountMonitor->page() : null); + $ledgerOverview = $tab === 'overview' ? $overviewData : null; if (is_array($ledgerOverview)) { unset($ledgerOverview['view']); } + $ledgerBankBalancePage = $pageMode === 'fund-ledger' && $tab === 'bank_balance' + ? $this->bankBalancePage($overviewData) + : null; return [ 'view' => 'business.pages.financial-ledger.ledger', @@ -213,15 +264,18 @@ class FinanceLedgerPageData 'ledgerPageMode' => $pageMode, 'ledgerPageTitle' => $pageMode === 'fund-ledger' ? '资金台账' : '账户资金管理', 'ledgerPageDescription' => $pageMode === 'fund-ledger' - ? '集中查看和维护全部动账明细;账户资金、银行账单和店铺台账请从“账户资金管理”进入。' + ? '集中查看银行余额、维护全部动账明细;账户资金、银行账单和店铺台账请从“账户资金管理”进入。' : '统一管理账户档案、银行账单、店铺台账和账户映射;动账明细请从“资金台账”进入。', + 'ledgerBankBalancePage' => $ledgerBankBalancePage, 'ledgerOverview' => $ledgerOverview, - 'ledgerBankBills' => $this->bankBills->page(), + 'ledgerBankBills' => $isAccountFunds ? $this->bankBills->page() : [], 'ledgerOpeningDate' => $openingDate, 'ledgerAccountView' => $accountView, 'ledgerAccounts' => $accounts['rows'], 'ledgerAccountSummary' => $accounts['summary'], - 'ledgerAccountTypeCards' => $flowView === 'basic' ? $this->accountTypeCards() : [], + 'ledgerAccountTypeCards' => $isAccountFunds && $flowView === 'basic' + ? $this->accountTypeCards() + : [], 'ledgerShops' => $shops['rows'], 'ledgerShopSummary' => $shops['summary'], 'ledgerShopBalanceDate' => $shops['balance_date'] ?? null, @@ -241,23 +295,24 @@ class FinanceLedgerPageData 'ledgerTransactionViewAccountExists' => $transactionViewAccountExists, 'ledgerTransactionViewIsIndependent' => $transactionViewIsIndependent, 'ledgerTransactionCustomFields' => $transactions['custom_fields'], - 'ledgerMapping' => $this->mapping($mappingPeriod), + 'ledgerMapping' => $isAccountFunds ? $this->mapping($mappingPeriod) : [], 'ledgerMappingPeriod' => $mappingPeriod, - 'ledgerSourceSummary' => $this->sourceSummary($sourcePeriod), + 'ledgerSourceSummary' => $isAccountFunds ? $this->sourceSummary($sourcePeriod) : [], 'ledgerSourcePeriod' => $sourcePeriod, 'ledgerMeta' => $this->meta($transactionPeriod, $flowPeriod), - 'ledgerAccountOptions' => $this->accountOptions(), + 'ledgerAccountOptions' => $isAccountFunds ? $this->accountOptions() : [], 'ledgerManualTransactionAccountOptions' => $this->manualTransactionAccountOptions(), 'ledgerTransactionAccountHeaderOptions' => $this->transactionAccountHeaderOptions(), 'ledgerTransactionDateHeaderOptions' => $this->transactionDateHeaderOptions(), - 'ledgerAccountFilterOptions' => $this->accountFilterOptions(), - 'ledgerCompanyOptions' => $this->companyOptions(), + 'ledgerAccountFilterOptions' => $isAccountFunds ? $this->accountFilterOptions() : [], + 'ledgerCompanyOptions' => $isAccountFunds ? $this->companyOptions() : [], 'ledgerAccountStatusOptions' => FinanceLedgerAccountStatus::OPTIONS, - 'ledgerAccountPlanOptions' => $this->accountPlanOptions(), + 'ledgerAccountPlanOptions' => $isAccountFunds ? $this->accountPlanOptions() : [], 'ledgerAccountKeepOptions' => FinanceLedgerAccountShouldKeep::OPTIONS, 'ledgerFlowSummaryDataSourceOptions' => FinanceLedgerFlowSummaryDataSource::OPTIONS, 'ledgerCanEditMapping' => FinanceLedgerAccess::canEditMapping(user()), 'ledgerCanEditTransactions' => FinanceLedgerAccess::canEditTransactions(user()), + 'ledgerCanEditBankBalance' => FinanceLedgerAccess::canEditBankBalance(user()), 'ledgerCanEditAccountStatus' => FinanceLedgerAccess::canEditAccountStatus(user()), 'ledgerCanEditAccountType' => FinanceLedgerAccess::canEditAccountType(user()), ]; @@ -408,6 +463,241 @@ class FinanceLedgerPageData return ['rows' => $rows, 'summary' => $summary]; } + /** + * 资金台账“银行余额”页签:展示真实银行账户(含网商银行), + * 当前余额按动账明细滚动,本页校正不参与账户资金管理。 + */ + public function bankBalancePage(?array $overview = null): array + { + $overview ??= $this->nonStoreAccountMonitor->page(); + $bankAccounts = collect($overview['fundOverview']['bank_accounts'] ?? []); + $accountShorts = $bankAccounts + ->pluck('account_short') + ->map(static fn (mixed $accountShort): string => trim((string) $accountShort)) + ->filter() + ->unique() + ->values() + ->all(); + $period = $this->dateRange('period'); + $adjustments = $this->bankBalanceCurrentEditor->adjustments($accountShorts); + $columns = [ + ['key' => 'account_display_short', 'label' => '账户简称', 'type' => 'text'], + ['key' => 'bank_display', 'label' => '所属银行', 'type' => 'text'], + ['key' => 'account_type', 'label' => '账户类型', 'type' => 'text'], + ['key' => 'bank_direct_connection', 'label' => '是否银企直连', 'type' => 'text'], + ['key' => 'bank_direct_balance', 'label' => '银企直连余额', 'type' => 'number'], + ['key' => 'opening_balance', 'label' => '期初余额', 'type' => 'number'], + ['key' => 'current_balance', 'label' => '当前余额', 'type' => 'number'], + ['key' => 'bank_direct_difference', 'label' => '与银企直连余额差异', 'type' => 'number'], + ['key' => 'company_name', 'label' => '公司名称', 'type' => 'text'], + ['key' => 'account_no', 'label' => '账号', 'type' => 'text'], + ['key' => 'bank_name', 'label' => '开户行', 'type' => 'text'], + ]; + $columnTypes = collect($columns)->pluck('type', 'key')->all(); + $baseRows = $bankAccounts + ->map(static function (array $row) use ( + $adjustments, + ): array { + $isDirect = (bool) ($row['is_direct'] ?? false); + $accountShort = (string) ($row['account_short'] ?? ''); + $directBalance = $isDirect + ? round((float) ($row['current_balance'] ?? 0), 2) + : null; + $directBalanceDate = $isDirect + ? trim((string) ( + ($row['bank_bill_latest_date'] ?? null) + ?: ($row['bank_direct_balance_date'] ?? null) + ?: '' + )) + : ''; + + return [ + 'account_short' => $accountShort, + 'account_display_short' => (string) ($row['account_display_short'] ?? $row['account_short'] ?? ''), + 'bank_display' => (string) ($row['platform_label'] ?? ''), + 'account_type' => (string) ($row['account_type'] ?? ''), + 'bank_direct_connection' => $isDirect ? '是' : '否', + 'bank_direct_balance' => $directBalance, + 'bank_direct_balance_date' => $directBalanceDate, + 'opening_balance' => $row['opening_balance'] === null + ? null + : round((float) $row['opening_balance'], 2), + 'overview_current_balance' => round((float) ($row['current_balance'] ?? 0), 2), + 'adjustment_amount' => round((float) ($adjustments[$accountShort] ?? 0), 2), + 'company_name' => (string) ($row['company_name'] ?? ''), + 'account_no' => (string) ($row['account_no'] ?? ''), + 'bank_name' => (string) ($row['bank_name'] ?? ''), + 'available_balance' => (float) ($row['available_balance'] ?? 0), + 'blocked_balance' => (float) ($row['blocked_balance'] ?? 0), + ]; + }) + ->values(); + $directAccountShorts = $baseRows + ->whereNotNull('bank_direct_balance') + ->pluck('account_short') + ->map(static fn (mixed $accountShort): string => trim((string) $accountShort)) + ->filter() + ->values() + ->all(); + $movementDate = $period['to'] ?: now()->toDateString(); + if ($movementDate > now()->toDateString()) { + $movementDate = now()->toDateString(); + } + $directMovements = $this->bankBalanceCurrentCalculator->movementsOnDate( + $directAccountShorts, + $movementDate, + ); + $rows = $baseRows + ->map(static function (array $row) use ($directMovements): array { + $isDirect = $row['bank_direct_balance'] !== null; + $currentBalance = $isDirect + ? round( + (float) $row['bank_direct_balance'] + + (float) ($directMovements[$row['account_short']] ?? 0) + + (float) $row['adjustment_amount'], + 2, + ) + : round( + (float) $row['overview_current_balance'] + + (float) $row['adjustment_amount'], + 2, + ); + unset($row['overview_current_balance'], $row['adjustment_amount']); + + return [ + ...$row, + 'current_balance' => $currentBalance, + 'bank_direct_difference' => $isDirect + ? round($currentBalance - (float) $row['bank_direct_balance'], 2) + : null, + ]; + }) + ->values(); + + $displayValue = static function (array $row, string $key) use ($columnTypes): string { + $value = $row[$key] ?? null; + if ($value === null || $value === '') { + return '—'; + } + + return ($columnTypes[$key] ?? 'text') === 'number' + ? number_format((float) $value, 2, '.', ',') + : (string) $value; + }; + $filterValues = []; + foreach ($columns as $column) { + $key = (string) $column['key']; + $filterValues[$key] = $rows + ->map(static fn (array $row): string => $displayValue($row, $key)) + ->unique() + ->sort(static fn (string $left, string $right): int => strnatcasecmp($left, $right)) + ->values() + ->all(); + } + + $filters = []; + $rawFilters = json_decode((string) request('bank_balance_filters', ''), true); + if (is_array($rawFilters)) { + foreach ($rawFilters as $key => $values) { + if (! is_string($key) + || ! array_key_exists($key, $filterValues) + || ! is_array($values)) { + continue; + } + $selected = collect($values) + ->filter(static fn (mixed $value): bool => is_scalar($value)) + ->map(static fn (mixed $value): string => trim((string) $value)) + ->filter(static fn (string $value): bool => $value !== '') + ->unique() + ->take(500) + ->values() + ->all(); + if ($selected !== []) { + $filters[$key] = $selected; + } + } + } + if ($filters !== []) { + $rows = $rows + ->filter(static function (array $row) use ($filters, $displayValue): bool { + foreach ($filters as $key => $selected) { + if (! in_array($displayValue($row, $key), $selected, true)) { + return false; + } + } + + return true; + }) + ->values(); + } + + $sortKey = trim((string) request('bank_balance_sort', '')); + $sortDirection = trim((string) request('bank_balance_direction', '')); + if (! array_key_exists($sortKey, $filterValues) + || ! in_array($sortDirection, ['asc', 'desc'], true)) { + $sortKey = ''; + $sortDirection = ''; + } + if ($sortKey !== '') { + $multiplier = $sortDirection === 'desc' ? -1 : 1; + $rows = $rows->sort(static function (array $left, array $right) use ( + $sortKey, + $multiplier, + $columnTypes, + $displayValue, + ): int { + if (($columnTypes[$sortKey] ?? 'text') === 'number') { + $comparison = (float) ($left[$sortKey] ?? 0) <=> (float) ($right[$sortKey] ?? 0); + } else { + $comparison = strnatcasecmp( + $displayValue($left, $sortKey), + $displayValue($right, $sortKey), + ); + } + + return $comparison === 0 + ? strnatcasecmp( + (string) ($left['company_name'] ?? ''), + (string) ($right['company_name'] ?? ''), + ) + : $comparison * $multiplier; + })->values(); + } + + $summary = [ + 'count' => $rows->count(), + 'current_balance' => round((float) $rows->sum('current_balance'), 2), + 'available' => round((float) $rows->sum('available_balance'), 2), + 'blocked' => round((float) $rows->sum('blocked_balance'), 2), + ]; + $currentPage = 1; + $perPage = max(1, $rows->count()); + $paginator = new LengthAwarePaginator( + $rows->values(), + $rows->count(), + $perPage, + $currentPage, + [ + 'path' => Paginator::resolveCurrentPath(), + 'pageName' => 'bank_balances_page', + ], + ); + + return [ + 'rows' => $paginator, + 'summary' => $summary, + 'columns' => $columns, + 'filters' => $filters, + 'filter_values' => $filterValues, + 'sort' => $sortKey, + 'direction' => $sortDirection, + 'period' => $period, + 'movement_date' => $movementDate, + 'can_edit' => FinanceLedgerAccess::canEditBankBalance(user()), + 'update_url' => route('business.financial-ledger.bank-balances.current.update'), + ]; + } + /** * 账户基本信息首页的账户类型卡片。 * diff --git a/modules/EcommerceFinance/View/NonStoreAccountMonitorPageData.php b/modules/EcommerceFinance/View/NonStoreAccountMonitorPageData.php index d1c509f9..90ba6237 100644 --- a/modules/EcommerceFinance/View/NonStoreAccountMonitorPageData.php +++ b/modules/EcommerceFinance/View/NonStoreAccountMonitorPageData.php @@ -11,6 +11,7 @@ use Illuminate\Pagination\LengthAwarePaginator; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Modules\EcommerceFinance\Repositories\BankDirectBalanceRepository; +use Modules\EcommerceFinance\Services\FinanceLedgerBankBalanceCurrentCalculator; final class NonStoreAccountMonitorPageData { @@ -90,6 +91,7 @@ final class NonStoreAccountMonitorPageData public function __construct( private readonly BankDirectBalanceRepository $bankDirectBalances, + private readonly FinanceLedgerBankBalanceCurrentCalculator $transactionBalances, ) { } @@ -100,6 +102,7 @@ final class NonStoreAccountMonitorPageData $this->attachFlowMetrics($accountRows, $period, true); $this->attachBankBillMetrics($accountRows, $period, true); $this->attachLatestDirectBalances($accountRows, $period['to']); + $this->attachNonDirectRollingBalances($accountRows, $period['to']); $accounts = collect($accountRows); $view = $this->view(); $retained = $accounts @@ -350,6 +353,7 @@ final class NonStoreAccountMonitorPageData $this->attachFlowMetrics($retainedAccountRows, $period); $this->attachBankBillMetrics($retainedAccountRows, $period, true); $this->attachLatestDirectBalances($retainedAccountRows, $period['to']); + $this->attachNonDirectRollingBalances($retainedAccountRows, $period['to']); $retainedAccounts = collect($retainedAccountRows); [$filtered, $accountFilters] = $this->filterAccounts($retainedAccounts, $accountFilters); $accountPage = $this->paginate($filtered, 100, 'account_page'); @@ -553,6 +557,7 @@ final class NonStoreAccountMonitorPageData 'daily_limit' => $account->daily_limit, 'monthly_limit' => $account->monthly_limit, 'yearly_limit' => $account->yearly_limit, + 'account_current_balance' => round((float) ($account->current_balance ?? 0), 2), 'current_balance' => round((float) ($account->current_balance ?? 0), 2), 'available_balance' => round((float) ($account->daily_available ?? 0), 2), 'blocked_balance' => round((float) ($account->blocked_amount ?? 0), 2), @@ -640,6 +645,51 @@ final class NonStoreAccountMonitorPageData unset($row); } + /** + * 非银企直连账户的当前余额直接按账户期初和动账明细滚动, + * 不读取资金台账或账户总表里的 current_balance。 + * + * @param array> $rows + */ + private function attachNonDirectRollingBalances(array &$rows, string $asOf): void + { + $accountShorts = array_values(array_unique(array_filter(array_map( + static fn (array $row): string => (bool) ($row['is_direct'] ?? false) + || ! (bool) ($row['is_retained'] ?? false) + || ($row['category'] ?? '') !== self::CATEGORY_BANK + ? '' + : trim((string) ($row['account_short'] ?? '')), + $rows, + )))); + if ($accountShorts === []) { + return; + } + + $balances = $this->transactionBalances->balances($accountShorts, $asOf); + foreach ($rows as &$row) { + if ((bool) ($row['is_direct'] ?? false) + || ! (bool) ($row['is_retained'] ?? false) + || ($row['category'] ?? '') !== self::CATEGORY_BANK) { + continue; + } + $accountShort = (string) ($row['account_short'] ?? ''); + if (! array_key_exists($accountShort, $balances)) { + continue; + } + + $currentBalance = round((float) $balances[$accountShort], 2); + $blockedBalance = round(min( + max(0.0, (float) ($row['blocked_balance'] ?? 0)), + max(0.0, $currentBalance), + ), 2); + $row['current_balance'] = $currentBalance; + $row['blocked_balance'] = $blockedBalance; + $row['available_balance'] = round($currentBalance - $blockedBalance, 2); + $row['balance_source'] = 'transactions'; + } + unset($row); + } + /** * @param Collection> $accounts * @return array diff --git a/resources/views/business/pages/financial-ledger/ledger.blade.php b/resources/views/business/pages/financial-ledger/ledger.blade.php index d08c832b..b9559a43 100644 --- a/resources/views/business/pages/financial-ledger/ledger.blade.php +++ b/resources/views/business/pages/financial-ledger/ledger.blade.php @@ -38,6 +38,8 @@ request('accounts_bank'), request('accounts_balance'), ], static fn ($value): bool => trim((string) $value) !== '')); + $bankBalancePage = $ledgerBankBalancePage ?? null; + $bankBalanceRows = is_array($bankBalancePage) ? ($bankBalancePage['rows'] ?? null) : null; $money = static fn ($value): string => $value === null || $value === '' ? '' : number_format((float) $value, 2); $moneyWan = static function ($value): string { if ($value === null || trim((string) $value) === '') { @@ -670,6 +672,14 @@ #ledger-panel-transactions [data-ledger-transaction-summary] { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); } #ledger-panel-transactions [data-ledger-transaction-summary] .ledger-summary__item { flex:none; width:auto; min-width:0; } @media (max-width: 560px) { #ledger-panel-transactions [data-ledger-transaction-summary] { grid-template-columns:repeat(2,minmax(0,1fr)); } } + #ledger-panel-bank_balance [data-ledger-bank-balance-summary] { display:grid; grid-template-columns:repeat(4,minmax(0,1fr)); } + #ledger-panel-bank_balance [data-ledger-bank-balance-summary] .ledger-summary__item { flex:none; width:auto; min-width:0; } + .ledger-bank-balance-note { margin:.15rem 0 .75rem; color:var(--vip-content-muted, #595959); font-size:.68rem; line-height:1.55; } + .ledger-bank-balance-table { min-width:69rem; } + .ledger-bank-balance-table tbody td { padding-top:.4rem; padding-bottom:.4rem; vertical-align:middle; } + .ledger-bank-balance-table .money-negative { color:var(--vip-danger, #B80000); } + .ledger-bank-balance-table .ledger-source-tag { white-space:nowrap; } + @media (max-width: 760px) { #ledger-panel-bank_balance [data-ledger-bank-balance-summary] { grid-template-columns:repeat(2,minmax(0,1fr)); } } .ledger-summary__item--available { background:#f3f7ee; } .ledger-summary__item--blocked { background:#fff5f5; } .ledger-summary__item--link { color:inherit; text-decoration:none; transition:border-color .15s ease, box-shadow .15s ease; } @@ -1104,6 +1114,7 @@ @endif + @if ($ledgerPageMode === 'account-funds') {{-- 账户总览:首次点击时局部载入,不离开财务台账 --}}
@endif
+ @endif + + @if ($ledgerPageMode === 'fund-ledger') + + @endif {{-- 动账明细 --}} + @if ($ledgerPageMode === 'account-funds') {{-- 账户映射 --}} + @endif @if ($canEditAccounts) @@ -2831,9 +2865,13 @@ const tabs = Array.from(page.querySelectorAll('[data-ledger-tab]')); const panels = Array.from(page.querySelectorAll('[data-ledger-panel]')); const overviewPanel = page.querySelector('[data-ledger-overview-panel]'); + const bankBalancePanel = page.querySelector('[data-ledger-bank-balance-panel]'); let overviewRequest = null; let overviewAbort = null; let overviewSequence = 0; + let bankBalanceRequest = null; + let bankBalanceAbort = null; + let bankBalanceSequence = 0; let ledgerDependentDataStale = false; if (overviewPanel?.dataset.loaded === '1') { overviewPanel.dataset.sourceUrl = window.location.href; @@ -2848,6 +2886,91 @@ script.replaceWith(executable); }); }; + const loadBankBalance = ({ force = false } = {}) => { + if (!bankBalancePanel) return Promise.resolve(); + if (!force && bankBalancePanel.dataset.loaded === '1') { + return Promise.resolve(); + } + + bankBalanceAbort?.abort(); + bankBalanceAbort = new AbortController(); + const sequence = ++bankBalanceSequence; + const loading = bankBalancePanel.querySelector('[data-ledger-bank-balance-loading]'); + if (loading) { + loading.hidden = false; + loading.classList.remove('is-error'); + loading.textContent = '正在载入银行余额…'; + } + bankBalancePanel.setAttribute('aria-busy', 'true'); + bankBalancePanel.querySelector('[data-bank-balance-load-error]')?.remove(); + const requestUrl = new URL( + bankBalancePanel.dataset.url || '/1/workspace/financial-operations/fund-ledger', + window.location.href, + ); + requestUrl.searchParams.set('tab', 'bank_balance'); + requestUrl.searchParams.set('ledger_bank_balance_partial', '1'); + bankBalanceRequest = fetch(requestUrl.toString(), { + credentials: 'same-origin', + headers: { + 'Accept': 'text/html', + 'X-Requested-With': 'XMLHttpRequest', + }, + signal: bankBalanceAbort.signal, + }) + .then(async (response) => { + if (!response.ok) throw new Error('银行余额载入失败'); + let responsePath = ''; + try { + responsePath = new URL(response.url, window.location.href).pathname; + } catch (error) { + responsePath = ''; + } + const html = await response.text(); + if (/\/auth\/login\/?$/.test(responsePath) + || /]+action="[^"]*\/auth\/login"/i.test(html)) { + const authError = new Error('登录已过期,请重新登录后继续操作。'); + authError.authExpired = true; + throw authError; + } + if (sequence !== bankBalanceSequence) return; + bankBalancePanel.innerHTML = html; + bankBalancePanel.dataset.loaded = '1'; + bankBalancePanel.removeAttribute('aria-busy'); + runPanelScripts(bankBalancePanel); + initializeLedgerDateRanges(bankBalancePanel); + }) + .catch((error) => { + if (error.name === 'AbortError' || sequence !== bankBalanceSequence) return; + const alert = document.createElement('div'); + alert.className = 'ledger-note is-warning'; + alert.dataset.bankBalanceLoadError = ''; + alert.setAttribute('role', 'alert'); + alert.textContent = error.message || '银行余额载入失败,请稍后重试'; + if (error.authExpired) { + const loginLink = document.createElement('a'); + loginLink.href = '/auth/login'; + loginLink.textContent = '重新登录'; + loginLink.style.marginLeft = '.5rem'; + loginLink.style.color = 'var(--vip-content-accent-dark, #856632)'; + loginLink.style.fontWeight = '600'; + loginLink.style.textDecoration = 'underline'; + alert.append(loginLink); + } + bankBalancePanel.prepend(alert); + }) + .finally(() => { + if (sequence === bankBalanceSequence) { + bankBalancePanel.removeAttribute('aria-busy'); + bankBalanceRequest = null; + bankBalanceAbort = null; + } + }); + + return bankBalanceRequest; + }; + bankBalancePanel?.addEventListener('ledger-bank-balance-loaded', () => { + initializeLedgerDateRanges(bankBalancePanel); + }); const overviewUrlFor = (targetUrl = null) => { const url = new URL(window.location.href); url.search = ''; @@ -3053,8 +3176,13 @@ void loadOverview(); return; } + if (name === 'bank_balance') { + showTab(name); + void loadBankBalance(); + return; + } overviewAbort?.abort(); - if (ledgerDependentDataStale && ['accounts', 'shops', 'flows', 'mapping', 'sources'].includes(name)) { + if (ledgerDependentDataStale && ['bank_balance', 'accounts', 'shops', 'flows', 'mapping', 'sources'].includes(name)) { const url = new URL(window.location.href); url.searchParams.set('tab', name); window.location.assign(url.toString()); diff --git a/resources/views/business/pages/financial-ledger/partials/bank-balance-panel.blade.php b/resources/views/business/pages/financial-ledger/partials/bank-balance-panel.blade.php new file mode 100644 index 00000000..129327cd --- /dev/null +++ b/resources/views/business/pages/financial-ledger/partials/bank-balance-panel.blade.php @@ -0,0 +1,912 @@ +@php + $bankBalancePage = $ledgerBankBalancePage ?? []; + $bankBalanceRows = $bankBalancePage['rows'] ?? null; + $bankBalanceSummary = $bankBalancePage['summary'] ?? []; + $bankBalanceColumns = $bankBalancePage['columns'] ?? []; + $bankBalancePeriod = $bankBalancePage['period'] ?? []; + $canEditBankBalance = (bool) ($bankBalancePage['can_edit'] ?? false); + $money = static fn ($value): string => $value === null || $value === '' ? '—' : number_format((float) $value, 2); + $moneyYuanTitle = static fn ($value): string => $value === null || $value === '' + ? '' + : number_format((float) $value, 2) . ' 元'; +@endphp + +@if ($bankBalanceRows !== null) + + +
+
+ +
+
+ 银行账户数 + {{ number_format((int) ($bankBalanceSummary['count'] ?? 0)) }} +
+
+ 当前余额合计(元) + {{ $money($bankBalanceSummary['current_balance'] ?? 0) }} +
+
+ @include('business.pages.financial-ledger.partials.date-range-filter', [ + 'id' => 'bank-balance-period', + 'label' => '日期筛选', + 'startName' => 'period_from', + 'endName' => 'period_to', + 'from' => $bankBalancePeriod['from'] ?? '', + 'to' => $bankBalancePeriod['to'] ?? '', + ]) +
+ + +
+
+ + +
+
+

期初余额取自账户总览当前日期范围。直连账户以昨天最后一笔银企直连余额为起点,叠加所选日期当天的动账;默认按今天计算,查看历史日期时按结束日期计算。非直连账户采用账户总览中按动账明细滚动后的当前余额。本页校正只影响本页,不回写账户资金管理。

+
+ + + + @foreach ($bankBalanceColumns as $column) + + @endforeach + + + + @forelse ($bankBalanceRows as $row) + @php + $currentBalance = (float) ($row['current_balance'] ?? 0); + $directBalance = $row['bank_direct_balance'] ?? null; + $directDifference = $row['bank_direct_difference'] ?? null; + @endphp + + + + + + + + + + + + + + @empty + + @endforelse + +
{{ $column['label'] }}
{{ $row['account_display_short'] ?: $row['account_short'] }}{{ $row['bank_display'] ?: '未识别' }}{{ $row['account_type'] ?: '未填写' }}{{ $row['bank_direct_connection'] }}{{ $directBalance === null ? '—' : $money($directBalance) }}{{ $money($row['opening_balance'] ?? null) }} +
+ {{ $money($currentBalance) }} + @if ($canEditBankBalance) + + @endif +
+ + +
{{ $directDifference === null ? '—' : $money($directDifference) }}{{ $row['company_name'] ?: '—' }}{{ $row['account_no'] ?: '—' }}{{ $row['bank_name'] ?: '—' }}
当前没有可展示的保留银行账户余额。
+
+ @if ($bankBalanceRows->hasPages()) + @include('business.pages.financial-ledger.partials.pagination', [ + 'rows' => $bankBalanceRows, + 'paginationKey' => 'bank_balances', + 'paginationLabel' => '银行余额分页', + ]) + @endif +
+ + +@endif diff --git a/routes/admin.php b/routes/admin.php index edb103dd..e7604992 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -1057,6 +1057,10 @@ Route::get('workspace/financial-ledger/bank-bills/filter-options', [\App\Http\Co ->middleware('business.page:financial-operations,ledger') ->name('business.financial-ledger.bank-bills.filter-options'); +Route::post('workspace/financial-ledger/bank-balances/current', [\App\Http\Controllers\Business\FinanceLedger::class, 'updateBankBalanceCurrent']) + ->middleware('business.page:financial-operations,ledger') + ->name('business.financial-ledger.bank-balances.current.update'); + Route::post('workspace/financial-ledger/mapping/shop/preview', [\App\Http\Controllers\Business\FinanceLedger::class, 'previewShopMapping']) ->middleware('business.page:financial-operations,ledger') ->name('business.financial-ledger.mapping.shop.preview'); diff --git a/tests/Feature/Business/FinanceLedgerNavigationTest.php b/tests/Feature/Business/FinanceLedgerNavigationTest.php index 85a40312..ff5d7733 100644 --- a/tests/Feature/Business/FinanceLedgerNavigationTest.php +++ b/tests/Feature/Business/FinanceLedgerNavigationTest.php @@ -8,6 +8,7 @@ use App\Models\Auth\User; use App\Utilities\BusinessNavigation; use App\Utilities\SidebarMenu; use App\Utilities\SidebarPermissions; +use Illuminate\Support\Facades\DB; use Modules\EcommerceFinance\View\FinanceLedgerPageData; use Tests\Feature\FeatureTestCase; @@ -249,7 +250,7 @@ class FinanceLedgerNavigationTest extends FeatureTestCase } } - public function test_fund_ledger_contains_only_transaction_panel(): void + public function test_fund_ledger_contains_bank_balance_and_transaction_panels(): void { $this->loginAs(); @@ -264,22 +265,455 @@ class FinanceLedgerNavigationTest extends FeatureTestCase $this->assertSame(1, preg_match('/