diff --git a/app/Console/Commands/LockFinanceLedgerMonthlyOpening.php b/app/Console/Commands/LockFinanceLedgerMonthlyOpening.php index 49c57a25..c418d399 100644 --- a/app/Console/Commands/LockFinanceLedgerMonthlyOpening.php +++ b/app/Console/Commands/LockFinanceLedgerMonthlyOpening.php @@ -169,11 +169,22 @@ class LockFinanceLedgerMonthlyOpening extends Command $latestTransactionByShort, $latestTransactionByAccountNo, ); + $opening = $openingBefore->get($short); + $latestOpeningDate = $opening === null + ? '' + : substr((string) $opening->opening_date, 0, 10); if ($carriedBalance !== null && ($balance === null || $carriedSourceDate > $sourceDate)) { $balance = $carriedBalance; $source = $carriedSource; $sourceDate = $carriedSourceDate; + } elseif ($balance !== null + && $latestOpeningDate !== '' + && $sourceDate < $latestOpeningDate) { + // 新期初比旧账单余额更晚;若期初后还有未定价动账,不能回退使用旧余额。 + $balance = null; + $source = ''; + $sourceDate = ''; } if ($balance === null) { $byShort[$short][] = [ diff --git a/tests/Unit/EcommerceFinance/LockFinanceLedgerMonthlyOpeningTest.php b/tests/Unit/EcommerceFinance/LockFinanceLedgerMonthlyOpeningTest.php index 4fe29626..1d04ce43 100644 --- a/tests/Unit/EcommerceFinance/LockFinanceLedgerMonthlyOpeningTest.php +++ b/tests/Unit/EcommerceFinance/LockFinanceLedgerMonthlyOpeningTest.php @@ -188,6 +188,16 @@ class LockFinanceLedgerMonthlyOpeningTest extends TestCase 'updated_at' => '2026-10-01 08:00:00', ]); $db->table('fin_transactions')->insert([ + [ + 'txn_date' => '2026-09-30', + 'account_short' => '有交易无余额账户', + 'source' => 'bank_statement', + 'source_value' => '6200000000000004', + 'income' => 0, + 'expense' => 0, + 'balance' => 100, + ], + [ 'txn_date' => '2026-10-02', 'account_short' => '有交易无余额账户', 'source' => 'bank_statement', @@ -195,6 +205,7 @@ class LockFinanceLedgerMonthlyOpeningTest extends TestCase 'income' => 0, 'expense' => 10, 'balance' => null, + ], ]); $this->artisan('finance-ledger:lock-monthly-opening', [