fix(财务台账): 锁定月度期初不让动账改写 (#1400)

This commit is contained in:
shanshi 2026-11-25 12:03:11 +08:00
parent 1114349ac7
commit a14c0d44ca
8 changed files with 685 additions and 97 deletions

View File

@ -0,0 +1,299 @@
<?php
namespace App\Console\Commands;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use RuntimeException;
class LockFinanceLedgerMonthlyOpening extends Command
{
protected $signature = 'finance-ledger:lock-monthly-opening
{date? : 锁定日期,必须为每月 1 日;默认当月}
{--apply : 正式写入;不传时只预览}
{--json : 以 JSON 输出结果}';
protected $description = '按上月末最后一笔真实银行余额锁定账户月度期初';
public function handle(): int
{
try {
$date = $this->date();
$previousEnd = $date->subDay();
$nextMonth = $date->addMonthNoOverflow();
$result = $this->lock($date, $previousEnd, $nextMonth, (bool) $this->option('apply'));
if ((bool) $this->option('json')) {
$this->line(json_encode(
$result,
JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
));
} else {
$this->line(($result['applied'] ? '已锁定' : '预览') . ' ' . $result['opening_date'] . ' 月度期初');
$this->line(
'可锁定账户:' . $result['eligible_accounts']
. ';写入账户:' . $result['unique_account_shorts']
. ';新增:' . $result['created']
. ';更新:' . $result['updated']
. ';无变化:' . $result['unchanged']
);
$this->line(
'跳过:无真实余额 ' . $result['skipped_no_basis']
. ';同名账户余额冲突 ' . $result['skipped_conflicts']
);
}
return self::SUCCESS;
} catch (\Throwable $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
}
private function date(): CarbonImmutable
{
$value = trim((string) ($this->argument('date') ?: now('Asia/Shanghai')->toDateString()));
$date = CarbonImmutable::createFromFormat('!Y-m-d', $value, 'Asia/Shanghai');
if (! $date instanceof CarbonImmutable
|| $date->format('Y-m-d') !== $value
|| $date->day !== 1) {
throw new RuntimeException('锁定日期必须使用 YYYY-MM-01 格式。');
}
return $date;
}
/**
* @return array<string,mixed>
*/
private function lock(
CarbonImmutable $date,
CarbonImmutable $previousEnd,
CarbonImmutable $nextMonth,
bool $apply,
): array {
$connection = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror'));
$accounts = $connection->table('fin_accounts')
->whereNotNull('account_short')
->where('account_short', '<>', '')
->orderBy('account_short')
->orderBy('account_no')
->get(['id', 'account_short', 'account_no']);
$bankStatementBefore = [];
$bankStatementFirst = [];
foreach ($connection->table('fin_transactions')
->where('source', 'bank_statement')
->whereNotNull('balance')
->orderBy('txn_date')
->orderBy('id')
->get(['txn_date', 'source_value', 'income', 'expense', 'balance']) as $row) {
$accountNo = $this->accountNo($row->source_value);
if ($accountNo === '') {
continue;
}
if ($row->txn_date <= $previousEnd->toDateString()) {
$bankStatementBefore[$accountNo] = $row;
} elseif ($row->txn_date >= $date->toDateString()
&& $row->txn_date < $nextMonth->toDateString()
&& ! isset($bankStatementFirst[$accountNo])) {
$bankStatementFirst[$accountNo] = $row;
}
}
$bankBillBefore = [];
$bankBillFirst = [];
foreach ($connection->table('fin_bank_direct_bills')
->whereNotNull('balance')
->orderBy('txn_date')
->orderBy('txn_at')
->orderBy('id')
->get(['account_no', 'txn_date', 'income', 'expense', 'balance']) as $row) {
$accountNo = $this->accountNo($row->account_no);
if ($accountNo === '') {
continue;
}
if ($row->txn_date <= $previousEnd->toDateString()) {
$bankBillBefore[$accountNo] = $row;
} elseif ($row->txn_date >= $date->toDateString()
&& $row->txn_date < $nextMonth->toDateString()
&& ! isset($bankBillFirst[$accountNo])) {
$bankBillFirst[$accountNo] = $row;
}
}
$snapshotBefore = [];
foreach ($connection->table('fin_bank_direct_balance_snapshots')
->where('balance_date', '<=', $previousEnd->toDateString())
->orderBy('balance_date')
->orderBy('balance_at')
->orderBy('id')
->get(['account_no', 'account_balance', 'available_balance']) as $row) {
$accountNo = $this->accountNo($row->account_no);
if ($accountNo !== '') {
$snapshotBefore[$accountNo] = $row;
}
}
$existingOpenings = $connection->table('fin_account_opening')
->where('opening_date', $date->toDateString())
->get()
->keyBy('account_short');
$byShort = [];
foreach ($accounts as $account) {
$short = trim((string) $account->account_short);
$accountNo = $this->accountNo($account->account_no);
[$balance, $source] = $this->actualOpening(
$accountNo,
$bankStatementBefore,
$bankStatementFirst,
$bankBillBefore,
$bankBillFirst,
$snapshotBefore,
);
if ($balance === null && $existingOpenings->has($short)) {
$balance = round((float) $existingOpenings->get($short)->opening_balance, 2);
$source = 'existing_locked';
}
$byShort[$short][] = [
'account_id' => (int) $account->id,
'balance' => $balance,
'source' => $source,
];
}
$eligibleAccounts = 0;
$skippedNoBasis = 0;
$skippedConflicts = 0;
$candidates = [];
foreach ($byShort as $short => $items) {
$missing = array_filter($items, static fn (array $item): bool => $item['balance'] === null);
if ($missing !== []) {
$skippedNoBasis += count($items);
continue;
}
$balances = array_values(array_unique(array_map(
static fn (array $item): string => number_format((float) $item['balance'], 2, '.', ''),
$items,
)));
if (count($balances) !== 1) {
$skippedConflicts += count($items);
continue;
}
$eligibleAccounts += count($items);
$candidates[$short] = [
'opening_balance' => (float) $balances[0],
'source' => (string) $items[0]['source'],
];
}
$created = 0;
$updated = 0;
$unchanged = 0;
if ($apply) {
$connection->transaction(function () use (
$connection,
$date,
$candidates,
$existingOpenings,
&$created,
&$updated,
&$unchanged,
): void {
foreach ($candidates as $short => $candidate) {
$existing = $existingOpenings->get($short);
$remark = '系统锁定:' . $date->subDay()->toDateString() . ' 最后一笔实际余额';
if ($existing === null) {
$connection->table('fin_account_opening')->insert([
'account_short' => $short,
'opening_date' => $date->toDateString(),
'opening_balance' => $candidate['opening_balance'],
'remark' => $remark,
'created_at' => now(),
'updated_at' => now(),
]);
$created++;
continue;
}
if (abs((float) $existing->opening_balance - (float) $candidate['opening_balance']) < 0.005
&& (string) $existing->remark === $remark) {
$unchanged++;
continue;
}
$connection->table('fin_account_opening')
->where('id', $existing->id)
->update([
'opening_balance' => $candidate['opening_balance'],
'remark' => $remark,
'updated_at' => now(),
]);
$updated++;
}
});
}
return [
'applied' => $apply,
'opening_date' => $date->toDateString(),
'previous_period_end' => $previousEnd->toDateString(),
'eligible_accounts' => $eligibleAccounts,
'unique_account_shorts' => count($candidates),
'created' => $created,
'updated' => $updated,
'unchanged' => $unchanged,
'skipped_no_basis' => $skippedNoBasis,
'skipped_conflicts' => $skippedConflicts,
];
}
/**
* @return array{0:?float,1:string}
*/
private function actualOpening(
string $accountNo,
array $bankStatementBefore,
array $bankStatementFirst,
array $bankBillBefore,
array $bankBillFirst,
array $snapshotBefore,
): array {
if ($accountNo === '') {
return [null, ''];
}
if (isset($bankStatementBefore[$accountNo])) {
return [round((float) $bankStatementBefore[$accountNo]->balance, 2), 'bank_statement'];
}
if (isset($bankBillBefore[$accountNo])) {
return [round((float) $bankBillBefore[$accountNo]->balance, 2), 'bank_bill'];
}
if (isset($snapshotBefore[$accountNo])) {
$row = $snapshotBefore[$accountNo];
return [
round((float) ($row->account_balance ?? $row->available_balance), 2),
'balance_snapshot',
];
}
if (isset($bankStatementFirst[$accountNo])) {
$row = $bankStatementFirst[$accountNo];
return [
round((float) $row->balance - (float) $row->income + (float) $row->expense, 2),
'bank_statement_next_day',
];
}
if (isset($bankBillFirst[$accountNo])) {
$row = $bankBillFirst[$accountNo];
return [
round((float) $row->balance - (float) $row->income + (float) $row->expense, 2),
'bank_bill_next_day',
];
}
return [null, ''];
}
private function accountNo(mixed $value): string
{
return preg_replace('/\D+/', '', trim((string) $value)) ?? '';
}
}

View File

@ -25,12 +25,12 @@ class FinanceLedgerCalculator
$openingDate = (string) config('finance_ledger.opening_date', '2026-10-17');
$now = now();
$opening = $connection->table('fin_account_opening')
$openingByAccount = $connection->table('fin_account_opening')
->orderBy('opening_date')
->orderBy('id')
->get()
->groupBy('account_short')
->map(static fn ($rows) => $rows->last());
->map(static fn ($rows) => $rows->values());
$directAccountShorts = $this->directAccountShorts($connection);
$accountCompanies = FinanceLedgerIndependentAccounts::exclude(
$connection->table('fin_accounts'),
@ -101,34 +101,8 @@ class FinanceLedgerCalculator
}
$company = (string) ($accountRow->company_name ?? '');
$openingRow = $opening->get($account);
$balance = $openingRow === null ? 0.0 : (float) $openingRow->opening_balance;
$start = $openingRow === null
? $openingDate
: (string) $openingRow->opening_date;
$rows = array_values($dailyByAccount[$account] ?? []);
usort($rows, static fn (array $a, array $b): int => strcmp($a['flow_date'], $b['flow_date']));
$openingFlow = [
'flow_date' => $start,
'company_name' => $company,
'account_short' => $account,
'opening_balance' => round($balance, 2),
'inflow' => 0.0,
'outflow' => 0.0,
'closing_balance' => round($balance, 2),
'remark' => '期初',
'created_at' => $now,
'updated_at' => $now,
];
if ($hasManualColumns) {
$openingFlow['manual_override'] = false;
$openingFlow['updated_by'] = null;
}
$flows[] = $openingFlow;
$openingIndex = array_key_last($flows);
$dates = array_values(array_unique([
...array_column($rows, 'flow_date'),
...$manualOverrides
@ -142,18 +116,110 @@ class FinanceLedgerCalculator
foreach ($rows as $row) {
$rowsByDate[(string) $row['flow_date']] = $row;
}
$accountOpenings = $openingByAccount->get($account, collect())
->map(static fn (object $row): array => [
'date' => substr((string) $row->opening_date, 0, 10),
'balance' => round((float) $row->opening_balance, 2),
])
->sortBy('date')
->values();
if ($accountOpenings->isEmpty()) {
$accountOpenings = collect([[
'date' => $openingDate,
'balance' => 0.0,
]]);
}
foreach ($dates as $date) {
if ($date < $start) {
continue;
$balance = 0.0;
foreach ($accountOpenings as $index => $openingSegment) {
$start = (string) $openingSegment['date'];
$nextStart = (string) ($accountOpenings->get($index + 1)['date'] ?? '');
$balance = round((float) $openingSegment['balance'], 2);
$openingFlow = [
'flow_date' => $start,
'company_name' => $company,
'account_short' => $account,
'opening_balance' => $balance,
'inflow' => 0.0,
'outflow' => 0.0,
'closing_balance' => $balance,
'remark' => '期初',
'created_at' => $now,
'updated_at' => $now,
];
if ($hasManualColumns) {
$openingFlow['manual_override'] = false;
$openingFlow['updated_by'] = null;
}
$flows[] = $openingFlow;
$openingIndex = array_key_last($flows);
$override = $manualOverrides->get($date . "\0" . $account);
if ($override !== null) {
$openingBalance = round((float) $override->opening_balance, 2);
$inflow = round((float) $override->inflow, 2);
$outflow = round((float) $override->outflow, 2);
$balance = round((float) $override->closing_balance, 2);
foreach ($dates as $date) {
if ($date < $start) {
continue;
}
if ($nextStart !== '' && $date >= $nextStart) {
break;
}
$override = $manualOverrides->get($date . "\0" . $account);
if ($override !== null) {
$inflow = round((float) $override->inflow, 2);
$outflow = round((float) $override->outflow, 2);
$openingBalance = $date === $start
? $balance
: round((float) $override->opening_balance, 2);
$closingBalance = $date === $start
? round($openingBalance + $inflow - $outflow, 2)
: round((float) $override->closing_balance, 2);
$balance = $closingBalance;
$flow = [
'flow_date' => $date,
'company_name' => $company,
'account_short' => $account,
'opening_balance' => $openingBalance,
'inflow' => $inflow,
'outflow' => $outflow,
'closing_balance' => $closingBalance,
'remark' => $override->remark !== null ? (string) $override->remark : '手动调整',
'created_at' => $now,
'updated_at' => $now,
];
if ($hasManualColumns) {
$flow['manual_override'] = true;
$flow['updated_by'] = $override->updated_by !== null ? (string) $override->updated_by : null;
}
if ($date === $start) {
$flows[$openingIndex] = $flow;
} else {
$flows[] = $flow;
}
continue;
}
$row = $rowsByDate[$date] ?? null;
if ($row === null) {
continue;
}
$inflow = round((float) $row['inflow'], 2);
$outflow = round((float) $row['outflow'], 2);
if (abs($inflow) < 0.005 && abs($outflow) < 0.005) {
continue;
}
if ($date === $start) {
// 期初日发生动账时合并到同一行,固定期初余额本身不变。
$balance = round($balance + $inflow - $outflow, 2);
$flows[$openingIndex]['inflow'] = $inflow;
$flows[$openingIndex]['outflow'] = $outflow;
$flows[$openingIndex]['closing_balance'] = $balance;
$flows[$openingIndex]['remark'] = null;
continue;
}
$openingBalance = $balance;
$balance = round($balance + $inflow - $outflow, 2);
$flow = [
'flow_date' => $date,
'company_name' => $company,
@ -162,63 +228,17 @@ class FinanceLedgerCalculator
'inflow' => $inflow,
'outflow' => $outflow,
'closing_balance' => $balance,
'remark' => $override->remark !== null ? (string) $override->remark : '手动调整',
'remark' => null,
'created_at' => $now,
'updated_at' => $now,
];
if ($hasManualColumns) {
$flow['manual_override'] = true;
$flow['updated_by'] = $override->updated_by !== null ? (string) $override->updated_by : null;
$flow['manual_override'] = false;
$flow['updated_by'] = null;
}
if ($date === $start) {
$flows[$openingIndex] = $flow;
} else {
$flows[] = $flow;
}
continue;
$flows[] = $flow;
}
$row = $rowsByDate[$date] ?? null;
if ($row === null) {
continue;
}
$inflow = round((float) $row['inflow'], 2);
$outflow = round((float) $row['outflow'], 2);
if (abs($inflow) < 0.005 && abs($outflow) < 0.005) {
continue;
}
if ($date === $start) {
// 期初日发生动账时合并到同一行,避免唯一键冲突。
$balance = round($balance + $inflow - $outflow, 2);
$flows[$openingIndex]['inflow'] = $inflow;
$flows[$openingIndex]['outflow'] = $outflow;
$flows[$openingIndex]['closing_balance'] = $balance;
$flows[$openingIndex]['remark'] = null;
continue;
}
$balance = round($balance + $inflow - $outflow, 2);
$flow = [
'flow_date' => $date,
'company_name' => $company,
'account_short' => $account,
'opening_balance' => round($balance - $inflow + $outflow, 2),
'inflow' => $inflow,
'outflow' => $outflow,
'closing_balance' => $balance,
'remark' => null,
'created_at' => $now,
'updated_at' => $now,
];
if ($hasManualColumns) {
$flow['manual_override'] = false;
$flow['updated_by'] = null;
}
$flows[] = $flow;
}
$latest[$account] = $balance;
}

View File

@ -28,7 +28,9 @@ class FinanceLedgerFlowEditor
{
$date = $this->date($data['flow_date'] ?? null);
$accountShort = $this->text($data['account_short'] ?? '');
$openingCents = $this->cents($data['opening_balance'] ?? 0);
$openingCents = $this->cents(
$this->editableFlow($date, $accountShort)['opening_balance'] ?? 0,
);
$inflowCents = $this->cents($data['inflow'] ?? 0);
$outflowCents = $this->cents($data['outflow'] ?? 0);
$closingCents = $this->cents($data['closing_balance'] ?? 0);
@ -185,7 +187,12 @@ class FinanceLedgerFlowEditor
$date = $this->date($flowDate);
$accountShort = $this->text($accountShort);
$existing = $this->existingFlow($date, $accountShort);
$lockedOpening = $this->lockedMonthlyOpening($date, $accountShort);
if ($existing !== null) {
if ($lockedOpening !== null) {
$existing['opening_balance'] = $lockedOpening;
}
return $existing;
}
@ -204,13 +211,13 @@ class FinanceLedgerFlowEditor
->orderByDesc('flow_date')
->orderByDesc('id')
->first(['closing_balance']);
$openingBalance = $latest === null
$openingBalance = $lockedOpening ?? ($latest === null
? round((float) ($this->connection->table('fin_account_opening')
->where('account_short', $accountShort)
->where('opening_date', '<=', $date)
->orderByDesc('opening_date')
->value('opening_balance') ?? 0), 2)
: round((float) $latest->closing_balance, 2);
: round((float) $latest->closing_balance, 2));
return [
'id' => null,
@ -240,6 +247,16 @@ class FinanceLedgerFlowEditor
return $text;
}
private function lockedMonthlyOpening(string $date, string $accountShort): ?float
{
$value = $this->connection->table('fin_account_opening')
->where('account_short', $accountShort)
->where('opening_date', $date)
->value('opening_balance');
return $value === null ? null : round((float) $value, 2);
}
private function cents(mixed $value): int
{
return (int) round((float) $value * 100);

View File

@ -1313,6 +1313,12 @@ final class NonStoreAccountMonitorPageData
if ($accountShorts === []) {
return;
}
$fixedOpenings = $this->db()->table('fin_account_opening')
->whereIn('account_short', $accountShorts)
->where('opening_date', $period['from'])
->pluck('opening_balance', 'account_short')
->map(static fn (mixed $value): float => round((float) $value, 2))
->all();
$query = $this->db()->table('fin_daily_flows')
->whereIn('account_short', $accountShorts)
@ -1340,9 +1346,11 @@ final class NonStoreAccountMonitorPageData
});
$latestBefore = $before->last();
$firstInPeriod = $inPeriod->first();
$openingBalance = $latestBefore !== null
? round((float) $latestBefore->closing_balance, 2)
: ($firstInPeriod === null ? null : round((float) $firstInPeriod->opening_balance, 2));
$openingBalance = array_key_exists((string) $accountShort, $fixedOpenings)
? $fixedOpenings[(string) $accountShort]
: ($latestBefore !== null
? round((float) $latestBefore->closing_balance, 2)
: ($firstInPeriod === null ? null : round((float) $firstInPeriod->opening_balance, 2)));
$inflow = round((float) $inPeriod->sum('inflow'), 2);
$outflow = round((float) $inPeriod->sum('outflow'), 2);
$metrics[(string) $accountShort] = [
@ -1390,10 +1398,15 @@ final class NonStoreAccountMonitorPageData
bool $useClosingAsCurrent,
): void {
$accountNumbers = [];
$accountShorts = [];
foreach ($rows as $row) {
if (! ($row['uses_bank_balance'] ?? false)) {
continue;
}
$accountShort = trim((string) ($row['account_short'] ?? ''));
if ($accountShort !== '') {
$accountShorts[$accountShort] = true;
}
$accountNo = preg_replace('/\D+/', '', (string) ($row['account_no'] ?? '')) ?? '';
if ($accountNo !== '') {
$accountNumbers[$accountNo] = true;
@ -1402,6 +1415,23 @@ final class NonStoreAccountMonitorPageData
if ($accountNumbers === []) {
return;
}
$fixedOpenings = $accountShorts === []
? []
: $this->db()->table('fin_account_opening')
->whereIn('account_short', array_keys($accountShorts))
->where('opening_date', $period['from'])
->pluck('opening_balance', 'account_short')
->map(static fn (mixed $value): float => round((float) $value, 2))
->all();
foreach ($rows as &$row) {
$accountShort = trim((string) ($row['account_short'] ?? ''));
if (($row['uses_bank_balance'] ?? false)
&& array_key_exists($accountShort, $fixedOpenings)) {
$row['opening_balance'] = $fixedOpenings[$accountShort];
$row['monthly_opening_locked'] = true;
}
}
unset($row);
$bankBills = $this->db()->table('fin_bank_direct_bills')
->whereIn('bank_name', ['招商银行', '华夏银行', '网商银行'])
@ -1458,9 +1488,10 @@ final class NonStoreAccountMonitorPageData
$opening = $before
->filter(static fn (object $bill): bool => $bill->balance !== null && $bill->balance !== '')
->last();
$openingBalance = $opening !== null
? round((float) $opening->balance, 2)
: null;
$accountShort = trim((string) ($row['account_short'] ?? ''));
$openingBalance = array_key_exists($accountShort, $fixedOpenings)
? $fixedOpenings[$accountShort]
: ($opening !== null ? round((float) $opening->balance, 2) : null);
$firstInPeriod = $inPeriod->first();
if ($openingBalance === null && $firstInPeriod !== null && $firstInPeriod->balance !== null) {
$openingBalance = round(

View File

@ -2641,7 +2641,7 @@
<div class="ledger-company-field"><label for="ledger-flow-date-edit">日期</label><input id="ledger-flow-date-edit" type="date" min="{{ config('finance_ledger.opening_date', '2026-10-17') }}" max="{{ now()->toDateString() }}" required data-ledger-flow-date readonly></div>
<div class="ledger-company-field ledger-edit-field--wide"><label for="ledger-flow-account-edit">账户简称</label><input id="ledger-flow-account-edit" type="text" data-ledger-flow-account readonly></div>
<div class="ledger-company-field"><label>当前口径</label><input type="text" data-ledger-flow-mode readonly></div>
<div class="ledger-company-field"><label for="ledger-flow-opening">期初余额(元)</label><input id="ledger-flow-opening" name="opening_balance" type="number" step="0.01" required data-ledger-flow-opening></div>
<div class="ledger-company-field"><label for="ledger-flow-opening">期初余额(元,系统锁定)</label><input id="ledger-flow-opening" name="opening_balance" type="number" step="0.01" required readonly data-ledger-flow-opening></div>
<div class="ledger-company-field"><label for="ledger-flow-inflow">当日入账(元)</label><input id="ledger-flow-inflow" name="inflow" type="number" min="0" step="0.01" required data-ledger-flow-inflow></div>
<div class="ledger-company-field"><label for="ledger-flow-outflow">当日出账(元)</label><input id="ledger-flow-outflow" name="outflow" type="number" min="0" step="0.01" required data-ledger-flow-outflow></div>
<div class="ledger-company-field"><label for="ledger-flow-closing">期末余额(元)</label><input id="ledger-flow-closing" name="closing_balance" type="number" step="0.01" required readonly data-ledger-flow-closing></div>

View File

@ -399,6 +399,60 @@ class NonStoreAccountMonitorTest extends FeatureTestCase
);
}
public function test_locked_monthly_opening_does_not_follow_previous_daily_flow(): void
{
$connection = DB::connection('business_mirror');
$connection->table('fin_accounts')->insert([
'company_name' => '期初锁定公司',
'account_short' => '期初锁定账户',
'account_type' => '公户',
'bank_name' => '中国银行常州分行',
'account_no' => '6200000000000001',
'account_should_keep' => '是',
'current_balance' => 312.44,
'daily_available' => 312.44,
'blocked_amount' => 0,
]);
$connection->table('fin_account_opening')->insert([
'account_short' => '期初锁定账户',
'opening_date' => '2026-11-01',
'opening_balance' => 412.44,
'remark' => '系统锁定:2026-10-31 最后一笔实际余额',
]);
$connection->table('fin_daily_flows')->insert([
[
'flow_date' => '2026-10-31',
'company_name' => '期初锁定公司',
'account_short' => '期初锁定账户',
'opening_balance' => -99999,
'inflow' => 0,
'outflow' => 0,
'closing_balance' => -99999,
],
[
'flow_date' => '2026-11-02',
'company_name' => '期初锁定公司',
'account_short' => '期初锁定账户',
'opening_balance' => 412.44,
'inflow' => 0,
'outflow' => 100,
'closing_balance' => 312.44,
],
]);
$html = $this->loginAs()->get($this->pageUrl([
'view' => 'accounts',
'account_category' => 'bank',
'account_search' => '期初锁定账户',
'period_from' => '2026-11-01',
'period_to' => '2026-11-30',
]))->assertOk()->getContent();
$this->assertStringContainsString('期初锁定账户', $html);
$this->assertStringContainsString('412.44', $html);
$this->assertStringNotContainsString('-99,999.00', $html);
}
public function test_wangshang_account_balance_uses_bank_bills_instead_of_transaction_flows(): void
{
$connection = DB::connection('business_mirror');

View File

@ -84,6 +84,18 @@ class FinanceLedgerCalculatorTest extends TestCase
$table->string('remark')->nullable();
$table->timestamps();
});
$schema->create('fin_daily_flow_overrides', function (Blueprint $table): void {
$table->increments('id');
$table->date('flow_date');
$table->string('account_short');
$table->decimal('opening_balance', 18, 2)->default(0);
$table->decimal('inflow', 18, 2)->default(0);
$table->decimal('outflow', 18, 2)->default(0);
$table->decimal('closing_balance', 18, 2)->default(0);
$table->string('remark')->nullable();
$table->string('updated_by')->nullable();
$table->timestamps();
});
$schema->create('fin_shops', function (Blueprint $table): void {
$table->increments('id');
$table->string('company_name');
@ -238,6 +250,55 @@ class FinanceLedgerCalculatorTest extends TestCase
);
}
public function test_later_locked_opening_is_not_changed_by_previous_period_overrides(): void
{
$db = DB::connection('business_mirror');
$db->table('fin_accounts')->insert([
'company_name' => '锁定期初公司',
'account_short' => '锁定期初账户',
'blocked_amount' => 0,
]);
$db->table('fin_account_opening')->insert([
['account_short' => '锁定期初账户', 'opening_date' => '2026-10-17', 'opening_balance' => 1000],
['account_short' => '锁定期初账户', 'opening_date' => '2026-11-01', 'opening_balance' => 412.44],
]);
$db->table('fin_transactions')->insert([
['txn_date' => '2026-10-18', 'account_short' => '锁定期初账户', 'source' => 'manual', 'source_value' => null, 'income' => 0, 'expense' => 2000],
['txn_date' => '2026-11-02', 'account_short' => '锁定期初账户', 'source' => 'manual', 'source_value' => null, 'income' => 0, 'expense' => 100],
]);
$db->table('fin_daily_flow_overrides')->insert([
'flow_date' => '2026-10-31',
'account_short' => '锁定期初账户',
'opening_balance' => -1000,
'inflow' => 0,
'outflow' => 0,
'closing_balance' => -99999,
'remark' => '上期手动调整',
'updated_by' => '测试人员',
'created_at' => now(),
'updated_at' => now(),
]);
app(FinanceLedgerCalculator::class)->recalculate();
$flows = $db->table('fin_daily_flows')
->where('account_short', '锁定期初账户')
->orderBy('flow_date')
->get();
$november = $flows->firstWhere('flow_date', '2026-11-01');
$this->assertNotNull($november);
$this->assertEqualsWithDelta(412.44, (float) $november->opening_balance, 0.001);
$this->assertEqualsWithDelta(412.44, (float) $november->closing_balance, 0.001);
$novemberTransaction = $flows->firstWhere('flow_date', '2026-11-02');
$this->assertEqualsWithDelta(412.44, (float) $novemberTransaction->opening_balance, 0.001);
$this->assertEqualsWithDelta(312.44, (float) $novemberTransaction->closing_balance, 0.001);
$this->assertEqualsWithDelta(
312.44,
(float) $db->table('fin_accounts')->where('account_short', '锁定期初账户')->value('current_balance'),
0.001,
);
}
public function test_direct_accounts_ignore_transaction_details_and_preserve_direct_amounts(): void
{
$db = DB::connection('business_mirror');

View File

@ -0,0 +1,106 @@
<?php
namespace Tests\Unit\EcommerceFinance;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\TestCase;
class LockFinanceLedgerMonthlyOpeningTest extends TestCase
{
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 = Schema::connection('business_mirror');
$schema->create('fin_accounts', function (Blueprint $table): void {
$table->increments('id');
$table->string('account_short');
$table->string('account_no')->nullable();
});
$schema->create('fin_account_opening', function (Blueprint $table): void {
$table->increments('id');
$table->string('account_short');
$table->date('opening_date');
$table->decimal('opening_balance', 18, 2);
$table->string('remark')->nullable();
$table->timestamps();
});
$schema->create('fin_transactions', function (Blueprint $table): void {
$table->increments('id');
$table->date('txn_date');
$table->string('source');
$table->string('source_value')->nullable();
$table->decimal('income', 18, 2)->default(0);
$table->decimal('expense', 18, 2)->default(0);
$table->decimal('balance', 18, 2)->nullable();
});
$schema->create('fin_bank_direct_bills', function (Blueprint $table): void {
$table->increments('id');
$table->string('account_no');
$table->date('txn_date');
$table->timestamp('txn_at')->nullable();
$table->decimal('income', 18, 2)->default(0);
$table->decimal('expense', 18, 2)->default(0);
$table->decimal('balance', 18, 2)->nullable();
});
$schema->create('fin_bank_direct_balance_snapshots', function (Blueprint $table): void {
$table->increments('id');
$table->string('account_no');
$table->date('balance_date');
$table->timestamp('balance_at')->nullable();
$table->decimal('account_balance', 18, 2)->nullable();
$table->decimal('available_balance', 18, 2);
});
$db = DB::connection('business_mirror');
$db->table('fin_accounts')->insert([
['account_short' => '有银行余额账户', 'account_no' => '6200000000000001'],
['account_short' => '无依据账户', 'account_no' => '6200000000000002'],
]);
$db->table('fin_transactions')->insert([
'txn_date' => '2026-10-31',
'source' => 'bank_statement',
'source_value' => '6200000000000001',
'income' => 0,
'expense' => 85000,
'balance' => 412.44,
]);
}
protected function tearDown(): void
{
DB::purge('business_mirror');
parent::tearDown();
}
public function test_it_locks_the_previous_month_last_real_balance(): void
{
$this->artisan('finance-ledger:lock-monthly-opening', [
'date' => '2026-11-01',
'--apply' => true,
])->expectsOutputToContain('新增:1')
->expectsOutputToContain('无真实余额 1')
->assertSuccessful();
$this->assertDatabaseHas('fin_account_opening', [
'account_short' => '有银行余额账户',
'opening_date' => '2026-11-01',
'opening_balance' => 412.44,
], 'business_mirror');
$this->assertDatabaseMissing('fin_account_opening', [
'account_short' => '无依据账户',
'opening_date' => '2026-11-01',
], 'business_mirror');
}
}