From f28fb133a44135d5c82517b81a4fd9bf36a3acfa Mon Sep 17 00:00:00 2001 From: qiuxiang <394405259@qq.com> Date: Sat, 7 Nov 2026 17:52:37 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=8C=89=E9=93=B6=E8=A1=8C=E5=8D=A1?= =?UTF-8?q?=E7=BB=93=E7=AE=97=E9=87=8D=E7=AE=97=E5=94=AF=E5=93=81=E4=BC=9A?= =?UTF-8?q?JX=E4=BD=99=E9=A2=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Commands/ImportVipshopJxBankPayments.php | 186 ++++++++++++++++++ .../Commands/StoreVipshopJxOpeningBalance.php | 6 +- ...180000_create_vipshop_jx_bank_payments.php | 47 +++++ deploy/finance-batch-imports.json | 1 + .../Http/Controllers/AccountBills.php | 8 +- .../VipshopJxBankPaymentRepository.php | 55 ++++++ .../VipshopJxOpeningBalanceRepository.php | 41 +++- .../js/components/business/AccountBills.vue | 16 +- .../Business/VipshopJxReceivingBillsTest.php | 71 ++++++- .../ImportVipshopJxBankPaymentsTest.php | 82 ++++++++ .../VipshopJxOpeningBalanceRepositoryTest.php | 38 +++- tests/Unit/View/AccountBillsTableTest.php | 23 ++- 12 files changed, 546 insertions(+), 28 deletions(-) create mode 100644 app/Console/Commands/ImportVipshopJxBankPayments.php create mode 100644 database/migrations/2026_11_07_180000_create_vipshop_jx_bank_payments.php create mode 100644 modules/EcommerceFinance/Repositories/VipshopJxBankPaymentRepository.php create mode 100644 tests/Feature/Console/ImportVipshopJxBankPaymentsTest.php diff --git a/app/Console/Commands/ImportVipshopJxBankPayments.php b/app/Console/Commands/ImportVipshopJxBankPayments.php new file mode 100644 index 00000000..9e395959 --- /dev/null +++ b/app/Console/Commands/ImportVipshopJxBankPayments.php @@ -0,0 +1,186 @@ +argument('file')); + if ($path === false || ! is_file($path) || ! is_readable($path)) { + $this->error('账单收付款文件不存在或不可读。'); + + return self::FAILURE; + } + try { + $sourceRows = json_decode((string) file_get_contents($path), true, 512, JSON_THROW_ON_ERROR); + } catch (JsonException) { + $this->error('账单收付款文件不是有效 JSON。'); + + return self::FAILURE; + } + if (! is_array($sourceRows) || $sourceRows === []) { + $this->error('账单收付款文件为空。'); + + return self::FAILURE; + } + + try { + [$rows, $skipped] = $this->normalize($sourceRows, hash_file('sha256', $path)); + } catch (RuntimeException $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $connection = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + if (! $connection->getSchemaBuilder()->hasTable(VipshopJxBankPaymentRepository::TABLE)) { + $this->error('唯品会JX银行卡结算表尚未完成迁移。'); + + return self::FAILURE; + } + + $net = '0.000000'; + $byPeriod = []; + foreach ($rows as $row) { + $net = bcadd($net, $row['amount'], 6); + $byPeriod[$row['bill_period']] = bcadd($byPeriod[$row['bill_period']] ?? '0', $row['amount'], 6); + } + ksort($byPeriod); + + $this->table(['状态', '源行数', '导入行数', '跳过行数', '净额'], [[ + $this->option('dry-run') ? 'validated' : 'ready', + count($sourceRows), + count($rows), + $skipped, + $net, + ]]); + $this->table( + ['账单期间', '银行卡结算净额'], + array_map(static fn (string $period, string $amount): array => [$period, $amount], array_keys($byPeriod), array_values($byPeriod)), + ); + + if ($this->option('dry-run')) { + return self::SUCCESS; + } + + try { + $connection->transaction(function () use ($connection, $rows): void { + if ($this->option('replace')) { + $connection->table(VipshopJxBankPaymentRepository::TABLE)->delete(); + } + $now = now(); + foreach (array_chunk($rows, 500) as $chunk) { + $connection->table(VipshopJxBankPaymentRepository::TABLE)->upsert( + array_map(static fn (array $row): array => $row + [ + 'imported_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ], $chunk), + ['source_payment_id'], + [ + 'source_bill_number', + 'bill_period', + 'pay_date', + 'batch_number', + 'vendor_account_num', + 'amount', + 'currency_code', + 'pay_status', + 'source_hash', + 'imported_at', + 'updated_at', + ], + ); + } + }); + } catch (Throwable $exception) { + report($exception); + $this->error('唯品会JX银行卡结算写入失败,详细原因已记录到受保护日志。'); + + return self::FAILURE; + } + + $this->info('唯品会JX银行卡结算记录导入成功。'); + + return self::SUCCESS; + } + + /** + * @param list $sourceRows + * @return array{0:list>,1:int} + */ + private function normalize(array $sourceRows, string $sourceHash): array + { + $rows = []; + $sourceIds = []; + $skipped = 0; + foreach ($sourceRows as $index => $source) { + if (! is_array($source)) { + throw new RuntimeException('第 ' . ($index + 1) . ' 行不是有效对象。'); + } + if ((string) ($source['vendorCode'] ?? '') !== '672378') { + throw new RuntimeException('第 ' . ($index + 1) . ' 行不是供应商 672378。'); + } + $vendorAccount = trim((string) ($source['vendorAccountNum'] ?? '')); + if (($source['payStatus'] ?? null) !== 'SUCCESS' + || $vendorAccount === '' + || $vendorAccount === '银行存款-中转') { + $skipped++; + continue; + } + + $sourceId = (int) ($source['id'] ?? 0); + if ($sourceId < 1 || isset($sourceIds[$sourceId])) { + throw new RuntimeException('第 ' . ($index + 1) . ' 行来源 ID 无效或重复。'); + } + $sourceIds[$sourceId] = true; + $billNumber = trim((string) ($source['billNumber'] ?? '')); + if (preg_match('/(?:^|[-_])(20\d{2})(\d{2})\d{2}(?:[-_]|$)/', $billNumber, $matches) !== 1) { + throw new RuntimeException("第 " . ($index + 1) . " 行账单编号无法识别账期:{$billNumber}"); + } + $amount = $source['billPayAmount'] ?? null; + if (! is_numeric($amount)) { + throw new RuntimeException('第 ' . ($index + 1) . ' 行已结金额无效。'); + } + $payDate = $source['payDate'] ?? null; + if (! is_numeric($payDate)) { + throw new RuntimeException('第 ' . ($index + 1) . ' 行付款日期无效。'); + } + $rows[] = [ + 'source_payment_id' => $sourceId, + 'source_bill_number' => $billNumber, + 'bill_period' => $matches[1] . '-' . $matches[2], + 'pay_date' => CarbonImmutable::createFromTimestampMs((int) $payDate, 'Asia/Shanghai')->format('Y-m-d'), + 'batch_number' => mb_substr((string) ($source['batchNumber'] ?? ''), 0, 64), + 'vendor_account_num' => mb_substr($vendorAccount, 0, 64), + 'amount' => number_format((float) $amount, 6, '.', ''), + 'currency_code' => mb_substr((string) ($source['currencyCode'] ?? 'CNY'), 0, 8), + 'pay_status' => 'SUCCESS', + 'source_hash' => $sourceHash, + ]; + } + if ($rows === []) { + throw new RuntimeException('账单收付款文件中没有可导入的银行卡结算记录。'); + } + + return [$rows, $skipped]; + } +} diff --git a/app/Console/Commands/StoreVipshopJxOpeningBalance.php b/app/Console/Commands/StoreVipshopJxOpeningBalance.php index 09b36884..2f4598d0 100644 --- a/app/Console/Commands/StoreVipshopJxOpeningBalance.php +++ b/app/Console/Commands/StoreVipshopJxOpeningBalance.php @@ -12,10 +12,10 @@ class StoreVipshopJxOpeningBalance extends Command protected $signature = 'vipshop-jx:store-opening-balance {period-end : 余额截止日期,格式 YYYY-MM-DD} {balance : 余额金额} - {--source=唯品会结算平台历史账单累计 : 余额来源说明} + {--source=唯品会结算平台历史账单累计 : 历史账单净额来源说明} {--dry-run : 只校验,不写数据库}'; - protected $description = '登记唯品会JX账户月末余额,作为后续月份期初余额的滚动基准'; + protected $description = '登记唯品会JX账户历史账单净额,作为银行卡结算扣减前的计算基准'; public function handle(DatabaseManager $databases): int { @@ -65,7 +65,7 @@ class StoreVipshopJxOpeningBalance extends Command ); } - $this->table(['截止日期', '状态', '余额', '来源'], [[ + $this->table(['截止日期', '状态', '历史账单净额', '来源'], [[ $periodEnd, $this->option('dry-run') ? 'validated' : 'succeeded', $balance, diff --git a/database/migrations/2026_11_07_180000_create_vipshop_jx_bank_payments.php b/database/migrations/2026_11_07_180000_create_vipshop_jx_bank_payments.php new file mode 100644 index 00000000..1c380d71 --- /dev/null +++ b/database/migrations/2026_11_07_180000_create_vipshop_jx_bank_payments.php @@ -0,0 +1,47 @@ +connection()); + if ($schema->hasTable(self::TABLE)) { + return; + } + + $schema->create(self::TABLE, function (Blueprint $table): void { + $table->id(); + $table->unsignedBigInteger('source_payment_id')->unique(); + $table->string('source_bill_number', 128); + $table->char('bill_period', 7); + $table->date('pay_date')->nullable(); + $table->string('batch_number', 64)->nullable(); + $table->string('vendor_account_num', 64); + $table->decimal('amount', 20, 6); + $table->string('currency_code', 8); + $table->string('pay_status', 24); + $table->string('source_hash', 64); + $table->dateTime('imported_at', 6); + $table->timestamps(6); + + $table->index(['bill_period', 'pay_date'], 'vipshop_jx_bank_period_date_idx'); + $table->index('source_bill_number', 'vipshop_jx_bank_bill_idx'); + }); + } + + public function down(): void + { + Schema::connection($this->connection())->dropIfExists(self::TABLE); + } + + private function connection(): string + { + return (string) config('upstream_mirrors.connection', 'business_mirror'); + } +}; diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index 8ad2085b..57ad321b 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -40,6 +40,7 @@ "vipshop-mp:import", "vipshop-mp:import-opening-balances", "vipshop-jx:import", + "vipshop-jx:import-bank-payments", "xiaohongshu-bills:import", "business-mirror:import-third-party-warehouse-anchor" ] diff --git a/modules/EcommerceFinance/Http/Controllers/AccountBills.php b/modules/EcommerceFinance/Http/Controllers/AccountBills.php index 2f84900b..420f3705 100644 --- a/modules/EcommerceFinance/Http/Controllers/AccountBills.php +++ b/modules/EcommerceFinance/Http/Controllers/AccountBills.php @@ -128,9 +128,15 @@ class AccountBills extends Controller 'opening_balance' => $openingBalance['balance'], 'opening_balance_date' => $openingBalance['date'], 'opening_balance_source' => $openingBalance['source'], + 'withdrawal_amount' => (float) ($openingBalance['withdrawal_amount'] ?? 0), + 'withdrawal_count' => (int) ($openingBalance['withdrawal_count'] ?? 0), + 'withdrawal_latest_date' => $openingBalance['withdrawal_latest_date'] ?? null, 'balance' => match (true) { $billType === 'vipshop' => round($openingBalance['balance'] + $income - $expense, 2), - $billType === 'vipshop-jx' => round($openingBalance['balance'] + $income - $expense, 2), + $billType === 'vipshop-jx' => round( + $openingBalance['balance'] + $income - $expense - (float) $openingBalance['withdrawal_amount'], + 2, + ), $billType === 'xiaohongshu' => round($openingBalance['balance'] + $income - $expense, 2), default => $latestBalance !== null ? (float) $latestBalance : 0, }, diff --git a/modules/EcommerceFinance/Repositories/VipshopJxBankPaymentRepository.php b/modules/EcommerceFinance/Repositories/VipshopJxBankPaymentRepository.php new file mode 100644 index 00000000..492ab0aa --- /dev/null +++ b/modules/EcommerceFinance/Repositories/VipshopJxBankPaymentRepository.php @@ -0,0 +1,55 @@ +mirror = $databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + public function netBefore(string $period): ?float + { + if (! $this->available()) { + return null; + } + + return round((float) $this->mirror->table(self::TABLE) + ->where('bill_period', '<', $period) + ->sum('amount'), 2); + } + + /** @return array{amount:float,count:int,latest_pay_date:?string} */ + public function forPeriod(string $period): array + { + if (! $this->available()) { + return ['amount' => 0.0, 'count' => 0, 'latest_pay_date' => null]; + } + + $summary = $this->mirror->table(self::TABLE) + ->where('bill_period', $period) + ->selectRaw('COALESCE(SUM(amount), 0) AS amount, COUNT(*) AS rows_count, MAX(pay_date) AS latest_pay_date') + ->first(); + + return [ + 'amount' => round((float) ($summary->amount ?? 0), 2), + 'count' => (int) ($summary->rows_count ?? 0), + 'latest_pay_date' => $summary->latest_pay_date ?? null, + ]; + } + + private function available(): bool + { + return $this->mirror->getSchemaBuilder()->hasTable(self::TABLE); + } +} diff --git a/modules/EcommerceFinance/Repositories/VipshopJxOpeningBalanceRepository.php b/modules/EcommerceFinance/Repositories/VipshopJxOpeningBalanceRepository.php index 496dec24..7c7552a0 100644 --- a/modules/EcommerceFinance/Repositories/VipshopJxOpeningBalanceRepository.php +++ b/modules/EcommerceFinance/Repositories/VipshopJxOpeningBalanceRepository.php @@ -13,35 +13,45 @@ class VipshopJxOpeningBalanceRepository private readonly ConnectionInterface $mirror; private readonly ConnectionInterface $bills; + private readonly VipshopJxBankPaymentRepository $bankPayments; - public function __construct(DatabaseManager $databases) + public function __construct( + DatabaseManager $databases, + VipshopJxBankPaymentRepository $bankPayments, + ) { $this->mirror = $databases->connection( (string) config('upstream_mirrors.connection', 'business_mirror'), ); $this->bills = $databases->connection(); + $this->bankPayments = $bankPayments; } - /** @return array{balance:float,date:?string,source:string} */ + /** @return array{balance:float,date:?string,source:string,withdrawal_amount:float,withdrawal_count:int,withdrawal_latest_date:?string} */ public function openingBalance(?string $startDate, ?string $endDate): array { $start = $this->monthStart($startDate) ?? $this->monthStart($endDate); $baselineMonth = CarbonImmutable::create(2026, 7, 1)->startOfDay(); if ($start === null || $start->lt($baselineMonth)) { - return ['balance' => 0.0, 'date' => null, 'source' => 'none']; + return $this->none(); } if (! $this->mirror->getSchemaBuilder()->hasTable(self::TABLE)) { - return ['balance' => 0.0, 'date' => null, 'source' => 'none']; + return $this->none(); } $baseline = $this->mirror->table(self::TABLE) ->where('period_end', self::BASELINE_PERIOD_END) ->value('balance'); if ($baseline === null) { - return ['balance' => 0.0, 'date' => null, 'source' => 'none']; + return $this->none(); } - $balance = (float) $baseline; + $withdrawnBefore = $this->bankPayments->netBefore($start->format('Y-m')); + if ($withdrawnBefore === null) { + return $this->none(); + } + + $balance = (float) $baseline - $withdrawnBefore; if ($start->gt($baselineMonth)) { $movement = $this->bills->table('ec_account_bills') ->where('company_id', (int) (company_id() ?: 1)) @@ -53,11 +63,28 @@ class VipshopJxOpeningBalanceRepository ->first(); $balance += (float) ($movement->income ?? 0) - (float) ($movement->expense ?? 0); } + $withdrawal = $this->bankPayments->forPeriod($start->format('Y-m')); return [ 'balance' => round($balance, 2), 'date' => $start->subDay()->format('Y-m-d'), - 'source' => $start->equalTo($baselineMonth) ? 'june_ending' : 'previous_period', + 'source' => $start->equalTo($baselineMonth) ? 'bank_settled' : 'previous_period', + 'withdrawal_amount' => $withdrawal['amount'], + 'withdrawal_count' => $withdrawal['count'], + 'withdrawal_latest_date' => $withdrawal['latest_pay_date'], + ]; + } + + /** @return array{balance:float,date:null,source:string,withdrawal_amount:float,withdrawal_count:int,withdrawal_latest_date:null} */ + private function none(): array + { + return [ + 'balance' => 0.0, + 'date' => null, + 'source' => 'none', + 'withdrawal_amount' => 0.0, + 'withdrawal_count' => 0, + 'withdrawal_latest_date' => null, ]; } diff --git a/resources/assets/js/components/business/AccountBills.vue b/resources/assets/js/components/business/AccountBills.vue index bab00093..c3eeb575 100644 --- a/resources/assets/js/components/business/AccountBills.vue +++ b/resources/assets/js/components/business/AccountBills.vue @@ -281,7 +281,7 @@ export default { name:'AccountBills', components:{ TableColumnSettings, flatPicker, [Select.name]:Select, [Option.name]:Option }, props:{ apiBase:{type:String,required:true}, billType:{type:String,required:true}, progressBase:{type:String,default:''}, userKey:{type:[String,Number],required:true}, pageKey:{type:String,default:'store-receiving-bills'}, compact:{type:Boolean,default:false}, initialStart:{type:String,default:''}, initialEnd:{type:String,default:''} }, data(){ const filters=filtersForRange(this.initialStart,this.initialEnd); - return{loading:false,loadError:false,sync:null,rows:[],sourceColumns:[],configuredColumns:[],columnsTitle:'',sourceGroups:[],summary:{income:0,expense:0,opening_balance:null,opening_balance_date:null,opening_balance_source:null,balance:null,balance_source:null,count:0},total:0,currentPage:1,lastPage:1,perPage:this.compact?1:20,filters,queryFilters:{...filters},resultFilters:null,filterOptions:{shops:[],bill_items:[],ledger_remarks:[]},filterOptionsLoading:true,filterOptionsError:false,filterOptionsRequestSerial:0,requestSerial:0,promotionRequestSerial:0,sort:{key:'occurred_at',dir:'desc'},exportMode:'filtered-visible',exporting:false,exportModalOpen:false,exportTasks:[],exportHint:'导出在后台生成,成功后点「下载」;期间可以继续查看其它页面。',exportTimer:null,promotionModalOpen:false,promotionExpenseTab:'platform',promotionExpenseLoading:false,promotionExpenseError:false,promotionStoreSummary:[],promotionExpenseSummary:{income:0,expense:0,balance:0,count:0},promotionExpenseMessage:'',promotionPlatformFilter:'',promotionStoreFilter:'',promotionNoteFilter:'',promotionNoteTimer:null}; + return{loading:false,loadError:false,sync:null,rows:[],sourceColumns:[],configuredColumns:[],columnsTitle:'',sourceGroups:[],summary:{income:0,expense:0,opening_balance:null,opening_balance_date:null,opening_balance_source:null,withdrawal_amount:0,withdrawal_count:0,withdrawal_latest_date:null,balance:null,balance_source:null,count:0},total:0,currentPage:1,lastPage:1,perPage:this.compact?1:20,filters,queryFilters:{...filters},resultFilters:null,filterOptions:{shops:[],bill_items:[],ledger_remarks:[]},filterOptionsLoading:true,filterOptionsError:false,filterOptionsRequestSerial:0,requestSerial:0,promotionRequestSerial:0,sort:{key:'occurred_at',dir:'desc'},exportMode:'filtered-visible',exporting:false,exportModalOpen:false,exportTasks:[],exportHint:'导出在后台生成,成功后点「下载」;期间可以继续查看其它页面。',exportTimer:null,promotionModalOpen:false,promotionExpenseTab:'platform',promotionExpenseLoading:false,promotionExpenseError:false,promotionStoreSummary:[],promotionExpenseSummary:{income:0,expense:0,balance:0,count:0},promotionExpenseMessage:'',promotionPlatformFilter:'',promotionStoreFilter:'',promotionNoteFilter:'',promotionNoteTimer:null}; }, computed:{ isDouyin(){return this.billType==='douyin';}, @@ -401,14 +401,18 @@ export default { const openingDate=this.summary.opening_balance_date; const openingNote=openingSource==='none' ?'未找到 2026-06-30 平台期末余额' - :(openingSource==='june_ending' - ?`截至 ${openingDate} 平台历史账单累计` + :(openingSource==='bank_settled' + ?`截至 ${openingDate} 历史账单已扣银行卡结算` :`截至 ${openingDate} 上一账期期末`); + const withdrawalNote=this.summary.withdrawal_count + ?`${this.summary.withdrawal_count} 笔账单已结算至银行卡${this.summary.withdrawal_latest_date?`,最近到账 ${this.summary.withdrawal_latest_date}`:''}` + :'本期暂无银行卡结算'; return [ {label:'期初余额',value:this.moneyWan(this.summary.opening_balance),note:openingNote,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:''}, + {label:'提现金额',value:this.moneyWan(this.summary.withdrawal_amount),note:withdrawalNote,className:''}, + {label:'期末余额',value:this.moneyWan(this.summary.balance),note:'期初余额 + 收入合计 - 支出合计 - 提现金额',className:''}, {label:'交易笔数',value:this.summary.count,note:'当前筛选结果',className:''}, ]; } @@ -446,7 +450,7 @@ export default { beforeDestroy(){if(this.promotionNoteTimer)window.clearTimeout(this.promotionNoteTimer);}, methods:{ async fetchFilterOptions(){const requestId=++this.filterOptionsRequestSerial;this.filterOptionsLoading=true;this.filterOptionsError=false;try{const response=await window.axios.get(`${this.apiBase}/filter-options`,{params:{start:this.filters.start,end:this.filters.end}});if(requestId!==this.filterOptionsRequestSerial)return;const body=response.data||{};const shops=Array.isArray(body.shops)?body.shops.slice():[];const selected=String(this.filters.store_name||'').trim();if(selected&&shops.indexOf(selected)===-1)shops.unshift(selected);this.filterOptions={shops,bill_items:Array.isArray(body.bill_items)?body.bill_items:[],ledger_remarks:Array.isArray(body.ledger_remarks)?body.ledger_remarks:[]};}catch(error){if(requestId===this.filterOptionsRequestSerial)this.filterOptionsError=true;}finally{if(requestId===this.filterOptionsRequestSerial)this.filterOptionsLoading=false;}}, - async fetch(){const requestId=++this.requestSerial;const requestedFilters={...this.queryFilters};this.loading=true;this.loadError=false;try{const response=await window.axios.get(this.apiBase,{params:{...requestedFilters,sort:this.sort.key,dir:this.sort.dir,limit:this.perPage,page:this.currentPage}});if(requestId!==this.requestSerial)return;const body=response.data||{};this.resultFilters=requestedFilters;this.sync=body.sync||null;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:null,opening_balance_date:null,opening_balance_source:null,balance:null,balance_source:null,count:0};if(this.isPromotionMarketing){this.promotionExpenseSummary={income:Number(this.summary.income||0),expense:Number(this.summary.expense||0),balance:Number(this.summary.balance||0),count:Number(this.summary.count||0)};}if(body.columns){this.columnsTitle=body.columns.title||'';this.sourceGroups=body.columns.groups||[];this.sourceColumns=this.attachGroups(body.columns.columns||body.columns||[],this.sourceGroups);}}catch(error){if(requestId!==this.requestSerial)return;this.rows=[];this.total=0;this.sync=null;this.summary={income:0,expense:0,opening_balance:null,opening_balance_date:null,opening_balance_source:null,balance:null,balance_source:null,count:0};this.promotionExpenseSummary={income:0,expense:0,balance:0,count:0};this.loadError=true;}finally{if(requestId===this.requestSerial)this.loading=false;}}, + async fetch(){const requestId=++this.requestSerial;const requestedFilters={...this.queryFilters};this.loading=true;this.loadError=false;try{const response=await window.axios.get(this.apiBase,{params:{...requestedFilters,sort:this.sort.key,dir:this.sort.dir,limit:this.perPage,page:this.currentPage}});if(requestId!==this.requestSerial)return;const body=response.data||{};this.resultFilters=requestedFilters;this.sync=body.sync||null;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:null,opening_balance_date:null,opening_balance_source:null,withdrawal_amount:0,withdrawal_count:0,withdrawal_latest_date:null,balance:null,balance_source:null,count:0};if(this.isPromotionMarketing){this.promotionExpenseSummary={income:Number(this.summary.income||0),expense:Number(this.summary.expense||0),balance:Number(this.summary.balance||0),count:Number(this.summary.count||0)};}if(body.columns){this.columnsTitle=body.columns.title||'';this.sourceGroups=body.columns.groups||[];this.sourceColumns=this.attachGroups(body.columns.columns||body.columns||[],this.sourceGroups);}}catch(error){if(requestId!==this.requestSerial)return;this.rows=[];this.total=0;this.sync=null;this.summary={income:0,expense:0,opening_balance:null,opening_balance_date:null,opening_balance_source:null,withdrawal_amount:0,withdrawal_count:0,withdrawal_latest_date:null,balance:null,balance_source:null,count:0};this.promotionExpenseSummary={income:0,expense:0,balance:0,count:0};this.loadError=true;}finally{if(requestId===this.requestSerial)this.loading=false;}}, attachGroups(columns,groups){let index=0;return columns.map((column,columnIndex)=>{while(groups[index]&&columnIndex>=groups.slice(0,index+1).reduce((sum,group)=>sum+Number(group.span||0),0))index+=1;return{...column,key:column.field||`column-${columnIndex}`,group:groups[index]?groups[index].label:''};});}, applyFilters(){if(this.invalidDateRange)return;const dateRangeChanged=this.queryFilters.start!==this.filters.start||this.queryFilters.end!==this.filters.end;this.queryFilters={...this.filters};this.currentPage=1;const requests=[this.fetch()];if(this.usesMirrorOptions&&!this.compact&&dateRangeChanged)requests.push(this.fetchFilterOptions());return Promise.all(requests);},resetFilters(){this.filters=filtersForRange();return this.applyFilters();},changePage(page){this.currentPage=page;this.fetch();this.$nextTick(()=>{if(this.$refs.scroll)this.$refs.scroll.scrollTop=0;});}, openDatePicker(refName){const picker=this.$refs[refName];if(picker&&picker.fp)picker.fp.open();}, @@ -573,7 +577,7 @@ export default { .tw-tools { flex: 1 1 24rem; min-width: 0; } .tw-stats--douyin { grid-template-columns: repeat(5, minmax(0, 1fr)); } .tw-stats--vipshop { grid-template-columns: repeat(5, minmax(0, 1fr)); } -.tw-stats--vipshop-jx { grid-template-columns: repeat(5, minmax(0, 1fr)); } +.tw-stats--vipshop-jx { grid-template-columns: repeat(6, minmax(0, 1fr)); } .tw-stats--xiaohongshu { grid-template-columns: repeat(5, minmax(0, 1fr)); } @media (max-width: 900px) { .tw-stats--douyin { grid-template-columns: repeat(2, minmax(0, 1fr)); } diff --git a/tests/Feature/Business/VipshopJxReceivingBillsTest.php b/tests/Feature/Business/VipshopJxReceivingBillsTest.php index 0466329b..825f57ca 100644 --- a/tests/Feature/Business/VipshopJxReceivingBillsTest.php +++ b/tests/Feature/Business/VipshopJxReceivingBillsTest.php @@ -8,6 +8,7 @@ use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use Modules\EcommerceFinance\Services\AccountLedgerRemarkMap; use Modules\EcommerceFinance\Models\AccountBill; +use Modules\EcommerceFinance\Repositories\VipshopJxBankPaymentRepository; use Modules\EcommerceFinance\Repositories\VipshopJxOpeningBalanceRepository; use Tests\Feature\FeatureTestCase; @@ -61,6 +62,53 @@ class VipshopJxReceivingBillsTest extends FeatureTestCase 'created_at' => now(), 'updated_at' => now(), ]); + DB::connection('business_mirror')->table(VipshopJxBankPaymentRepository::TABLE)->insert([ + [ + 'source_payment_id' => 1, + 'source_bill_number' => 'BILL-2026-06', + 'bill_period' => '2026-06', + 'pay_date' => '2026-07-01', + 'batch_number' => 'BATCH-1', + 'vendor_account_num' => '1105055609100026936', + 'amount' => '491948.53', + 'currency_code' => 'CNY', + 'pay_status' => 'SUCCESS', + 'source_hash' => str_repeat('a', 64), + 'imported_at' => now(), + 'created_at' => now(), + 'updated_at' => now(), + ], + [ + 'source_payment_id' => 2, + 'source_bill_number' => 'BILL-2026-07', + 'bill_period' => '2026-07', + 'pay_date' => '2026-10-10', + 'batch_number' => 'BATCH-2', + 'vendor_account_num' => '1105055609100026936', + 'amount' => '100', + 'currency_code' => 'CNY', + 'pay_status' => 'SUCCESS', + 'source_hash' => str_repeat('a', 64), + 'imported_at' => now(), + 'created_at' => now(), + 'updated_at' => now(), + ], + [ + 'source_payment_id' => 3, + 'source_bill_number' => 'BILL-2026-08', + 'bill_period' => '2026-08', + 'pay_date' => '2026-10-10', + 'batch_number' => 'BATCH-3', + 'vendor_account_num' => '1105055609100026936', + 'amount' => '30', + 'currency_code' => 'CNY', + 'pay_status' => 'SUCCESS', + 'source_hash' => str_repeat('a', 64), + 'imported_at' => now(), + 'created_at' => now(), + 'updated_at' => now(), + ], + ]); $this->bill('vipshop-jx', 'JUL-ROLL', '销售明细', '2026-07-09 00:00:00', 300, 50, '订单', '2026-07'); $this->bill('vipshop-jx', 'AUG-VIEW', '销售明细', '2026-08-09 00:00:00', 100, 20, '订单', '2026-08'); @@ -74,10 +122,12 @@ class VipshopJxReceivingBillsTest extends FeatureTestCase ->assertOk() ->assertJsonPath('summary.income', 100) ->assertJsonPath('summary.expense', 20) - ->assertJsonPath('summary.opening_balance', 492198.53) + ->assertJsonPath('summary.opening_balance', 150) ->assertJsonPath('summary.opening_balance_date', '2026-07-31') ->assertJsonPath('summary.opening_balance_source', 'previous_period') - ->assertJsonPath('summary.balance', 492278.53); + ->assertJsonPath('summary.withdrawal_amount', 30) + ->assertJsonPath('summary.withdrawal_count', 1) + ->assertJsonPath('summary.balance', 200); } public function test_vipshop_jx_filter_options_and_export_stay_inside_the_tab(): void @@ -204,6 +254,23 @@ class VipshopJxReceivingBillsTest extends FeatureTestCase $table->unique('period_end'); }); } + if (! $schema->hasTable(VipshopJxBankPaymentRepository::TABLE)) { + $schema->create(VipshopJxBankPaymentRepository::TABLE, function (Blueprint $table): void { + $table->id(); + $table->unsignedBigInteger('source_payment_id')->unique(); + $table->string('source_bill_number', 128); + $table->char('bill_period', 7); + $table->date('pay_date')->nullable(); + $table->string('batch_number', 64)->nullable(); + $table->string('vendor_account_num', 64); + $table->decimal('amount', 20, 6); + $table->string('currency_code', 8); + $table->string('pay_status', 24); + $table->string('source_hash', 64); + $table->dateTime('imported_at', 6); + $table->timestamps(6); + }); + } } private function allowPage(): void diff --git a/tests/Feature/Console/ImportVipshopJxBankPaymentsTest.php b/tests/Feature/Console/ImportVipshopJxBankPaymentsTest.php new file mode 100644 index 00000000..eddd73de --- /dev/null +++ b/tests/Feature/Console/ImportVipshopJxBankPaymentsTest.php @@ -0,0 +1,82 @@ + [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ], + 'upstream_mirrors.connection' => 'business_mirror', + ]); + DB::purge('business_mirror'); + (require database_path('migrations/2026_11_07_180000_create_vipshop_jx_bank_payments.php'))->up(); + } + + protected function tearDown(): void + { + if ($this->file !== null && is_file($this->file)) { + unlink($this->file); + } + parent::tearDown(); + } + + public function test_it_imports_only_successful_bank_account_payments_and_replaces_the_snapshot(): void + { + $payDate = (int) now()->setDate(2026, 10, 10)->startOfDay()->getTimestampMs(); + $rows = [ + $this->row(10, 'VIP-20260701-672378-P-003672', 127399.77, $payDate), + $this->row(11, 'VIP-20260711-672378-P-009568', 149428.92, $payDate), + $this->row(12, 'JIT_CZ-20260705-672378-M-029407', -71300.46, $payDate), + array_replace($this->row(13, 'VIP-20260721-672378-P-017554', 31226.97, $payDate), [ + 'vendorAccountNum' => '银行存款-中转', + ]), + array_replace($this->row(14, 'VIP-20260801-672378-P-003230', 100, $payDate), [ + 'payStatus' => 'FAILED', + ]), + ]; + $this->file = tempnam(sys_get_temp_dir(), 'vipshop-jx-bank-'); + file_put_contents($this->file, json_encode($rows, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)); + + $this->artisan('vipshop-jx:import-bank-payments', [ + 'file' => $this->file, + '--replace' => true, + ])->assertSuccessful(); + + $payments = DB::connection('business_mirror') + ->table(VipshopJxBankPaymentRepository::TABLE) + ->orderBy('source_payment_id') + ->get(['source_payment_id', 'bill_period', 'amount']); + $this->assertCount(3, $payments); + $this->assertSame([10, 11, 12], $payments->pluck('source_payment_id')->all()); + $this->assertSame(['2026-07', '2026-07', '2026-07'], $payments->pluck('bill_period')->all()); + $this->assertSame(205528.23, round((float) $payments->sum('amount'), 2)); + } + + private function row(int $id, string $billNumber, float $amount, int $payDate): array + { + return [ + 'id' => $id, + 'billNumber' => $billNumber, + 'billPayAmount' => $amount, + 'payDate' => $payDate, + 'batchNumber' => 'BATCH-' . $id, + 'vendorCode' => '672378', + 'vendorAccountNum' => '1105055609100026936', + 'currencyCode' => 'CNY', + 'payStatus' => 'SUCCESS', + ]; + } +} diff --git a/tests/Unit/EcommerceFinance/VipshopJxOpeningBalanceRepositoryTest.php b/tests/Unit/EcommerceFinance/VipshopJxOpeningBalanceRepositoryTest.php index 7c051913..3658fe4e 100644 --- a/tests/Unit/EcommerceFinance/VipshopJxOpeningBalanceRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/VipshopJxOpeningBalanceRepositoryTest.php @@ -3,6 +3,7 @@ namespace Tests\Unit\EcommerceFinance; use Illuminate\Support\Facades\DB; +use Modules\EcommerceFinance\Repositories\VipshopJxBankPaymentRepository; use Modules\EcommerceFinance\Repositories\VipshopJxOpeningBalanceRepository; use Tests\TestCase; @@ -21,6 +22,7 @@ class VipshopJxOpeningBalanceRepositoryTest extends TestCase ]); DB::purge('business_mirror'); (require database_path('migrations/2026_11_07_120000_create_vipshop_jx_opening_balance_snapshots.php'))->up(); + (require database_path('migrations/2026_11_07_180000_create_vipshop_jx_bank_payments.php'))->up(); } public function test_opening_balance_rolls_from_june_ending_by_settlement_period(): void @@ -36,19 +38,24 @@ class VipshopJxOpeningBalanceRepositoryTest extends TestCase ]); $this->bill($companyId, 'JUL-A', '2026-07', '300', '50'); $this->bill($companyId, 'AUG-A', '2026-08', '100', '20'); + $this->payment(1, 'BILL-2026-06', '2026-06', '491948.53'); + $this->payment(2, 'BILL-2026-07', '2026-07', '100'); + $this->payment(3, 'BILL-2026-08', '2026-08', '30'); $repository = app(VipshopJxOpeningBalanceRepository::class); $july = $repository->openingBalance('2026-07-01', '2026-07-31'); $august = $repository->openingBalance('2026-08-01', '2026-08-31'); $september = $repository->openingBalance('2026-09-01', '2026-09-30'); - $this->assertSame(491948.53, $july['balance']); + $this->assertSame(0.0, $july['balance']); $this->assertSame('2026-06-30', $july['date']); - $this->assertSame('june_ending', $july['source']); - $this->assertSame(492198.53, $august['balance']); + $this->assertSame('bank_settled', $july['source']); + $this->assertSame(100.0, $july['withdrawal_amount']); + $this->assertSame(150.0, $august['balance']); $this->assertSame('2026-07-31', $august['date']); $this->assertSame('previous_period', $august['source']); - $this->assertSame(492278.53, $september['balance']); + $this->assertSame(30.0, $august['withdrawal_amount']); + $this->assertSame(200.0, $september['balance']); } public function test_it_returns_no_opening_balance_before_the_june_baseline(): void @@ -85,4 +92,27 @@ class VipshopJxOpeningBalanceRepositoryTest extends TestCase 'updated_at' => now(), ]); } + + private function payment( + int $sourcePaymentId, + string $billNumber, + string $billPeriod, + string $amount, + ): void { + DB::connection('business_mirror')->table(VipshopJxBankPaymentRepository::TABLE)->insert([ + 'source_payment_id' => $sourcePaymentId, + 'source_bill_number' => $billNumber, + 'bill_period' => $billPeriod, + 'pay_date' => $billPeriod . '-15', + 'batch_number' => 'BATCH-' . $sourcePaymentId, + 'vendor_account_num' => '1105055609100026936', + 'amount' => $amount, + 'currency_code' => 'CNY', + 'pay_status' => 'SUCCESS', + 'source_hash' => str_repeat('a', 64), + 'imported_at' => now(), + 'created_at' => now(), + 'updated_at' => now(), + ]); + } } diff --git a/tests/Unit/View/AccountBillsTableTest.php b/tests/Unit/View/AccountBillsTableTest.php index 4db79544..a6043a34 100644 --- a/tests/Unit/View/AccountBillsTableTest.php +++ b/tests/Unit/View/AccountBillsTableTest.php @@ -196,16 +196,29 @@ class AccountBillsTableTest extends TestCase $this->assertStringContainsString("'tw-stats--vipshop-jx': billType === 'vipshop-jx'", $source); $this->assertStringContainsString("if(this.billType==='vipshop-jx')", $source); - $this->assertStringContainsString('平台历史账单累计', $source); + $this->assertStringContainsString('历史账单已扣银行卡结算', $source); + $this->assertStringContainsString("label:'提现金额'", $source); + $this->assertStringContainsString('账单已结算至银行卡', $source); $this->assertStringContainsString('上一账期期末', $source); $this->assertStringContainsString("label:'期末余额'", $source); - $this->assertStringContainsString("note:'期初余额 + 收入合计 - 支出合计'", $source); + $this->assertStringContainsString("note:'期初余额 + 收入合计 - 支出合计 - 提现金额'", $source); + $julyStart = strpos($source, "if(this.billType==='vipshop-jx')"); + $julyEnd = strpos($source, "if(this.billType==='xiaohongshu')", $julyStart); + $julyStats = substr($source, $julyStart, $julyEnd - $julyStart); $this->assertLessThan( - strpos($source, "label:'收入合计'"), - strpos($source, "label:'期初余额'"), + strpos($julyStats, "label:'收入合计'"), + strpos($julyStats, "label:'期初余额'"), + ); + $this->assertLessThan( + strpos($julyStats, "label:'提现金额'"), + strpos($julyStats, "label:'支出合计'"), + ); + $this->assertLessThan( + strpos($julyStats, "label:'期末余额'"), + strpos($julyStats, "label:'提现金额'"), ); $this->assertStringContainsString( - '.tw-stats--vipshop-jx { grid-template-columns: repeat(5, minmax(0, 1fr)); }', + '.tw-stats--vipshop-jx { grid-template-columns: repeat(6, minmax(0, 1fr)); }', $source, ); } -- 2.47.2