diff --git a/database/migrations/2026_11_05_010000_add_taobao_alipay_opening_balance_index.php b/database/migrations/2026_11_05_010000_add_taobao_alipay_opening_balance_index.php new file mode 100644 index 00000000..94d30bfa --- /dev/null +++ b/database/migrations/2026_11_05_010000_add_taobao_alipay_opening_balance_index.php @@ -0,0 +1,54 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + if (! $schema->hasTable('taobao_alipay_bill_rows') + || collect($schema->getIndexes('taobao_alipay_bill_rows')) + ->contains('name', 'taobao_alipay_account_time_row_idx')) { + return; + } + + $schema->table('taobao_alipay_bill_rows', function (Blueprint $table): void { + $table->index( + ['alipay_account', 'occurred_at', 'source_row_number', 'balance_amount'], + 'taobao_alipay_account_time_row_idx', + ); + }); + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + if (! $schema->hasTable('taobao_alipay_bill_rows') + || ! collect($schema->getIndexes('taobao_alipay_bill_rows')) + ->contains('name', 'taobao_alipay_account_time_row_idx')) { + return; + } + + $schema->table('taobao_alipay_bill_rows', function (Blueprint $table): void { + $table->dropIndex('taobao_alipay_account_time_row_idx'); + }); + } +}; diff --git a/modules/EcommerceFinance/Http/Controllers/AlipayBills.php b/modules/EcommerceFinance/Http/Controllers/AlipayBills.php index 0a7fc571..0ce15d89 100644 --- a/modules/EcommerceFinance/Http/Controllers/AlipayBills.php +++ b/modules/EcommerceFinance/Http/Controllers/AlipayBills.php @@ -91,7 +91,14 @@ class AlipayBills extends Controller 'current_page' => 1, 'last_page' => 1, 'per_page' => min(max((int) $request->get('limit', 10), 1), 100), - 'summary' => ['income' => 0, 'expense' => 0, 'balance' => 0, 'count' => 0], + 'summary' => [ + 'income' => 0, + 'expense' => 0, + 'opening_balance' => 0, + 'opening_balance_date' => null, + 'balance' => 0, + 'count' => 0, + ], ], 503); } } diff --git a/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php b/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php index 11d04427..9f9664c1 100644 --- a/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php +++ b/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php @@ -6,6 +6,7 @@ use DateTimeImmutable; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\DatabaseManager; use Illuminate\Database\Query\Builder; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Schema; use Modules\EcommerceFinance\Services\LedgerRemarkFilter; use RuntimeException; @@ -15,6 +16,8 @@ class TaobaoAlipaySettlementBillRepository private const IMPORT_TABLE = 'taobao_alipay_bill_imports'; private const ROW_TABLE = 'taobao_alipay_bill_rows'; + private const OPENING_BALANCE_CACHE_SECONDS = 300; + private readonly ConnectionInterface $connection; public function __construct(DatabaseManager $databases) @@ -61,6 +64,7 @@ class TaobaoAlipaySettlementBillRepository $total = (int) ($summary->row_count ?? 0); $income = (float) ($summary->income_total ?? 0); $expense = (float) ($summary->expense_total ?? 0); + $opening = $this->openingBalance($filters); $sortColumn = $this->sortColumn($sort); $direction = $direction === 'asc' ? 'asc' : 'desc'; $query->orderBy($sortColumn, $direction); @@ -78,7 +82,9 @@ class TaobaoAlipaySettlementBillRepository 'summary' => [ 'income' => $income, 'expense' => $expense, - 'balance' => round($income - $expense, 2), + 'opening_balance' => $opening['balance'], + 'opening_balance_date' => $opening['date'], + 'balance' => round($opening['balance'] + $income - $expense, 2), 'count' => $total, ], 'sync' => [ @@ -167,6 +173,63 @@ class TaobaoAlipaySettlementBillRepository ][$sort] ?? 'occurred_at'; } + /** + * 当前账期开始前,每个支付宝账号最后一笔余额之和。 + * + * 同一秒可能有多笔流水,按源表行号继续取最后一笔,避免同一时间点重复计入。 + * + * @return array{balance:float,date:?string} + */ + private function openingBalance(array $filters): array + { + $start = $this->date($filters['start'] ?? null) + ?? $this->date($filters['end'] ?? null); + if ($start === null) { + return ['balance' => 0.0, 'date' => null]; + } + + $monthStart = $start->modify('first day of this month'); + $cutoff = $monthStart->format('Y-m-d') . ' 00:00:00'; + $store = trim((string) ($filters['store_name'] ?? '')); + $importVersion = (string) ($this->connection->table(self::IMPORT_TABLE) + ->where('status', 'succeeded') + ->max('completed_at') ?? ''); + $cacheKey = 'taobao-alipay-opening-balance:v1:' . hash('sha256', implode('|', [ + $cutoff, + $store, + $importVersion, + ])); + + $balance = Cache::remember( + $cacheKey, + self::OPENING_BALANCE_CACHE_SECONDS, + function () use ($cutoff, $store): float { + $ranked = $this->connection->table(self::ROW_TABLE) + ->where('occurred_at', '<', $cutoff) + ->whereNotNull('alipay_account') + ->where('alipay_account', '<>', '') + ->when($store !== '', fn (Builder $query) => $query->where('store_name', $store)) + ->select(['alipay_account', 'occurred_at', 'source_row_number', 'balance_amount']) + ->selectRaw( + 'ROW_NUMBER() OVER (' . + 'PARTITION BY alipay_account ' . + 'ORDER BY occurred_at DESC, source_row_number DESC' . + ') AS row_rank', + ); + + return round((float) $this->connection->query() + ->fromSub($ranked, 'latest_balances') + ->where('row_rank', 1) + ->sum('balance_amount'), 2); + }, + ); + + return [ + 'balance' => (float) $balance, + 'date' => $monthStart->modify('-1 day')->format('Y-m-d'), + ]; + } + /** @return array */ private function mapRow(object $row): array { diff --git a/resources/assets/js/components/business/TaobaoAlipayBills.vue b/resources/assets/js/components/business/TaobaoAlipayBills.vue index 9d1ebd16..6b652310 100644 --- a/resources/assets/js/components/business/TaobaoAlipayBills.vue +++ b/resources/assets/js/components/business/TaobaoAlipayBills.vue @@ -1,6 +1,6 @@