374 lines
14 KiB
PHP
374 lines
14 KiB
PHP
<?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']
|
|
. ';保留手工期初:' . $result['preserved_existing']
|
|
);
|
|
$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 = [];
|
|
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;
|
|
}
|
|
}
|
|
$bankBillBefore = [];
|
|
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;
|
|
}
|
|
}
|
|
$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;
|
|
}
|
|
}
|
|
$openingBefore = $connection->table('fin_account_opening')
|
|
->where('opening_date', '<', $date->toDateString())
|
|
->orderBy('opening_date')
|
|
->orderBy('id')
|
|
->get(['account_short', 'opening_date', 'opening_balance'])
|
|
->keyBy('account_short');
|
|
$latestTransactionByShort = [];
|
|
$latestTransactionByAccountNo = [];
|
|
foreach ($connection->table('fin_transactions')
|
|
->whereNull('deleted_at')
|
|
->where('txn_date', '<=', $previousEnd->toDateString())
|
|
->cursor() as $row) {
|
|
$transactionDate = substr((string) $row->txn_date, 0, 10);
|
|
$short = trim((string) ($row->account_short ?? ''));
|
|
if ($short !== ''
|
|
&& ($latestTransactionByShort[$short] ?? '') < $transactionDate) {
|
|
$latestTransactionByShort[$short] = $transactionDate;
|
|
}
|
|
$accountNo = $this->accountNo($row->source_value ?? null);
|
|
if ($accountNo !== ''
|
|
&& ($latestTransactionByAccountNo[$accountNo] ?? '') < $transactionDate) {
|
|
$latestTransactionByAccountNo[$accountNo] = $transactionDate;
|
|
}
|
|
}
|
|
$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, $sourceDate] = $this->actualOpening(
|
|
$accountNo,
|
|
$bankStatementBefore,
|
|
$bankBillBefore,
|
|
$snapshotBefore,
|
|
);
|
|
[$carriedBalance, $carriedSource, $carriedSourceDate] = $this->carriedOpening(
|
|
$short,
|
|
$accountNo,
|
|
$openingBefore,
|
|
$latestTransactionByShort,
|
|
$latestTransactionByAccountNo,
|
|
);
|
|
if ($carriedBalance !== null
|
|
&& ($balance === null || $carriedSourceDate > $sourceDate)) {
|
|
$balance = $carriedBalance;
|
|
$source = $carriedSource;
|
|
$sourceDate = $carriedSourceDate;
|
|
}
|
|
if ($balance === null) {
|
|
$byShort[$short][] = [
|
|
'account_id' => (int) $account->id,
|
|
'balance' => null,
|
|
'source' => '',
|
|
'source_date' => '',
|
|
];
|
|
continue;
|
|
}
|
|
$byShort[$short][] = [
|
|
'account_id' => (int) $account->id,
|
|
'balance' => $balance,
|
|
'source' => $source,
|
|
'source_date' => $sourceDate,
|
|
];
|
|
}
|
|
|
|
$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'],
|
|
'source_date' => (string) $items[0]['source_date'],
|
|
];
|
|
}
|
|
|
|
$created = 0;
|
|
$updated = 0;
|
|
$unchanged = 0;
|
|
$preservedExisting = 0;
|
|
if ($apply) {
|
|
$connection->transaction(function () use (
|
|
$connection,
|
|
$date,
|
|
$candidates,
|
|
$existingOpenings,
|
|
&$created,
|
|
&$updated,
|
|
&$unchanged,
|
|
&$preservedExisting,
|
|
): void {
|
|
foreach ($candidates as $short => $candidate) {
|
|
$existing = $existingOpenings->get($short);
|
|
$remark = '系统锁定:' . $candidate['source_date'] . ' 最后一笔实际余额';
|
|
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 (! str_starts_with((string) $existing->remark, '系统锁定:')) {
|
|
$preservedExisting++;
|
|
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,
|
|
'preserved_existing' => $preservedExisting,
|
|
'skipped_no_basis' => $skippedNoBasis,
|
|
'skipped_conflicts' => $skippedConflicts,
|
|
'candidates' => array_map(
|
|
static fn (string $short, array $candidate): array => [
|
|
'account_short' => $short,
|
|
...$candidate,
|
|
],
|
|
array_keys($candidates),
|
|
array_values($candidates),
|
|
),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @return array{0:?float,1:string,2:string}
|
|
*/
|
|
private function actualOpening(
|
|
string $accountNo,
|
|
array $bankStatementBefore,
|
|
array $bankBillBefore,
|
|
array $snapshotBefore,
|
|
): array {
|
|
if ($accountNo === '') {
|
|
return [null, '', ''];
|
|
}
|
|
if (isset($bankStatementBefore[$accountNo])) {
|
|
$row = $bankStatementBefore[$accountNo];
|
|
|
|
return [
|
|
round((float) $row->balance, 2),
|
|
'bank_statement',
|
|
substr((string) $row->txn_date, 0, 10),
|
|
];
|
|
}
|
|
if (isset($bankBillBefore[$accountNo])) {
|
|
$row = $bankBillBefore[$accountNo];
|
|
|
|
return [
|
|
round((float) $row->balance, 2),
|
|
'bank_bill',
|
|
substr((string) $row->txn_date, 0, 10),
|
|
];
|
|
}
|
|
if (isset($snapshotBefore[$accountNo])) {
|
|
$row = $snapshotBefore[$accountNo];
|
|
|
|
return [
|
|
round((float) ($row->account_balance ?? $row->available_balance), 2),
|
|
'balance_snapshot',
|
|
substr((string) $row->balance_date, 0, 10),
|
|
];
|
|
}
|
|
|
|
return [null, '', ''];
|
|
}
|
|
|
|
/**
|
|
* @return array{0:?float,1:string,2:string}
|
|
*/
|
|
private function carriedOpening(
|
|
string $accountShort,
|
|
string $accountNo,
|
|
mixed $openingBefore,
|
|
array $latestTransactionByShort,
|
|
array $latestTransactionByAccountNo,
|
|
): array {
|
|
$opening = $openingBefore->get($accountShort);
|
|
if ($opening === null) {
|
|
return [null, '', ''];
|
|
}
|
|
|
|
$openingDate = substr((string) $opening->opening_date, 0, 10);
|
|
$latestTransactionDate = max(
|
|
(string) ($latestTransactionByShort[$accountShort] ?? ''),
|
|
$accountNo !== '' ? (string) ($latestTransactionByAccountNo[$accountNo] ?? '') : '',
|
|
);
|
|
if ($latestTransactionDate !== '' && $latestTransactionDate >= $openingDate) {
|
|
return [null, '', ''];
|
|
}
|
|
|
|
return [
|
|
round((float) $opening->opening_balance, 2),
|
|
'opening_carry_forward',
|
|
$openingDate,
|
|
];
|
|
}
|
|
|
|
private function accountNo(mixed $value): string
|
|
{
|
|
return preg_replace('/\D+/', '', trim((string) $value)) ?? '';
|
|
}
|
|
}
|