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 */ 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)) ?? ''; } }