fix: 支持财务台账店铺台账重建 #623
@ -12,6 +12,7 @@ class SyncFinanceLedgerShopData extends Command
|
||||
{--from= : 提现业务日期起,默认从台账期初日}
|
||||
{--to= : 提现业务日期止,最晚只同步到前一晚}
|
||||
{--days= : 只同步最近 N 天}
|
||||
{--rebuild : 先用最新余额快照清空并重建店铺台账}
|
||||
{--no-recalculate : 只同步数据,不重算流水}';
|
||||
|
||||
protected $description = '同步上一晚店铺余额,并把平台账单中的提现对应到财务账户收入';
|
||||
@ -29,6 +30,7 @@ class SyncFinanceLedgerShopData extends Command
|
||||
$from,
|
||||
$this->option('to') ?: null,
|
||||
! $this->option('no-recalculate'),
|
||||
(bool) $this->option('rebuild'),
|
||||
);
|
||||
} catch (Throwable $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
@ -40,6 +42,7 @@ class SyncFinanceLedgerShopData extends Command
|
||||
['店铺余额日期', $result['balance']['date'] ?: '-'],
|
||||
['余额源记录', $result['balance']['source']],
|
||||
['补充确认店铺', $result['balance']['added']],
|
||||
['重建店铺台账', $result['balance']['rebuilt']],
|
||||
['已更新店铺余额', $result['balance']['matched']],
|
||||
['店铺余额合计', number_format((float) $result['balance']['amount'], 2)],
|
||||
['提现处理笔数', $result['withdrawals']['processed']],
|
||||
|
||||
@ -27,12 +27,12 @@ class FinanceLedgerShopDataSynchronizer
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* balance:array{date:?string,source:int,added:int,matched:int,amount:float},
|
||||
* balance:array{date:?string,source:int,added:int,rebuilt:int,matched:int,amount:float},
|
||||
* withdrawals:array{from:string,to:string,processed:int,written:int,upstream_duplicates:int,unmatched:int,account_missing:int,income:float,expense:float},
|
||||
* recalculated:?array
|
||||
* }
|
||||
*/
|
||||
public function sync(?string $from = null, ?string $to = null, bool $recalculate = true): array
|
||||
public function sync(?string $from = null, ?string $to = null, bool $recalculate = true, bool $rebuild = false): array
|
||||
{
|
||||
$previousNight = now()->startOfDay()->subDay()->toDateString();
|
||||
$to = $this->validDate($to) ?? $previousNight;
|
||||
@ -45,7 +45,7 @@ class FinanceLedgerShopDataSynchronizer
|
||||
$from = $to;
|
||||
}
|
||||
|
||||
$balance = $this->syncShopBalances($to);
|
||||
$balance = $this->syncShopBalances($to, $rebuild);
|
||||
$withdrawals = $this->syncWithdrawals($from, $to);
|
||||
$recalculated = $recalculate && ($balance['matched'] > 0 || $withdrawals['written'] > 0)
|
||||
? app(FinanceLedgerCalculator::class)->recalculate()
|
||||
@ -59,20 +59,21 @@ class FinanceLedgerShopDataSynchronizer
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{date:?string,source:int,added:int,matched:int,amount:float}
|
||||
* @return array{date:?string,source:int,added:int,rebuilt:int,matched:int,amount:float}
|
||||
*/
|
||||
public function syncShopBalances(?string $through = null): array
|
||||
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));
|
||||
if ($balanceDate === null) {
|
||||
return ['date' => null, 'source' => 0, 'added' => 0, 'matched' => 0, 'amount' => 0.0];
|
||||
return ['date' => null, 'source' => 0, 'added' => 0, 'rebuilt' => 0, 'matched' => 0, 'amount' => 0.0];
|
||||
}
|
||||
|
||||
$rebuilt = $rebuild ? $this->rebuildShopLedger($balanceDate) : 0;
|
||||
$shops = $this->connection->table('fin_shops')
|
||||
->orderBy('id')
|
||||
->get(['id', 'shop_name', 'platform', 'account_short']);
|
||||
$added = $this->addConfirmedMissingShops($balanceDate, $shops);
|
||||
$added = $rebuilt > 0 ? 0 : $this->addConfirmedMissingShops($balanceDate, $shops);
|
||||
if ($added > 0) {
|
||||
$shops = $this->connection->table('fin_shops')
|
||||
->orderBy('id')
|
||||
@ -112,11 +113,89 @@ class FinanceLedgerShopDataSynchronizer
|
||||
'date' => $balanceDate,
|
||||
'source' => $this->shopBalances->countForDate($balanceDate),
|
||||
'added' => $added,
|
||||
'rebuilt' => $rebuilt,
|
||||
'matched' => count($updates),
|
||||
'amount' => round(array_sum($updates), 2),
|
||||
];
|
||||
}
|
||||
|
||||
private function rebuildShopLedger(string $balanceDate): int
|
||||
{
|
||||
$sourceRows = $this->connection->table(JushuitanShopBalanceRepository::TABLE)
|
||||
->where('balance_date', $balanceDate)
|
||||
->orderByRaw("CASE WHEN data_source = 'jushuitan' THEN 0 ELSE 1 END")
|
||||
->orderBy('id')
|
||||
->get(['source_platform', 'store_name']);
|
||||
if ($sourceRows->isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$receivingByNormalized = [];
|
||||
foreach (StoreReceivingAccount::withoutGlobalScopes()->whereNull('deleted_at')->get() as $account) {
|
||||
$name = trim((string) ($account->erp_store_name ?? ''));
|
||||
if ($name !== '') {
|
||||
$receivingByNormalized[JushuitanShopBalanceRepository::normalizeStoreName($name)][] = $account;
|
||||
}
|
||||
}
|
||||
$accountShortByShop = $this->connection->table('fin_account_map')
|
||||
->where('source', 'shop')
|
||||
->whereNotNull('account_short')
|
||||
->where('account_short', '<>', '')
|
||||
->pluck('account_short', 'source_value');
|
||||
|
||||
$now = now();
|
||||
$seen = [];
|
||||
$rows = [];
|
||||
foreach ($sourceRows as $source) {
|
||||
$name = trim((string) ($source->store_name ?? ''));
|
||||
if ($name === '' || isset($seen[$name])) {
|
||||
continue;
|
||||
}
|
||||
$seen[$name] = true;
|
||||
$normalized = JushuitanShopBalanceRepository::normalizeStoreName($name);
|
||||
$receivingMatches = $receivingByNormalized[$normalized] ?? [];
|
||||
$receiving = count($receivingMatches) === 1 ? $receivingMatches[0] : null;
|
||||
$accountShort = trim((string) ($accountShortByShop[$name] ?? ''));
|
||||
$bankLastFour = $receiving === null ? '' : trim((string) ($receiving->bank_card_last_four ?? ''));
|
||||
$payout = $receiving === null ? '' : trim((string) ($receiving->withdrawal_account_name ?? ''));
|
||||
if ($payout !== '' && $bankLastFour !== '') {
|
||||
$payout .= ' ' . $bankLastFour;
|
||||
}
|
||||
$row = [
|
||||
'shop_name' => mb_substr($name, 0, 200),
|
||||
'platform' => mb_substr($this->financialPlatform((string) ($source->source_platform ?? ''), $name), 0, 50),
|
||||
'company_name' => $receiving === null
|
||||
? null
|
||||
: (mb_substr(trim((string) ($receiving->store_entity_name ?? '')), 0, 100) ?: null),
|
||||
'account_short' => $accountShort === '' ? null : mb_substr($accountShort, 0, 100),
|
||||
'status' => $receiving === null ? '待确认' : $this->financialShopStatus($receiving->store_status),
|
||||
'payout_account' => $payout === '' ? null : mb_substr($payout, 0, 100),
|
||||
'shop_balance' => 0,
|
||||
'remark' => $receiving === null
|
||||
? '由聚水潭店铺余额快照重新生成,待确认回款账户'
|
||||
: '由店铺主数据与最新店铺余额快照重新生成',
|
||||
'created_at' => $now,
|
||||
'updated_at' => $now,
|
||||
];
|
||||
if ($this->connection->getSchemaBuilder()->hasColumn('fin_shops', 'shop_balance_date')) {
|
||||
$row['shop_balance_date'] = null;
|
||||
}
|
||||
$rows[] = $row;
|
||||
}
|
||||
if ($rows === []) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return $this->connection->transaction(function () use ($rows): int {
|
||||
$this->connection->table('fin_shops')->delete();
|
||||
foreach (array_chunk($rows, 200) as $chunk) {
|
||||
$this->connection->table('fin_shops')->insert($chunk);
|
||||
}
|
||||
|
||||
return count($rows);
|
||||
});
|
||||
}
|
||||
|
||||
private function addConfirmedMissingShops(string $balanceDate, $existingShops): int
|
||||
{
|
||||
$sourceRows = $this->connection->table(JushuitanShopBalanceRepository::TABLE)
|
||||
@ -450,6 +529,16 @@ class FinanceLedgerShopDataSynchronizer
|
||||
return $sourcePlatform !== '' ? $sourcePlatform : '未填写';
|
||||
}
|
||||
|
||||
private function financialShopStatus(mixed $status): string
|
||||
{
|
||||
return match (trim((string) $status)) {
|
||||
'正常', '在营' => '在营',
|
||||
'关店中', '暂停' => '暂停',
|
||||
'已关店', '已注销' => '已注销',
|
||||
default => trim((string) $status) ?: '待确认',
|
||||
};
|
||||
}
|
||||
|
||||
private function validDate(?string $value): ?string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
|
||||
@ -115,6 +115,79 @@ class FinanceLedgerShopDataSynchronizerTest extends FeatureTestCase
|
||||
$this->assertStringContainsString('待确认回款账户', (string) $shop->remark);
|
||||
}
|
||||
|
||||
public function test_rebuild_clears_stale_shop_ledger_and_reloads_latest_snapshot(): void
|
||||
{
|
||||
Carbon::setTestNow('2026-10-26 09:00:00');
|
||||
$connection = DB::connection('business_mirror');
|
||||
$connection->table('fin_shops')->insert([
|
||||
'shop_name' => '历史脏数据店',
|
||||
'platform' => '天猫',
|
||||
'shop_balance' => 99,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
StoreReceivingAccount::withoutGlobalScopes()->create([
|
||||
'company_id' => $this->company->id,
|
||||
'store_platform' => '拼多多',
|
||||
'store_name' => '拼多多-台账重建店',
|
||||
'store_entity_name' => '台账重建主体有限公司',
|
||||
'withdrawal_account_name' => '台账重建回款户',
|
||||
'bank_card_last_four' => '7788',
|
||||
'store_status' => '正常',
|
||||
]);
|
||||
$connection->table('fin_account_map')->insert([
|
||||
'source' => 'shop',
|
||||
'source_value' => '拼多多-台账重建店',
|
||||
'account_short' => '重建账户',
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
$this->insertBalance(
|
||||
$connection,
|
||||
'2026-10-25',
|
||||
'拼多多-台账重建店',
|
||||
1588.66,
|
||||
'拼多多',
|
||||
);
|
||||
|
||||
$result = app(FinanceLedgerShopDataSynchronizer::class)
|
||||
->syncShopBalances('2026-10-25', true);
|
||||
|
||||
$this->assertSame(1, $result['rebuilt']);
|
||||
$this->assertSame(1, $result['matched']);
|
||||
$this->assertDatabaseMissing('fin_shops', ['shop_name' => '历史脏数据店'], 'business_mirror');
|
||||
$shop = $connection->table('fin_shops')->first();
|
||||
$this->assertSame('拼多多-台账重建店', $shop->shop_name);
|
||||
$this->assertSame('拼多多', $shop->platform);
|
||||
$this->assertSame('台账重建主体有限公司', $shop->company_name);
|
||||
$this->assertSame('重建账户', $shop->account_short);
|
||||
$this->assertSame('在营', $shop->status);
|
||||
$this->assertSame('台账重建回款户 7788', $shop->payout_account);
|
||||
$this->assertSame(1588.66, (float) $shop->shop_balance);
|
||||
$this->assertSame('2026-10-25', substr((string) $shop->shop_balance_date, 0, 10));
|
||||
}
|
||||
|
||||
public function test_rebuild_without_balance_snapshot_keeps_existing_shop_ledger(): void
|
||||
{
|
||||
$connection = DB::connection('business_mirror');
|
||||
$connection->table('fin_shops')->insert([
|
||||
'shop_name' => '保留店铺',
|
||||
'platform' => '天猫',
|
||||
'shop_balance' => 88,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
|
||||
$result = app(FinanceLedgerShopDataSynchronizer::class)
|
||||
->syncShopBalances('2026-10-25', true);
|
||||
|
||||
$this->assertSame(0, $result['rebuilt']);
|
||||
$this->assertDatabaseHas('fin_shops', [
|
||||
'shop_name' => '保留店铺',
|
||||
'shop_balance' => 88,
|
||||
], 'business_mirror');
|
||||
}
|
||||
|
||||
public function test_withdrawal_rows_are_mapped_to_shop_account_income_and_are_idempotent(): void
|
||||
{
|
||||
Carbon::setTestNow('2026-10-24 09:00:00');
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user