From e25f133f935ab8f6b89beaded075bdc06a8c4054 Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Thu, 5 Nov 2026 11:45:58 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=B7=98=E7=B3=BB=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E5=AE=9D=E9=A6=96=E6=9C=88=E6=8C=89=E9=A6=96=E7=AC=94=E4=BD=99?= =?UTF-8?q?=E9=A2=9D=E5=80=92=E6=8E=A8=E6=9C=9F=E5=88=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 当所选月份之前没有支付宝账单快照时,不再把期初余额按零处理,而是按每个支付宝账号当月首笔余额减首笔收入加首笔支出倒推,避免7月余额被错误显示为负数。 --- .../Http/Controllers/AlipayBills.php | 1 + .../TaobaoAlipaySettlementBillRepository.php | 70 ++++++++++++++++--- .../components/business/TaobaoAlipayBills.vue | 6 +- ...obaoAlipaySettlementBillRepositoryTest.php | 27 +++++++ 4 files changed, 93 insertions(+), 11 deletions(-) diff --git a/modules/EcommerceFinance/Http/Controllers/AlipayBills.php b/modules/EcommerceFinance/Http/Controllers/AlipayBills.php index 0ce15d89..58ba3b18 100644 --- a/modules/EcommerceFinance/Http/Controllers/AlipayBills.php +++ b/modules/EcommerceFinance/Http/Controllers/AlipayBills.php @@ -96,6 +96,7 @@ class AlipayBills extends Controller 'expense' => 0, 'opening_balance' => 0, 'opening_balance_date' => null, + 'opening_balance_source' => null, 'balance' => 0, 'count' => 0, ], diff --git a/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php b/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php index 9f9664c1..356d2f76 100644 --- a/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php +++ b/modules/EcommerceFinance/Repositories/TaobaoAlipaySettlementBillRepository.php @@ -84,6 +84,7 @@ class TaobaoAlipaySettlementBillRepository 'expense' => $expense, 'opening_balance' => $opening['balance'], 'opening_balance_date' => $opening['date'], + 'opening_balance_source' => $opening['source'], 'balance' => round($opening['balance'] + $income - $expense, 2), 'count' => $total, ], @@ -178,18 +179,20 @@ class TaobaoAlipaySettlementBillRepository * * 同一秒可能有多笔流水,按源表行号继续取最后一笔,避免同一时间点重复计入。 * - * @return array{balance:float,date:?string} + * @return array{balance:float,date:?string,source: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]; + return ['balance' => 0.0, 'date' => null, 'source' => 'none']; } $monthStart = $start->modify('first day of this month'); + $nextMonthStart = $monthStart->modify('+1 month'); $cutoff = $monthStart->format('Y-m-d') . ' 00:00:00'; + $periodEnd = $nextMonthStart->format('Y-m-d') . ' 00:00:00'; $store = trim((string) ($filters['store_name'] ?? '')); $importVersion = (string) ($this->connection->table(self::IMPORT_TABLE) ->where('status', 'succeeded') @@ -200,16 +203,23 @@ class TaobaoAlipaySettlementBillRepository $importVersion, ])); - $balance = Cache::remember( + $opening = Cache::remember( $cacheKey, self::OPENING_BALANCE_CACHE_SECONDS, - function () use ($cutoff, $store): float { + function () use ($cutoff, $periodEnd, $store): array { $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']) + ->select([ + 'alipay_account', + 'occurred_at', + 'source_row_number', + 'income_amount', + 'expense_amount', + 'balance_amount', + ]) ->selectRaw( 'ROW_NUMBER() OVER (' . 'PARTITION BY alipay_account ' . @@ -217,16 +227,60 @@ class TaobaoAlipaySettlementBillRepository ') AS row_rank', ); - return round((float) $this->connection->query() + $latestRows = $this->connection->query() ->fromSub($ranked, 'latest_balances') ->where('row_rank', 1) - ->sum('balance_amount'), 2); + ->get(); + + if ($latestRows->isNotEmpty()) { + return [ + 'balance' => round((float) $latestRows->sum('balance_amount'), 2), + 'source' => 'previous_period', + ]; + } + + // 首个导入月份没有上月快照时,用当月首笔余额倒推期初: + // 期初 = 首笔余额 - 首笔收入 + 首笔支出。 + $firstRows = $this->connection->table(self::ROW_TABLE) + ->where('occurred_at', '>=', $cutoff) + ->where('occurred_at', '<', $periodEnd) + ->whereNotNull('alipay_account') + ->where('alipay_account', '<>', '') + ->when($store !== '', fn (Builder $query) => $query->where('store_name', $store)) + ->select([ + 'alipay_account', + 'occurred_at', + 'source_row_number', + 'income_amount', + 'expense_amount', + 'balance_amount', + ]) + ->selectRaw( + 'ROW_NUMBER() OVER (' . + 'PARTITION BY alipay_account ' . + 'ORDER BY occurred_at ASC, source_row_number ASC' . + ') AS row_rank', + ); + $first = $this->connection->query() + ->fromSub($firstRows, 'first_balances') + ->where('row_rank', 1) + ->get(); + + return [ + 'balance' => round((float) $first->sum( + static fn (object $row): float => (float) $row->balance_amount + - (float) $row->income_amount + + (float) $row->expense_amount, + ), 2), + 'source' => 'first_row_estimate', + ]; }, ); return [ - 'balance' => (float) $balance, + 'balance' => (float) $opening['balance'], 'date' => $monthStart->modify('-1 day')->format('Y-m-d'), + 'source' => (string) $opening['source'], ]; } diff --git a/resources/assets/js/components/business/TaobaoAlipayBills.vue b/resources/assets/js/components/business/TaobaoAlipayBills.vue index 6b652310..5f305bcc 100644 --- a/resources/assets/js/components/business/TaobaoAlipayBills.vue +++ b/resources/assets/js/components/business/TaobaoAlipayBills.vue @@ -163,13 +163,13 @@ const SORTABLE = ['occurred_at', 'income', 'expense', 'balance', 'record_code']; export default { name: 'TaobaoAlipayBills', components: { TableColumnSettings, flatPicker, [Select.name]: Select, [Option.name]: Option }, props: { apiBase: { type: String, required: true }, exportBase: { type: String, required: true }, progressBase: { type: String, default: '' }, userKey: { type: [String, Number], required: true } }, - data() { return { loading: false, error: '', rows: [], configuredColumns: [], summary: { income: 0, expense: 0, opening_balance: 0, opening_balance_date: null, balance: 0, count: 0 }, total: 0, currentPage: 1, lastPage: 1, perPage: 20, filters: { store_name: '', ledger_remark: '', source_channel: '', bill_item: '', business_type: '', ...currentMonthRange(), keyword: '' }, filterOptions: { shops: [], bill_items: [], ledger_remarks: [] }, filterOptionsLoading: false, filterOptionsError: false, sort: { key: 'occurred_at', dir: 'desc' }, exportMode: 'filtered-visible', exporting: false, exportModalOpen: false, exportTasks: [], exportHint: '导出在后台生成,成功后点「下载」;期间可以继续查看其它页面。', exportTimer: null }; }, + data() { return { loading: false, error: '', rows: [], configuredColumns: [], summary: { income: 0, expense: 0, opening_balance: 0, opening_balance_date: null, opening_balance_source: null, balance: 0, count: 0 }, total: 0, currentPage: 1, lastPage: 1, perPage: 20, filters: { store_name: '', ledger_remark: '', source_channel: '', bill_item: '', business_type: '', ...currentMonthRange(), keyword: '' }, filterOptions: { shops: [], bill_items: [], ledger_remarks: [] }, filterOptionsLoading: false, filterOptionsError: false, sort: { key: 'occurred_at', dir: 'desc' }, exportMode: 'filtered-visible', exporting: false, exportModalOpen: false, exportTasks: [], exportHint: '导出在后台生成,成功后点「下载」;期间可以继续查看其它页面。', exportTimer: null }; }, computed: { defaultColumns() { return COLUMNS; }, visibleColumns() { return this.configuredColumns.filter((column) => column.visible); }, visibleGroups() { return this.visibleColumns.reduce((groups, column) => { const last = groups[groups.length - 1]; if (last && last.label === column.group) last.span += 1; else groups.push({ label: column.group, span: 1 }); return groups; }, []); }, stats() { return [ - { label: '期初余额', value: this.moneyWan(this.summary.opening_balance), note: this.summary.opening_balance_date ? `截至 ${this.summary.opening_balance_date} 最后一笔` : '上月最后一笔', className: '' }, + { label: '期初余额', value: this.moneyWan(this.summary.opening_balance), note: this.summary.opening_balance_source === 'first_row_estimate' ? '首月按首笔余额倒推' : (this.summary.opening_balance_date ? `截至 ${this.summary.opening_balance_date} 最后一笔` : '上月最后一笔'), className: '' }, { label: '收入合计', value: this.moneyWan(this.summary.income), note: `${this.summary.count} 笔交易`, className: 'is-income' }, { label: '支出合计', value: this.moneyWan(this.summary.expense), note: '按当前筛选', className: 'is-expense' }, { label: '余额', value: this.moneyWan(this.summary.balance), note: '期初余额 + 收入合计 - 支出合计', className: '' }, @@ -187,7 +187,7 @@ export default { mounted() { this.fetchFilterOptions(); this.fetch(); }, methods: { async fetchFilterOptions() { this.filterOptionsLoading = true; this.filterOptionsError = false; try { const response = await window.axios.get(`${this.apiBase}/filter-options`); const body = response.data || {}; this.filterOptions = { shops: Array.isArray(body.shops) ? body.shops : [], bill_items: Array.isArray(body.bill_items) ? body.bill_items : [], ledger_remarks: Array.isArray(body.ledger_remarks) ? body.ledger_remarks : [] }; } catch (error) { this.filterOptionsError = true; } finally { this.filterOptionsLoading = false; } }, - async fetch() { this.loading = true; this.error = ''; try { const response = await window.axios.get(this.apiBase, { params: { ...this.filters, sort: this.sort.key, dir: this.sort.dir, limit: this.perPage, page: this.currentPage } }); const body = response.data || {}; this.rows = body.data || []; this.total = body.total || 0; this.currentPage = body.current_page || 1; this.lastPage = body.last_page || 1; this.perPage = body.per_page || this.perPage; this.summary = body.summary || { income: 0, expense: 0, opening_balance: 0, opening_balance_date: null, balance: 0, count: 0 }; } catch (error) { this.rows = []; this.total = 0; this.summary = { income: 0, expense: 0, opening_balance: 0, opening_balance_date: null, balance: 0, count: 0 }; this.error = (error.response && error.response.data && error.response.data.message) || '淘系支付宝账单暂时无法读取,请稍后重试。'; } finally { this.loading = false; } }, + async fetch() { this.loading = true; this.error = ''; try { const response = await window.axios.get(this.apiBase, { params: { ...this.filters, sort: this.sort.key, dir: this.sort.dir, limit: this.perPage, page: this.currentPage } }); const body = response.data || {}; this.rows = body.data || []; this.total = body.total || 0; this.currentPage = body.current_page || 1; this.lastPage = body.last_page || 1; this.perPage = body.per_page || this.perPage; this.summary = body.summary || { income: 0, expense: 0, opening_balance: 0, opening_balance_date: null, opening_balance_source: null, balance: 0, count: 0 }; } catch (error) { this.rows = []; this.total = 0; this.summary = { income: 0, expense: 0, opening_balance: 0, opening_balance_date: null, opening_balance_source: null, balance: 0, count: 0 }; this.error = (error.response && error.response.data && error.response.data.message) || '淘系支付宝账单暂时无法读取,请稍后重试。'; } finally { this.loading = false; } }, applyFilters() { if (this.invalidDateRange) return; this.currentPage = 1; this.fetch(); }, resetFilters() { this.filters = { store_name: '', ledger_remark: '', source_channel: '', bill_item: '', business_type: '', ...currentMonthRange(), keyword: '' }; this.applyFilters(); }, openDatePicker(refName) { const picker = this.$refs[refName]; if (picker && picker.fp) picker.fp.open(); }, // 选日期不自动查询:日期是一对(开始/结束),中途触发会先按半截条件查全表,很慢。改完点「查询」再生效。 diff --git a/tests/Unit/EcommerceFinance/TaobaoAlipaySettlementBillRepositoryTest.php b/tests/Unit/EcommerceFinance/TaobaoAlipaySettlementBillRepositoryTest.php index 33946b33..55155552 100644 --- a/tests/Unit/EcommerceFinance/TaobaoAlipaySettlementBillRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/TaobaoAlipaySettlementBillRepositoryTest.php @@ -56,6 +56,7 @@ class TaobaoAlipaySettlementBillRepositoryTest extends TestCase $this->assertSame(15.0, $result['summary']['expense']); $this->assertSame(230.0, $result['summary']['opening_balance']); $this->assertSame('2026-09-30', $result['summary']['opening_balance_date']); + $this->assertSame('previous_period', $result['summary']['opening_balance_source']); $this->assertSame(275.0, $result['summary']['balance']); } @@ -84,6 +85,32 @@ class TaobaoAlipaySettlementBillRepositoryTest extends TestCase $this->assertSame(180.0, $result['summary']['balance']); } + public function test_first_imported_month_infers_opening_balance_from_first_account_rows(): void + { + $rows = DB::connection('business_mirror')->table('taobao_alipay_bill_rows'); + $rows->insert([ + $this->row('A-JUL-1', '天猫-A店', 'account-a', '2026-07-01 09:00:00', 10, 0, 210, 10), + $this->row('A-JUL-2', '天猫-A店', 'account-a', '2026-07-02 09:00:00', 20, 5, 225, 20), + $this->row('B-JUL-1', '淘宝-B店', 'account-b', '2026-07-01 10:00:00', 0, 10, 90, 30), + $this->row('B-JUL-2', '淘宝-B店', 'account-b', '2026-07-03 10:00:00', 5, 0, 95, 40), + ]); + + $result = app(TaobaoAlipaySettlementBillRepository::class)->paginate( + ['start' => '2026-07-01', 'end' => '2026-07-31'], + 'occurred_at', + 'desc', + 1, + 20, + ); + + // A 首笔倒推期初 200,B 首笔倒推期初 100。 + $this->assertSame(300.0, $result['summary']['opening_balance']); + $this->assertSame('first_row_estimate', $result['summary']['opening_balance_source']); + $this->assertSame(35.0, $result['summary']['income']); + $this->assertSame(15.0, $result['summary']['expense']); + $this->assertSame(320.0, $result['summary']['balance']); + } + private function createTables(): void { $schema = Schema::connection('business_mirror'); -- 2.47.2