From 1cb04adc7bd15ccc2cc11b79d88bca9e39ffeab3 Mon Sep 17 00:00:00 2001 From: 92451 <924518135@qq.com> Date: Tue, 27 Oct 2026 18:13:00 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=BA=97=E9=93=BA=E5=8F=B0=E8=B4=A6?= =?UTF-8?q?=E6=8E=A5=E5=85=A5=E6=AF=8F=E6=97=A5=E4=BD=99=E9=A2=9D=E3=80=81?= =?UTF-8?q?=E9=A2=84=E7=95=99=E6=A0=87=E5=87=86=E4=B8=8E=E9=A2=84=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 完成店铺台账每日余额来源、日期筛选、预留标准和连续3天预警。 Co-authored-by: 92451 <924518135@qq.com> Co-committed-by: 92451 <924518135@qq.com> --- .../WithdrawalBalanceAlertSynchronizer.php | 9 +- .../Commands/SyncFinanceLedgerShopData.php | 39 +++- deploy/activate-incremental-release.sh | 3 +- deploy/activate-release.sh | 3 +- .../JushuitanShopBalanceRepository.php | 42 +++- .../FinanceLedgerShopDataSynchronizer.php | 63 ++++- ...ceivingBillBalanceSnapshotSynchronizer.php | 218 ++++++++++++++++++ .../View/FinanceLedgerPageData.php | 168 +++++++++++++- .../pages/financial-ledger/ledger.blade.php | 16 +- .../FinanceLedgerHeaderControlsTest.php | 7 +- .../FinanceLedgerShopDirectoryTest.php | 75 ++++++ ...ingBillBalanceSnapshotSynchronizerTest.php | 118 ++++++++++ .../Deployment/BusinessMirrorScheduleTest.php | 9 +- 13 files changed, 728 insertions(+), 42 deletions(-) create mode 100644 modules/EcommerceFinance/Services/StoreReceivingBillBalanceSnapshotSynchronizer.php create mode 100644 tests/Feature/Business/StoreReceivingBillBalanceSnapshotSynchronizerTest.php diff --git a/app/Business/WithdrawalBalanceAlertSynchronizer.php b/app/Business/WithdrawalBalanceAlertSynchronizer.php index b5eb2dee..fc093735 100644 --- a/app/Business/WithdrawalBalanceAlertSynchronizer.php +++ b/app/Business/WithdrawalBalanceAlertSynchronizer.php @@ -45,7 +45,7 @@ class WithdrawalBalanceAlertSynchronizer /** * @return array{balance_date:string,dates:list,alerts:array>,created:int,updated:int} */ - public function syncForDate(int $companyId, string $balanceDate): array + public function syncForDate(int $companyId, string $balanceDate, ?string $sourceScope = null): array { $dates = self::datesEndingAt($balanceDate); $stores = StoreReceivingAccount::withoutGlobalScopes() @@ -64,7 +64,12 @@ class WithdrawalBalanceAlertSynchronizer ]; } - $balancesByDate = $this->shopBalances->matchesForStoresOnDates($stores, $dates); + $balancesByDate = $this->shopBalances->matchesForStoresOnDates( + $stores, + $dates, + null, + $sourceScope, + ); $reserveStandards = $stores->mapWithKeys( static fn (StoreReceivingAccount $store): array => [ (int) $store->id => WithdrawalReserveStandard::amountFor( diff --git a/app/Console/Commands/SyncFinanceLedgerShopData.php b/app/Console/Commands/SyncFinanceLedgerShopData.php index fd5d3bb2..6ab2863c 100644 --- a/app/Console/Commands/SyncFinanceLedgerShopData.php +++ b/app/Console/Commands/SyncFinanceLedgerShopData.php @@ -13,9 +13,10 @@ class SyncFinanceLedgerShopData extends Command {--to= : 提现业务日期止,最晚只同步到前一晚} {--days= : 只同步最近 N 天} {--rebuild : 先用最新余额快照清空并重建店铺台账} + {--balance-only : 只生成店铺余额快照并更新台账,不处理平台提现} {--no-recalculate : 只同步数据,不重算流水}'; - protected $description = '同步上一晚店铺余额,并把平台账单中的提现对应到财务账户收入'; + protected $description = '生成上一晚店铺余额快照(店铺收款账户账单优先),并把平台提现对应到财务账户收入'; public function handle(FinanceLedgerShopDataSynchronizer $synchronizer): int { @@ -26,12 +27,32 @@ class SyncFinanceLedgerShopData extends Command } try { - $result = $synchronizer->sync( - $from, - $this->option('to') ?: null, - ! $this->option('no-recalculate'), - (bool) $this->option('rebuild'), - ); + if ($this->option('balance-only')) { + $balance = $synchronizer->syncShopBalances( + $this->option('to') ?: null, + (bool) $this->option('rebuild'), + ); + $result = [ + 'balance' => $balance, + 'withdrawals' => [ + 'processed' => 0, + 'written' => 0, + 'upstream_duplicates' => 0, + 'unmatched' => 0, + 'account_missing' => 0, + 'income' => 0.0, + 'expense' => 0.0, + ], + 'recalculated' => null, + ]; + } else { + $result = $synchronizer->sync( + $from, + $this->option('to') ?: null, + ! $this->option('no-recalculate'), + (bool) $this->option('rebuild'), + ); + } } catch (Throwable $exception) { $this->error($exception->getMessage()); @@ -41,6 +62,8 @@ class SyncFinanceLedgerShopData extends Command $this->table(['项目', '值'], [ ['店铺余额日期', $result['balance']['date'] ?: '-'], ['余额源记录', $result['balance']['source']], + ['店铺账单余额来源', $result['balance']['receiving_bill']], + ['聚水潭补录来源', $result['balance']['jushuitan']], ['补充确认店铺', $result['balance']['added']], ['重建店铺台账', $result['balance']['rebuilt']], ['已更新店铺余额', $result['balance']['matched']], @@ -52,6 +75,8 @@ class SyncFinanceLedgerShopData extends Command ['账户缺失', $result['withdrawals']['account_missing']], ['提现收入合计', number_format((float) $result['withdrawals']['income'], 2)], ['提现冲回支出', number_format((float) $result['withdrawals']['expense'], 2)], + ['余额预警待办新增', $result['balance']['alerts']['created']], + ['余额预警待办更新', $result['balance']['alerts']['updated']], ['每日流水行数', $result['recalculated']['flows'] ?? '-'], ['PHP 峰值内存', number_format(memory_get_peak_usage(true) / 1048576, 1) . ' MiB'], ]); diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 8e31b999..38bdc078 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -225,8 +225,9 @@ CRON_TZ=Asia/Shanghai # 供应商管理每天北京时间 08:15 完整校准档案、合同、联系人与打款资料。 15 8 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-management --quiet >/dev/null 2>&1 */2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1 -# 财务台账:每天 02:30 同步 AI 库动账并重算流水;店铺台账默认不自动回填。 +# 财务台账:每天 02:30 同步 AI 库动账并重算流水;10:30 生成前一晚店铺余额快照。 30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=7 --merge --quiet >/dev/null 2>&1 +30 10 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-shop-data --balance-only --quiet >/dev/null 2>&1 # 财务流程明细每周完整校准一次,修正超过 48 小时重叠窗口才出现的上游改单或晚到付款。 20 2 * * 0 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --full --quiet >/dev/null 2>&1 # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index d78b7b3f..ac6e5f93 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -229,8 +229,9 @@ CRON_TZ=Asia/Shanghai # 供应商管理每天北京时间 08:15 完整校准档案、合同、联系人与打款资料。 15 8 * * * root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-supplier-management --quiet >/dev/null 2>&1 */2 * * * * root /usr/bin/flock -n /run/caiwu-esign-polling.lock /usr/bin/docker exec -u www-data caiwu_app php artisan esign:poll-signatures --quiet >/dev/null 2>&1 -# 财务台账:每天 02:30 同步 AI 库动账并重算流水;店铺台账默认不自动回填。 +# 财务台账:每天 02:30 同步 AI 库动账并重算流水;10:30 生成前一晚店铺余额快照。 30 2 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-rpt --days=7 --merge --quiet >/dev/null 2>&1 +30 10 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-shop-data --balance-only --quiet >/dev/null 2>&1 # 财务流程明细每周完整校准一次,修正超过 48 小时重叠窗口才出现的上游改单或晚到付款。 20 2 * * 0 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --full --quiet >/dev/null 2>&1 # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 diff --git a/modules/EcommerceFinance/Repositories/JushuitanShopBalanceRepository.php b/modules/EcommerceFinance/Repositories/JushuitanShopBalanceRepository.php index 17041217..195f97cb 100644 --- a/modules/EcommerceFinance/Repositories/JushuitanShopBalanceRepository.php +++ b/modules/EcommerceFinance/Repositories/JushuitanShopBalanceRepository.php @@ -24,11 +24,16 @@ class JushuitanShopBalanceRepository /** * @param iterable $stores - * @return array + * @return array */ - public function matchesForStores(iterable $stores, string $balanceDate): array + public function matchesForStores( + iterable $stores, + string $balanceDate, + ?string $dataSource = null, + ?string $sourceScope = null, + ): array { - $matches = $this->matchesForStoresOnDates($stores, [$balanceDate]); + $matches = $this->matchesForStoresOnDates($stores, [$balanceDate], $dataSource, $sourceScope); return array_map( static fn (array $dates): array => $dates[$balanceDate], @@ -39,12 +44,13 @@ class JushuitanShopBalanceRepository /** * @param iterable $stores * @param list $balanceDates - * @return array> + * @return array> */ public function matchesForStoresOnDates( iterable $stores, array $balanceDates, ?string $dataSource = null, + ?string $sourceScope = null, ): array { $stores = is_array($stores) ? array_values($stores) : iterator_to_array($stores, false); @@ -71,10 +77,14 @@ class JushuitanShopBalanceRepository $dataSource !== null, static fn ($query) => $query->where('data_source', $dataSource), ) + ->when( + $sourceScope !== null, + static fn ($query) => $query->where('source_scope', $sourceScope), + ) ->orderBy('id') ->get([ 'id', 'balance_date', 'data_source', 'source_platform', 'store_name', - 'normalized_store_name', 'platform_account_id', 'balance', + 'normalized_store_name', 'platform_account_id', 'balance', 'source_file_name', ]) ->groupBy(static fn (object $row): string => substr((string) $row->balance_date, 0, 10)); @@ -134,6 +144,7 @@ class JushuitanShopBalanceRepository 'source_store_name' => (string) $match->store_name, 'source_platform' => $match->source_platform === null ? null : (string) $match->source_platform, 'data_source' => (string) $match->data_source, + 'source_file_name' => $match->source_file_name === null ? null : (string) $match->source_file_name, ]; } } @@ -141,7 +152,7 @@ class JushuitanShopBalanceRepository return $result; } - public function countForDate(string $balanceDate): int + public function countForDate(string $balanceDate, ?string $sourceScope = null): int { if (! $this->hasTable()) { return 0; @@ -149,13 +160,17 @@ class JushuitanShopBalanceRepository return $this->connection->table(self::TABLE) ->where('balance_date', $balanceDate) + ->when( + $sourceScope !== null, + static fn ($query) => $query->where('source_scope', $sourceScope), + ) ->count(); } /** * 取不晚于今天的最新余额日期;没有任何快照时返回 null。 */ - public function latestBalanceDate(?CarbonInterface $today = null): ?string + public function latestBalanceDate(?CarbonInterface $today = null, ?string $sourceScope = null): ?string { if (! $this->hasTable()) { return null; @@ -164,6 +179,10 @@ class JushuitanShopBalanceRepository $today = ($today ?? now())->copy()->startOfDay(); $latest = $this->connection->table(self::TABLE) ->where('balance_date', '<=', $today->toDateString()) + ->when( + $sourceScope !== null, + static fn ($query) => $query->where('source_scope', $sourceScope), + ) ->max('balance_date'); return $latest === null ? null : substr((string) $latest, 0, 10); @@ -188,7 +207,7 @@ class JushuitanShopBalanceRepository * * @return list */ - public function availableDates(?CarbonInterface $today = null): array + public function availableDates(?CarbonInterface $today = null, ?string $sourceScope = null): array { if (! $this->hasTable()) { return []; @@ -198,6 +217,10 @@ class JushuitanShopBalanceRepository return $this->connection->table(self::TABLE) ->where('balance_date', '<=', $today->toDateString()) + ->when( + $sourceScope !== null, + static fn ($query) => $query->where('source_scope', $sourceScope), + ) ->distinct() ->orderByDesc('balance_date') ->pluck('balance_date') @@ -259,7 +282,7 @@ class JushuitanShopBalanceRepository return null; } - /** @return array{status:string,balance:null,source_store_name:null,source_platform:null,data_source:null} */ + /** @return array{status:string,balance:null,source_store_name:null,source_platform:null,data_source:null,source_file_name:null} */ private function emptyMatch(string $status): array { return [ @@ -268,6 +291,7 @@ class JushuitanShopBalanceRepository 'source_store_name' => null, 'source_platform' => null, 'data_source' => null, + 'source_file_name' => null, ]; } diff --git a/modules/EcommerceFinance/Services/FinanceLedgerShopDataSynchronizer.php b/modules/EcommerceFinance/Services/FinanceLedgerShopDataSynchronizer.php index 79a538ac..360e91d0 100644 --- a/modules/EcommerceFinance/Services/FinanceLedgerShopDataSynchronizer.php +++ b/modules/EcommerceFinance/Services/FinanceLedgerShopDataSynchronizer.php @@ -2,6 +2,7 @@ namespace Modules\EcommerceFinance\Services; +use App\Business\WithdrawalBalanceAlertSynchronizer; use App\Models\Business\StoreReceivingAccount; use Carbon\CarbonImmutable; use Illuminate\Database\ConnectionInterface; @@ -19,6 +20,7 @@ class FinanceLedgerShopDataSynchronizer DatabaseManager $databases, private readonly JushuitanShopBalanceRepository $shopBalances, private readonly BillingDetailsPageData $billingDetails, + private readonly StoreReceivingBillBalanceSnapshotSynchronizer $balanceSnapshots, ) { $this->connection = $databases->connection( (string) config('upstream_mirrors.connection', 'business_mirror'), @@ -27,7 +29,7 @@ class FinanceLedgerShopDataSynchronizer /** * @return array{ - * balance:array{date:?string,source:int,added:int,rebuilt:int,matched:int,amount:float}, + * balance:array{date:?string,source:int,receiving_bill:int,jushuitan:int,added:int,rebuilt:int,matched:int,amount:float,alerts:array{created:int,updated:int}}, * withdrawals:array{from:string,to:string,processed:int,written:int,upstream_duplicates:int,unmatched:int,account_missing:int,income:float,expense:float}, * recalculated:?array * } @@ -64,9 +66,25 @@ class FinanceLedgerShopDataSynchronizer public function syncShopBalances(?string $through = null, bool $rebuild = false): array { $through = $this->validDate($through) ?? now()->startOfDay()->subDay()->toDateString(); - $balanceDate = $this->shopBalances->latestBalanceDate(CarbonImmutable::parse($through)); + $snapshot = $this->balanceSnapshots->sync($through); + $balanceDate = $snapshot['total'] > 0 + ? (string) $snapshot['date'] + : $this->shopBalances->latestBalanceDate( + CarbonImmutable::parse($through), + StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE, + ); if ($balanceDate === null) { - return ['date' => null, 'source' => 0, 'added' => 0, 'rebuilt' => 0, 'matched' => 0, 'amount' => 0.0]; + return [ + 'date' => null, + 'source' => 0, + 'receiving_bill' => 0, + 'jushuitan' => 0, + 'added' => 0, + 'rebuilt' => 0, + 'matched' => 0, + 'amount' => 0.0, + 'alerts' => ['created' => 0, 'updated' => 0], + ]; } $rebuilt = $rebuild ? $this->rebuildShopLedger($balanceDate) : 0; @@ -79,7 +97,12 @@ class FinanceLedgerShopDataSynchronizer ->orderBy('id') ->get(['id', 'shop_name', 'platform', 'account_short']); } - $matches = $this->shopBalances->matchesForStores($shops, $balanceDate); + $matches = $this->shopBalances->matchesForStores( + $shops, + $balanceDate, + null, + StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE, + ); $updates = []; foreach ($matches as $id => $match) { if (($match['status'] ?? '') === 'matched' && $match['balance'] !== null) { @@ -109,13 +132,41 @@ class FinanceLedgerShopDataSynchronizer } } + $alerts = ['created' => 0, 'updated' => 0]; + if ($updates !== []) { + $companyIds = StoreReceivingAccount::withoutGlobalScopes() + ->whereNull('deleted_at') + ->distinct() + ->pluck('company_id') + ->filter() + ->map(static fn (mixed $id): int => (int) $id) + ->unique() + ->values(); + $alertSynchronizer = app(WithdrawalBalanceAlertSynchronizer::class); + foreach ($companyIds as $companyId) { + $result = $alertSynchronizer->syncForDate( + $companyId, + $balanceDate, + StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE, + ); + $alerts['created'] += $result['created']; + $alerts['updated'] += $result['updated']; + } + } + return [ 'date' => $balanceDate, - 'source' => $this->shopBalances->countForDate($balanceDate), + 'source' => $this->shopBalances->countForDate( + $balanceDate, + StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE, + ), + 'receiving_bill' => $snapshot['receiving_bill'], + 'jushuitan' => $snapshot['jushuitan'], 'added' => $added, 'rebuilt' => $rebuilt, 'matched' => count($updates), 'amount' => round(array_sum($updates), 2), + 'alerts' => $alerts, ]; } @@ -123,6 +174,7 @@ class FinanceLedgerShopDataSynchronizer { $sourceRows = $this->connection->table(JushuitanShopBalanceRepository::TABLE) ->where('balance_date', $balanceDate) + ->where('source_scope', StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE) ->orderByRaw("CASE WHEN data_source = 'jushuitan' THEN 0 ELSE 1 END") ->orderBy('id') ->get(['source_platform', 'store_name']); @@ -200,6 +252,7 @@ class FinanceLedgerShopDataSynchronizer { $sourceRows = $this->connection->table(JushuitanShopBalanceRepository::TABLE) ->where('balance_date', $balanceDate) + ->where('source_scope', StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE) ->get(['source_platform', 'store_name']); $existingExact = []; $existingNormalized = []; diff --git a/modules/EcommerceFinance/Services/StoreReceivingBillBalanceSnapshotSynchronizer.php b/modules/EcommerceFinance/Services/StoreReceivingBillBalanceSnapshotSynchronizer.php new file mode 100644 index 00000000..58b37466 --- /dev/null +++ b/modules/EcommerceFinance/Services/StoreReceivingBillBalanceSnapshotSynchronizer.php @@ -0,0 +1,218 @@ +connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * @return array{ + * date:string,total:int,receiving_bill:int,jushuitan:int, + * replaced:int,source_errors:list + * } + */ + public function sync(string $balanceDate): array + { + $date = CarbonImmutable::createFromFormat('!Y-m-d', $balanceDate); + if (! $date instanceof CarbonImmutable || $date->format('Y-m-d') !== $balanceDate) { + throw new InvalidArgumentException('店铺余额日期必须使用 YYYY-MM-DD 格式。'); + } + + $rows = []; + $sourceErrors = []; + $receivingBillCount = 0; + + foreach ([FinanceBillBalanceRepository::SCOPE_TAOBAO, FinanceBillBalanceRepository::SCOPE_JD_WALLET] as $scope) { + try { + foreach ($this->billBalances->latestBalances($scope, $balanceDate) as $source) { + $key = $this->key( + (string) ($source['source_platform'] ?? ''), + (string) ($source['store_name'] ?? ''), + ); + if ($key === '') { + continue; + } + + $rows[$key] = $this->snapshotRow( + $balanceDate, + self::DATA_SOURCE_RECEIVING_BILL, + $key, + $source, + ); + $receivingBillCount++; + } + } catch (Throwable $exception) { + report($exception); + $sourceErrors[] = $scope . ':' . $exception->getMessage(); + } + } + + $legacy = $this->connection->table(JushuitanShopBalanceRepository::TABLE) + ->where('balance_date', $balanceDate) + ->where('source_scope', '<>', self::SOURCE_SCOPE) + ->orderByRaw("CASE WHEN data_source = 'jushuitan' THEN 0 ELSE 1 END") + ->orderBy('id') + ->get(); + + $jushuitanCount = 0; + foreach ($legacy as $source) { + $key = $this->key( + (string) ($source->source_platform ?? ''), + (string) ($source->store_name ?? ''), + ); + if ($key === '' || isset($rows[$key])) { + continue; + } + + $dataSource = (string) ($source->data_source ?? JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN); + $rows[$key] = $this->snapshotRow($balanceDate, $dataSource, $key, (array) $source); + if ($dataSource === JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN) { + $jushuitanCount++; + } + } + + $rows = array_values($rows); + $existing = $this->connection->table(JushuitanShopBalanceRepository::TABLE) + ->where('balance_date', $balanceDate) + ->where('source_scope', self::SOURCE_SCOPE) + ->count(); + + if ($rows === []) { + return [ + 'date' => $balanceDate, + 'total' => 0, + 'receiving_bill' => 0, + 'jushuitan' => 0, + 'replaced' => $existing, + 'source_errors' => $sourceErrors, + ]; + } + + $this->connection->transaction(function () use ($balanceDate, $rows): void { + $this->connection->table(JushuitanShopBalanceRepository::TABLE) + ->where('balance_date', $balanceDate) + ->where('source_scope', self::SOURCE_SCOPE) + ->delete(); + + foreach (array_chunk($rows, 500) as $chunk) { + $this->connection->table(JushuitanShopBalanceRepository::TABLE)->insert($chunk); + } + }); + + return [ + 'date' => $balanceDate, + 'total' => count($rows), + 'receiving_bill' => $receivingBillCount, + 'jushuitan' => $jushuitanCount, + 'replaced' => $existing, + 'source_errors' => $sourceErrors, + ]; + } + + /** + * @param array $source + * @return array + */ + private function snapshotRow(string $balanceDate, string $dataSource, string $key, array $source): array + { + $now = now(); + $storeName = trim((string) ($source['store_name'] ?? '')); + $normalized = trim((string) ($source['normalized_store_name'] ?? '')); + if ($normalized === '') { + $normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName); + } + + $sourceFileName = trim((string) ($source['source_file_name'] ?? '')); + if ($sourceFileName === '') { + $sourceFileName = match ($dataSource) { + self::DATA_SOURCE_RECEIVING_BILL => '财务系统/店铺收款账户账单', + JushuitanShopBalanceRepository::DATA_SOURCE_FINANCE => '财务系统账单补录', + default => '聚水潭店铺余额', + }; + } + + return [ + 'balance_date' => $balanceDate, + 'source_scope' => self::SOURCE_SCOPE, + 'data_source' => $dataSource, + 'source_platform' => trim((string) ($source['source_platform'] ?? '')) ?: null, + 'store_name' => $storeName, + 'normalized_store_name' => $normalized, + 'platform_account_id' => trim((string) ($source['platform_account_id'] ?? '')) ?: null, + 'balance' => round((float) ($source['balance'] ?? 0), 6), + 'source_row_key' => hash('sha256', implode("\0", [ + self::SOURCE_SCOPE, + $dataSource, + $key, + ])), + 'source_file_name' => mb_substr($sourceFileName, 0, 255), + 'source_sha256' => hash('sha256', implode("\0", [ + $balanceDate, + $dataSource, + $key, + (string) ($source['occurred_at'] ?? ''), + number_format((float) ($source['balance'] ?? 0), 6, '.', ''), + ])), + 'imported_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ]; + } + + private function key(string $sourcePlatform, string $storeName): string + { + $storeName = trim($storeName); + if ($storeName === '') { + return ''; + } + + $platform = JushuitanShopBalanceRepository::platformKey($sourcePlatform) + ?? mb_strtolower(trim($sourcePlatform)); + $normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName); + + return $normalized === '' ? '' : $platform . "\0" . $normalized; + } + + public static function sourceLabel(?string $dataSource, ?string $sourceFileName = null): string + { + return match ($dataSource) { + self::DATA_SOURCE_RECEIVING_BILL => str_replace( + '财务系统/店铺收款账户账单/', + '店铺收款账户账单 · ', + trim((string) $sourceFileName) ?: '财务系统/店铺收款账户账单', + ), + JushuitanShopBalanceRepository::DATA_SOURCE_FINANCE => '财务系统账单补录', + JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN => '聚水潭店铺余额', + default => trim((string) $sourceFileName) ?: '未标明来源', + }; + } +} diff --git a/modules/EcommerceFinance/View/FinanceLedgerPageData.php b/modules/EcommerceFinance/View/FinanceLedgerPageData.php index 6fe76377..1f3d6eb8 100644 --- a/modules/EcommerceFinance/View/FinanceLedgerPageData.php +++ b/modules/EcommerceFinance/View/FinanceLedgerPageData.php @@ -2,6 +2,8 @@ namespace Modules\EcommerceFinance\View; +use App\Business\WithdrawalBalanceAlertSynchronizer; +use App\Business\WithdrawalReserveStandard; use App\Utilities\FinanceLedgerAccountStatus; use App\Utilities\FinanceLedgerAccountShouldKeep; use App\Utilities\FinanceLedgerAccountType; @@ -12,6 +14,7 @@ use Illuminate\Pagination\Paginator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Modules\EcommerceFinance\Services\FinanceLedgerShopDirectory; +use Modules\EcommerceFinance\Services\StoreReceivingBillBalanceSnapshotSynchronizer; use Modules\EcommerceFinance\Repositories\JushuitanShopBalanceRepository; /** @@ -35,6 +38,7 @@ class FinanceLedgerPageData public function __construct( private readonly FinanceLedgerShopDirectory $shopDirectory, + private readonly JushuitanShopBalanceRepository $shopBalances, ) { } @@ -59,7 +63,8 @@ class FinanceLedgerPageData 'ledgerAccountSummary' => $accounts['summary'], 'ledgerShops' => $shops['rows'], 'ledgerShopSummary' => $shops['summary'], - 'ledgerShopBalanceDate' => $this->latestShopBalanceDate(), + 'ledgerShopBalanceDate' => $shops['balance_date'] ?? null, + 'ledgerShopBalanceDates' => $shops['balance_dates'] ?? [], 'ledgerAvailableBreakdown' => $availableBreakdown, 'ledgerFlows' => $flows['rows'], 'ledgerFlowSummary' => $flows['summary'], @@ -226,16 +231,125 @@ class FinanceLedgerPageData { $directoryRows = $this->shopDirectory->rows(); - return $directoryRows === null - ? $this->shopsFromLedgerTable() - : $this->shopsFromStoreReport($directoryRows); + if ($directoryRows === null) { + return $this->shopsFromLedgerTable(); + } + + $context = $this->storeLedgerBalanceContext($directoryRows); + + return $this->shopsFromStoreReport($context['rows'], $context); + } + + /** + * 店铺余额按日期读取专用快照。店铺收款账户账单有真实余额的平台 + * 优先使用账单来源,其余平台由同步任务以聚水潭余额补足并明确标注。 + * + * @param list> $rows + * @return array{ + * rows:list>,balance_date:?string, + * balance_dates:list,alert_count:int + * } + */ + private function storeLedgerBalanceContext(array $rows): array + { + $latestAllowed = now()->startOfDay()->subDay(); + $balanceDates = $this->shopBalances->availableDates( + $latestAllowed, + StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE, + ); + $requestedDate = trim((string) request('shops_balance_date', '')); + $balanceDate = in_array($requestedDate, $balanceDates, true) + ? $requestedDate + : ($balanceDates[0] ?? null); + + $reserveStandards = []; + foreach ($rows as $index => $row) { + $reserveStandards[(int) ($row['id'] ?? $index)] = WithdrawalReserveStandard::amountFor( + (string) ($row['platform'] ?? ''), + (string) ($row['shop_name'] ?? ''), + ); + $rows[$index]['shop_balance_source'] = ($row['shop_balance_date'] ?? null) + ? StoreReceivingBillBalanceSnapshotSynchronizer::sourceLabel( + JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN, + ) + : '未同步'; + $rows[$index]['shop_balance_status'] = ($row['shop_balance_date'] ?? null) ? 'matched' : 'not_ready'; + $rows[$index]['reserve_standard'] = $reserveStandards[(int) ($row['id'] ?? $index)]; + $rows[$index]['balance_alert'] = '否'; + $rows[$index]['balance_alert_message'] = null; + } + + if ($balanceDate === null) { + return [ + 'rows' => $rows, + 'balance_date' => null, + 'balance_dates' => [], + 'alert_count' => 0, + ]; + } + + $stores = array_map( + static fn (array $row): object => (object) $row, + $rows, + ); + $historyDates = WithdrawalBalanceAlertSynchronizer::datesEndingAt($balanceDate); + $matches = $this->shopBalances->matchesForStoresOnDates( + $stores, + $historyDates, + null, + StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE, + ); + $alerts = WithdrawalBalanceAlertSynchronizer::detect( + $stores, + $matches, + array_map( + static fn (?int $amount): ?int => $amount === null ? null : (int) $amount, + $reserveStandards, + ), + $historyDates, + ); + + foreach ($rows as $index => $row) { + $id = (int) ($row['id'] ?? $index); + $match = $matches[$id][$balanceDate] ?? [ + 'status' => 'not_ready', + 'balance' => null, + 'data_source' => null, + 'source_file_name' => null, + ]; + $matched = ($match['status'] ?? '') === 'matched' && ($match['balance'] ?? null) !== null; + $rows[$index]['shop_balance'] = $matched ? round((float) $match['balance'], 2) : null; + $rows[$index]['shop_balance_date'] = $matched ? $balanceDate : null; + $rows[$index]['shop_balance_status'] = (string) ($match['status'] ?? 'not_ready'); + $rows[$index]['shop_balance_source'] = $matched + ? StoreReceivingBillBalanceSnapshotSynchronizer::sourceLabel( + $match['data_source'] ?? null, + $match['source_file_name'] ?? null, + ) + : '未同步'; + $alert = $alerts[$id] ?? null; + $rows[$index]['balance_alert'] = $alert === null ? '否' : '是'; + $rows[$index]['balance_alert_message'] = $alert['message'] ?? null; + } + + return [ + 'rows' => $rows, + 'balance_date' => $balanceDate, + 'balance_dates' => $balanceDates, + 'alert_count' => count($alerts), + ]; } /** * @param list> $rows - * @return array{rows:LengthAwarePaginator,summary:array{count:int,balance:float},overall_summary:array{count:int,balance:float}} + * @param array{balance_date:?string,balance_dates:list,alert_count:int}|array{} $context + * @return array{ + * rows:LengthAwarePaginator,summary:array{count:int,balance:float,alert_count:int}, + * overall_summary:array{count:int,balance:float},balance_date:?string, + * balance_dates:list,alert_count:int + * } */ - private function shopsFromStoreReport(array $rows): array + private function shopsFromStoreReport(array $rows, array $context = []): array { $overallSummary = [ 'count' => count($rows), @@ -289,6 +403,10 @@ class FinanceLedgerPageData static fn (array $row): float => (float) ($row['shop_balance'] ?? 0), $rows, )), 2), + 'alert_count' => count(array_filter( + $rows, + static fn (array $row): bool => ($row['balance_alert'] ?? '') === '是', + )), ]; $perPage = 100; $currentPage = Paginator::resolveCurrentPage('shops_page'); @@ -311,6 +429,9 @@ class FinanceLedgerPageData ))->withQueryString(), 'summary' => $summary, 'overall_summary' => $overallSummary, + 'balance_date' => $context['balance_date'] ?? null, + 'balance_dates' => $context['balance_dates'] ?? [], + 'alert_count' => $summary['alert_count'], ]; } @@ -340,6 +461,7 @@ class FinanceLedgerPageData $summary = [ 'count' => (clone $query)->count(), 'balance' => round((float) (clone $query)->sum('shop_balance'), 2), + 'alert_count' => 0, ]; $sorted = $this->applyLedgerHeaderSort($query, 'shops', $headerColumns); @@ -347,11 +469,35 @@ class FinanceLedgerPageData $query->orderBy('company_name')->orderBy('shop_name'); } + $rows = $query + ->paginate(100, ['*'], 'shops_page')->withQueryString(); + $rows->getCollection()->transform(static function ($row) { + $row->shop_balance_source = ($row->shop_balance_date ?? null) + ? StoreReceivingBillBalanceSnapshotSynchronizer::sourceLabel( + JushuitanShopBalanceRepository::DATA_SOURCE_JUSHUITAN, + ) + : '未同步'; + $row->shop_balance_status = ($row->shop_balance_date ?? null) ? 'matched' : 'not_ready'; + $row->reserve_standard = WithdrawalReserveStandard::amountFor( + (string) ($row->platform ?? ''), + (string) ($row->shop_name ?? ''), + ); + $row->balance_alert = '否'; + $row->balance_alert_message = null; + + return $row; + }); + return [ - 'rows' => $query - ->paginate(100, ['*'], 'shops_page')->withQueryString(), + 'rows' => $rows, 'summary' => $summary, 'overall_summary' => $overallSummary, + 'balance_date' => $this->latestShopBalanceDate(), + 'balance_dates' => $this->shopBalances->availableDates( + now()->startOfDay()->subDay(), + StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE, + ), + 'alert_count' => 0, ]; } @@ -369,7 +515,7 @@ class FinanceLedgerPageData 'bank_available' => $bankAvailable, 'shop_available' => $shopAvailable, 'total' => round($bankAvailable + $shopAvailable, 2), - 'shop_balance_date' => $this->latestShopBalanceDate(), + 'shop_balance_date' => $shops['balance_date'] ?? $this->latestShopBalanceDate(), ]; } @@ -617,6 +763,7 @@ class FinanceLedgerPageData } $latest = $this->db()->table(JushuitanShopBalanceRepository::TABLE) + ->where('source_scope', StoreReceivingBillBalanceSnapshotSynchronizer::SOURCE_SCOPE) ->where('balance_date', '<=', now()->startOfDay()->subDay()->toDateString()) ->max('balance_date'); @@ -851,7 +998,10 @@ class FinanceLedgerPageData 'store_manager' => ['sort' => 'shop_name', 'type' => 'text'], 'department_manager' => ['sort' => 'shop_name', 'type' => 'text'], 'payout_account' => ['sort' => 'payout_account', 'type' => 'text'], + 'shop_balance_source' => ['sort' => 'shop_balance_source', 'type' => 'text'], 'shop_balance' => ['sort' => 'shop_balance', 'type' => 'number'], + 'reserve_standard' => ['sort' => 'reserve_standard', 'type' => 'number'], + 'balance_alert' => ['sort' => 'balance_alert', 'type' => 'enum'], 'remark' => ['sort' => 'remark', 'type' => 'text'], ]; } diff --git a/resources/views/business/pages/financial-ledger/ledger.blade.php b/resources/views/business/pages/financial-ledger/ledger.blade.php index 34afa3d3..55ed8f6a 100644 --- a/resources/views/business/pages/financial-ledger/ledger.blade.php +++ b/resources/views/business/pages/financial-ledger/ledger.blade.php @@ -63,6 +63,7 @@ $tabUrl = static fn (string $tab): string => $ledgerPageUrl . '?' . http_build_query(['tab' => $tab]); $sourceLabels = ['dingtalk' => '钉钉审批', 'shop' => '店铺提现', 'shop_bill' => '店铺账单提现', 'payable' => '供应商应付', 'store' => '店铺开店', 'workorder' => '聚工单', 'manual' => '手工录入']; $shopBalanceDate = $ledgerShopBalanceDate ?? null; + $shopBalanceDates = $ledgerShopBalanceDates ?? []; $manualTransactionAccountOptions = $ledgerManualTransactionAccountOptions ?? []; $transactionAccountHeaderOptions = $ledgerTransactionAccountHeaderOptions ?? []; $transactionDateHeaderOptions = $ledgerTransactionDateHeaderOptions ?? []; @@ -118,7 +119,10 @@ ['store_manager', '店铺负责人', 'text'], ['department_manager', '部门负责人', 'text'], ['payout_account', '回款账户', 'text'], + ['shop_balance_source', '余额来源', 'text'], ['shop_balance', '店铺余额', 'number', ['headerClass' => 'num', 'align' => 'end']], + ['reserve_standard', '预留标准', 'number', ['headerClass' => 'num', 'align' => 'end']], + ['balance_alert', '余额预警', 'enum', ['options' => ['是' => '是', '否' => '否']]], ['remark', '备注', 'text'], ], 'flows' => [ @@ -445,6 +449,9 @@ .ledger-toast.is-visible { display:block; } .ledger-toast.is-error { border-color:var(--vip-danger, #B80000); color:var(--vip-danger, #B80000); } .ledger-source-tag { display:inline-flex; align-items:center; padding:.1rem .4rem; border-radius:.25rem; background:#f4f1eb; color:var(--vip-content-muted, #595959); font-size:.68rem; } + .ledger-source-tag--receiving { background:var(--vip-content-accent-soft, #F7F0DE); color:var(--vip-content-accent-dark, #856632); } + .ledger-balance-alert { display:inline-flex; align-items:center; gap:.2rem; color:var(--vip-warning, #935F07); font-size:.72rem; font-weight:600; white-space:nowrap; } + .ledger-balance-alert .material-icons-outlined { font-size:.95rem; } .ledger-mono { font-variant-numeric:tabular-nums; } @media (max-width: 900px) { .ledger-hero { align-items:flex-start; flex-direction:column; } .ledger-field { min-width:calc(50% - .5rem); } } @media (max-width: 760px) { .ledger-company-form__body { grid-template-columns:repeat(2, minmax(0, 1fr)); } .ledger-company-field--wide { grid-column:span 2; } } @@ -789,6 +796,7 @@
+
refresh重置
@if ($canEditAccountStatus) @@ -798,12 +806,12 @@ 同步上一晚余额与提现 - {{ $shopBalanceDate ? '店铺余额日期:' . $shopBalanceDate : '尚未同步店铺余额' }} + {{ $shopBalanceDate ? '店铺余额日期:' . $shopBalanceDate . ';店铺收款账户账单优先,其他平台标记为聚水潭补录。' : '尚未同步店铺余额' }} @endif -
店铺数{{ number_format((int) ($ledgerShopSummary['count'] ?? 0)) }}
店铺余额合计{{ $money($ledgerShopSummary['balance'] ?? 0) }}
余额口径{{ $shopBalanceDate ? '上一晚店铺余额(' . $shopBalanceDate . ')' : '尚未同步' }}
+
店铺数{{ number_format((int) ($ledgerShopSummary['count'] ?? 0)) }}
店铺余额合计{{ $money($ledgerShopSummary['balance'] ?? 0) }}
余额日期{{ $shopBalanceDate ?: '尚未同步' }}
连续3天预警{{ number_format((int) ($ledgerShopSummary['alert_count'] ?? 0)) }}
- +
@foreach ($ledgerTableHeaders['shops'] as $header) @include('business.pages.financial-ledger.partials.table-header', [ 'column' => $header[0], @@ -817,7 +825,7 @@ ]) @endforeach - @forelse ($ledgerShops as $row)@empty@endforelse + @forelse ($ledgerShops as $row)@empty@endforelse
{{ $row->platform }}{{ $row->shop_name }}{{ $row->company_name }}{{ $row->account_short }}{{ $row->status }}{{ $row->store_manager ?? '' }}{{ $row->department_manager ?? '' }}{{ $row->payout_account }}shop_balance_date ?? null) title="余额日期:{{ $row->shop_balance_date }}" @endif>{{ $money($row->shop_balance) }}{{ $row->remark }}
没有匹配的店铺数据。
{{ $row->platform }}{{ $row->shop_name }}{{ $row->company_name }}{{ $row->account_short }}{{ $row->status }}{{ $row->store_manager ?? '' }}{{ $row->department_manager ?? '' }}{{ $row->payout_account }}{{ $row->shop_balance_source ?? '未同步' }}shop_balance_date ?? null) title="余额日期:{{ $row->shop_balance_date }}" @endif>{{ ($row->shop_balance ?? null) === null ? '—' : $money($row->shop_balance) }}{{ ($row->reserve_standard ?? null) === null ? '—' : $money($row->reserve_standard) }}@if (($row->balance_alert ?? '否') === '是')预警@else否@endif{{ $row->remark }}
没有匹配的店铺数据。
@include('business.pages.financial-ledger.partials.pagination', [ 'rows' => $ledgerShops, diff --git a/tests/Feature/Business/FinanceLedgerHeaderControlsTest.php b/tests/Feature/Business/FinanceLedgerHeaderControlsTest.php index 84524ef2..0b30d853 100644 --- a/tests/Feature/Business/FinanceLedgerHeaderControlsTest.php +++ b/tests/Feature/Business/FinanceLedgerHeaderControlsTest.php @@ -130,8 +130,8 @@ class FinanceLedgerHeaderControlsTest extends FeatureTestCase $response = $this->loginAs()->get($this->pageUrl()); $html = $response->assertOk()->getContent(); - $this->assertSame(65, preg_match_all('/]*data-ledger-header-details/', $html)); - $this->assertSame(65, preg_match_all('/]*data-ledger-header-label/', $html)); + $this->assertSame(68, preg_match_all('/]*data-ledger-header-details/', $html)); + $this->assertSame(68, preg_match_all('/]*data-ledger-header-label/', $html)); $this->assertSame(2, preg_match_all('/