fix(账户余额): 优化平台每日余额汇总 (#1683)

This commit is contained in:
qiuxiang 2026-12-03 12:02:18 +08:00
parent 2c1b5dd0e4
commit 4c1fdce0c6
2 changed files with 132 additions and 37 deletions

View File

@ -367,7 +367,14 @@ class StoreReceivingBalanceOverviewService
$slug = (string) $platform['slug'];
$activityAvailable = true;
try {
$activity = $this->dailyActivity($slug, $periodStart, $periodEnd, $dates);
// 平台汇总不需要店铺维度,避免在百万级账单表上做多余分组。
$activity = $this->dailyActivity(
$slug,
$periodStart,
$periodEnd,
$dates,
false,
);
} catch (Throwable $exception) {
report($exception);
$activity = ['by_date' => [], 'by_store' => []];
@ -661,7 +668,12 @@ class StoreReceivingBalanceOverviewService
/**
* @return iterable<int,array<string,mixed>>
*/
protected function fetchPlatformDailyRows(string $platform, string $start, string $end): iterable
protected function fetchPlatformDailyRows(
string $platform,
string $start,
string $end,
bool $includeByStore = true,
): iterable
{
$connection = $this->mirrorConnection();
$from = $start . ' 00:00:00';
@ -676,7 +688,12 @@ class StoreReceivingBalanceOverviewService
->orWhere('store_name', 'not like', self::OVERVIEW_EXCLUDED_TAOBAO_ALIPAY_STORE_PREFIX . '%');
});
return $this->streamGroupedDailyRows($query, 'income_amount', 'expense_amount');
return $this->streamGroupedDailyRows(
$query,
'income_amount',
'expense_amount',
$includeByStore,
);
}
if ($platform === 'taobao-wechat') {
@ -684,7 +701,12 @@ class StoreReceivingBalanceOverviewService
->where('occurred_at', '>=', $from)
->where('occurred_at', '<', $until);
return $this->streamGroupedDailyRows($query, 'income_amount', 'expense_amount');
return $this->streamGroupedDailyRows(
$query,
'income_amount',
'expense_amount',
$includeByStore,
);
}
if ($platform === 'pinduoduo') {
@ -692,7 +714,12 @@ class StoreReceivingBalanceOverviewService
->where('occurred_at', '>=', $from)
->where('occurred_at', '<', $until);
return $this->streamGroupedDailyRows($query, 'income_amount', 'expense_amount');
return $this->streamGroupedDailyRows(
$query,
'income_amount',
'expense_amount',
$includeByStore,
);
}
if ($platform === 'jd-wallet') {
@ -712,7 +739,12 @@ class StoreReceivingBalanceOverviewService
->where('occurred_at', '>=', $from)
->where('occurred_at', '<', $until);
return $this->streamGroupedDailyRows($query, 'income', 'expense');
return $this->streamGroupedDailyRows(
$query,
'income',
'expense',
$includeByStore,
);
}
if ($platform === 'douyin') {
@ -731,7 +763,12 @@ class StoreReceivingBalanceOverviewService
->where('occurred_at', '>=', $from)
->where('occurred_at', '<', $until);
return $this->streamGroupedDailyRows($query, 'income', 'expense');
return $this->streamGroupedDailyRows(
$query,
'income',
'expense',
$includeByStore,
);
}
return $this->rawDailyRows($platform, $start, $end);
@ -754,12 +791,21 @@ class StoreReceivingBalanceOverviewService
$query->whereRaw($settlePeriod . ' >= ?', [substr($start, 0, 7)])
->whereRaw($settlePeriod . ' <= ?', [substr($end, 0, 7)]);
$query->selectRaw(
$settlePeriod . ' AS settle_period, '
. "COALESCE(TRIM(store_name), '') AS store_name, "
. 'COALESCE(SUM(income), 0) AS income, '
. 'COALESCE(SUM(expense), 0) AS expense'
)->groupByRaw($settlePeriod . ', store_name');
if ($includeByStore) {
$query->selectRaw(
$settlePeriod . ' AS settle_period, '
. "COALESCE(TRIM(store_name), '') AS store_name, "
. 'COALESCE(SUM(income), 0) AS income, '
. 'COALESCE(SUM(expense), 0) AS expense'
)->groupByRaw($settlePeriod . ', store_name');
} else {
$query->selectRaw(
$settlePeriod . ' AS settle_period, '
. "'' AS store_name, "
. 'COALESCE(SUM(income), 0) AS income, '
. 'COALESCE(SUM(expense), 0) AS expense'
)->groupByRaw($settlePeriod);
}
return $this->normalizeSettlementDailyRows($query->cursor(), $end);
}
@ -767,12 +813,21 @@ class StoreReceivingBalanceOverviewService
$query->where('occurred_at', '>=', $from)
->where('occurred_at', '<', $until);
$query->selectRaw(
'DATE(occurred_at) AS occurred_at, '
. "COALESCE(TRIM(store_name), '') AS store_name, "
. 'COALESCE(SUM(income), 0) AS income, '
. 'COALESCE(SUM(expense), 0) AS expense'
)->groupByRaw('DATE(occurred_at), store_name');
if ($includeByStore) {
$query->selectRaw(
'DATE(occurred_at) AS occurred_at, '
. "COALESCE(TRIM(store_name), '') AS store_name, "
. 'COALESCE(SUM(income), 0) AS income, '
. 'COALESCE(SUM(expense), 0) AS expense'
)->groupByRaw('DATE(occurred_at), store_name');
} else {
$query->selectRaw(
'DATE(occurred_at) AS occurred_at, '
. "'' AS store_name, "
. 'COALESCE(SUM(income), 0) AS income, '
. 'COALESCE(SUM(expense), 0) AS expense'
)->groupByRaw('DATE(occurred_at)');
}
return $this->normalizeDailyRows($query->cursor());
}
@ -782,19 +837,30 @@ class StoreReceivingBalanceOverviewService
/**
* Aggregate a platform mirror table in MySQL instead of streaming raw bills
* into PHP. A monthly result is bounded by stores × days, not bill rows.
* into PHP. A monthly platform result is bounded by days; the store view is
* bounded by stores × days.
*/
private function streamGroupedDailyRows(
Builder $query,
string $incomeColumn,
string $expenseColumn,
bool $includeByStore = true,
): iterable {
$query->selectRaw(
'DATE(occurred_at) AS occurred_at, '
. "COALESCE(TRIM(store_name), '') AS store_name, "
. "COALESCE(SUM($incomeColumn), 0) AS income, "
. "COALESCE(SUM($expenseColumn), 0) AS expense"
)->groupByRaw('DATE(occurred_at), store_name');
if ($includeByStore) {
$query->selectRaw(
'DATE(occurred_at) AS occurred_at, '
. "COALESCE(TRIM(store_name), '') AS store_name, "
. "COALESCE(SUM($incomeColumn), 0) AS income, "
. "COALESCE(SUM($expenseColumn), 0) AS expense"
)->groupByRaw('DATE(occurred_at), store_name');
} else {
$query->selectRaw(
'DATE(occurred_at) AS occurred_at, '
. "'' AS store_name, "
. "COALESCE(SUM($incomeColumn), 0) AS income, "
. "COALESCE(SUM($expenseColumn), 0) AS expense"
)->groupByRaw('DATE(occurred_at)');
}
return $this->normalizeDailyRows($query->cursor());
}
@ -881,29 +947,42 @@ class StoreReceivingBalanceOverviewService
* @param list<string> $dates
* @return array{by_date:array<string,array{income:float,expense:float}>,by_store:array<string,array<string,array{income:float,expense:float}>>}
*/
private function dailyActivity(string $platform, string $start, string $end, array $dates): array
private function dailyActivity(
string $platform,
string $start,
string $end,
array $dates,
bool $includeByStore = true,
): array
{
$dateSet = array_fill_keys($dates, true);
$byDate = [];
$byStore = [];
foreach ($this->fetchPlatformDailyRows($platform, $start, $end) as $row) {
foreach ($this->fetchPlatformDailyRows(
$platform,
$start,
$end,
$includeByStore,
) as $row) {
$date = substr(trim((string) ($row['occurred_at'] ?? '')), 0, 10);
if (! isset($dateSet[$date])) {
continue;
}
$storeKey = $this->dailyStoreKey($platform, (string) ($row['store_name'] ?? ''));
$incomeCents = (int) round((float) ($row['income'] ?? 0) * 100);
$expenseCents = (int) round((float) ($row['expense'] ?? 0) * 100);
$byDate[$date]['income_cents'] = ($byDate[$date]['income_cents'] ?? 0) + $incomeCents;
$byDate[$date]['expense_cents'] = ($byDate[$date]['expense_cents'] ?? 0) + $expenseCents;
$byStore[$storeKey][$date]['income_cents'] = (
$byStore[$storeKey][$date]['income_cents'] ?? 0
) + $incomeCents;
$byStore[$storeKey][$date]['expense_cents'] = (
$byStore[$storeKey][$date]['expense_cents'] ?? 0
) + $expenseCents;
if ($includeByStore) {
$storeKey = $this->dailyStoreKey($platform, (string) ($row['store_name'] ?? ''));
$byStore[$storeKey][$date]['income_cents'] = (
$byStore[$storeKey][$date]['income_cents'] ?? 0
) + $incomeCents;
$byStore[$storeKey][$date]['expense_cents'] = (
$byStore[$storeKey][$date]['expense_cents'] ?? 0
) + $expenseCents;
}
}
foreach ($byDate as $date => $value) {

View File

@ -387,6 +387,8 @@ class StoreReceivingBalanceOverviewServiceTest extends TestCase
public function test_daily_balances_roll_platform_and_store_opening_balances(): void
{
$service = new class extends StoreReceivingBalanceOverviewService {
public array $dailyScopes = [];
public function __construct()
{
}
@ -412,8 +414,14 @@ class StoreReceivingBalanceOverviewServiceTest extends TestCase
]];
}
protected function fetchPlatformDailyRows(string $platform, string $start, string $end): iterable
protected function fetchPlatformDailyRows(
string $platform,
string $start,
string $end,
bool $includeByStore = true,
): iterable
{
$this->dailyScopes[] = [$platform, $includeByStore];
$index = array_search($platform, array_column(StoreReceivingBalanceOverviewService::PLATFORMS, 'slug'), true) + 1;
yield [
@ -439,6 +447,8 @@ class StoreReceivingBalanceOverviewServiceTest extends TestCase
$this->assertSame(109.0, $result['daily_summary']['2026-10-03']['closing'] / 9);
$this->assertSame('dewu-alipay', $result['platforms'][8]['slug']);
$this->assertTrue($result['platforms'][0]['daily_reconciled']);
$this->assertCount(9, $service->dailyScopes);
$this->assertSame([false], array_values(array_unique(array_column($service->dailyScopes, 1))));
$storeResult = $service->dailyBalanceStores(
'2026-10-01',
@ -453,6 +463,7 @@ class StoreReceivingBalanceOverviewServiceTest extends TestCase
$this->assertSame(100.0, $storeResult['rows'][0]['opening_balance']);
$this->assertSame(109.0, $storeResult['rows'][0]['amount']);
$this->assertTrue($storeResult['rows'][0]['daily']['2026-10-03']['available']);
$this->assertSame(['taobao-alipay', true], $service->dailyScopes[9]);
}
public function test_daily_store_balance_stays_unavailable_when_opening_is_missing(): void
@ -477,7 +488,12 @@ class StoreReceivingBalanceOverviewServiceTest extends TestCase
]];
}
protected function fetchPlatformDailyRows(string $platform, string $start, string $end): iterable
protected function fetchPlatformDailyRows(
string $platform,
string $start,
string $end,
bool $includeByStore = true,
): iterable
{
yield [
'store_name' => '待补期初店铺-' . $platform,