diff --git a/app/Support/CourierBills/SurchargeSettlementMatcher.php b/app/Support/CourierBills/SurchargeSettlementMatcher.php index 5d32a9fbe..9c7da08bd 100644 --- a/app/Support/CourierBills/SurchargeSettlementMatcher.php +++ b/app/Support/CourierBills/SurchargeSettlementMatcher.php @@ -5,11 +5,13 @@ namespace App\Support\CourierBills; use App\Support\DropshipFreight\DropshipFreightStore; use Illuminate\Support\Facades\DB; use RuntimeException; +use Modules\EcommerceFinance\Services\SupplierPayableOverrideStore; /** 按账单月份归集,逐票/费用类型匹配结算表;不改来源报价和费用。 */ class SurchargeSettlementMatcher { public const TABLE = 'bill_surcharge_matches'; + public const PAID_HISTORY = 'bill-surcharge-paid-history'; public const HEADERS = ['账单月份','来源工作表','原始行号','快递单号','附加费类型','对方金额','自算金额','差额','匹配状态','快递名称','平台商品ID','商品编码','店铺名称','线上订单号','说明']; public function ready(): bool @@ -17,6 +19,11 @@ class SurchargeSettlementMatcher return DB::connection('business_mirror')->getSchemaBuilder()->hasTable(self::TABLE); } + public static function paidHistoryKey(string $scope, int $owner, string $month, string $waybill, string $type): string + { + return implode('|', [$scope, $owner, $month, strtoupper(trim($waybill)), self::type($type)]); + } + public static function type(string $type): string { $type = preg_replace('/\s+/u', '', $type) ?? ''; @@ -158,8 +165,10 @@ class SurchargeSettlementMatcher if(!isset($own[$express])&&array_filter($keywords,fn($k)=>str_contains($express,$k))!==[])$allowedCouriers[]=$express; } $calculated=app(BillSurchargeQuoteCalculator::class)->calculate($input,$scope,$month,array_values(array_unique($allowedCouriers))); + $historyRows = array_map(fn ($fee) => ['id' => self::paidHistoryKey($scope, $owner, $month, $fee['waybill_no'], $fee['item'])], $input); + $history = app(SupplierPayableOverrideStore::class)->decorate(self::PAID_HISTORY, $historyRows, (int) (company_id() ?: 1)); $output=[]; - foreach($input as $f){ + foreach($input as $index=>$f){ $type=self::type($f['item']);$wb=strtoupper($f['waybill_no']);$rows=$source[$wb][$type]??[]; $row=['scope'=>$scope,'owner_id'=>$owner,'file_id'=>$f['file_id'],'sheet'=>$f['sheet'],'row_no'=>$f['row_no'], 'bill_month'=>$month,'waybill_no'=>$wb,'item'=>$type,'summary_label'=>$f['label'],'bill_amount'=>$f['amount'],'self_amount'=>null, @@ -216,6 +225,15 @@ class SurchargeSettlementMatcher $row[$key]=implode('、',array_values(array_unique(array_filter(array_map(fn($r)=>trim((string)($r->$key??'')),$rows))))); } } elseif($rows===[] && ($source[$wb]??[])!==[]&&!isset($calculated['notes'][$wb][$type])) $row['match_note']='单号存在,但费用类型或快递归属不符'; + $paid = $history[$index]; + $settledMonth = (string) ($paid['settled_month'] ?? ''); + if ($paid['_overridden'] && preg_match('/^\d{4}-(0[1-9]|1[0-2])$/D', $settledMonth) + && $settledMonth < $month) { + $row['self_amount'] = 0; + $row['match_status'] = '历史已计入'; + $row['match_note'] = '财务确认:' . $settledMonth . '已结算,本期不重复结算'; + $seen[$identity] = true; + } $output[]=$row; } $db->table(self::TABLE)->insert($output); diff --git a/tests/Feature/Business/BillSurchargeMatchingTest.php b/tests/Feature/Business/BillSurchargeMatchingTest.php index b7f23fdbd..df284c76c 100644 --- a/tests/Feature/Business/BillSurchargeMatchingTest.php +++ b/tests/Feature/Business/BillSurchargeMatchingTest.php @@ -132,6 +132,40 @@ class BillSurchargeMatchingTest extends FeatureTestCase $this->artisan('courier-surcharge:match-bills',['--all-months'=>true])->assertFailed(); } + public function test_paid_history_zeroes_only_the_exact_fee_and_survives_rematching(): void + { + $store=app(CourierBillStore::class);$db=$store->db(); + $group=$store->saveGroup(null,['name'=>'历史费用测试','express_names'=>['历史费用测试']]); + $sid=$db->table('courier_bill_statements')->insertGetId(['group_id'=>$group,'bill_month'=>'2026-11','status'=>'open','created_at'=>now(),'updated_at'=>now()]); + $fid=$db->table('courier_bill_files')->insertGetId(['statement_id'=>$sid,'bill_month'=>'2026-11','group_id'=>$group,'original_name'=>'test','stored_path'=>'test','status'=>'parsed','created_at'=>now(),'updated_at'=>now()]); + foreach([['HISTORY-FEE01','超长费',8],['HISTORY-FEE01','超长费',8],['HISTORY-FEE01','拦截费',30], + ['HISTORY-FEE010','超长费',8],['HISTORY-FEE02','超长费',8]] as $i=>[$no,$type,$amount]){ + $db->table('courier_bill_surcharges')->insert(['file_id'=>$fid,'sheet'=>'附加费','row_no'=>$i+2,'waybill_no'=>$no,'item'=>$type,'amount'=>$amount]); + if($i!==1)$this->fee($no,$type,$amount,'历史费用测试'); + } + $overrides=app(\Modules\EcommerceFinance\Services\SupplierPayableOverrideStore::class); + $key=SurchargeSettlementMatcher::paidHistoryKey('courier',$sid,'2026-11','HISTORY-FEE01','超长费'); + $overrides->save(SurchargeSettlementMatcher::PAID_HISTORY,'id:'.$key,['settled_month'=>'2026-10'],(int)$this->company->id,null); + $otherKey=SurchargeSettlementMatcher::paidHistoryKey('courier',$sid,'2026-11','HISTORY-FEE010','超长费'); + $overrides->save(SurchargeSettlementMatcher::PAID_HISTORY,'id:'.$otherKey,['settled_month'=>'2026-10'],(int)$this->company->id+1,null); + $futureKey=SurchargeSettlementMatcher::paidHistoryKey('courier',$sid,'2026-11','HISTORY-FEE02','超长费'); + $overrides->save(SurchargeSettlementMatcher::PAID_HISTORY,'id:'.$futureKey,['settled_month'=>'2026-12'],(int)$this->company->id,null); + foreach([1,2] as $_){ + app(CourierBillMatcher::class)->refreshSurchargeSummary($sid); + $rows=app(SurchargeSettlementMatcher::class)->query('courier',$sid)->orderBy('row_no')->get(); + $this->assertEquals([0,0,30,8,8],$rows->pluck('self_amount')->all()); + $this->assertSame('历史已计入',$rows[0]->match_status); + $this->assertStringContainsString('2026-10已结算',$rows[0]->match_note); + $this->assertEquals(8,$rows[0]->bill_amount); + $this->assertEquals(46,$db->table('courier_bill_summary_items')->where('statement_id',$sid)->value('self_amount')); + } + $snapshot=$rows->toJson(); + $db->table('courier_bill_statements')->where('id',$sid)->update(['status'=>'confirmed']); + $db->table('courier_surcharge_settlement_rows')->update(['settlement_amount'=>999]); + app(CourierBillMatcher::class)->refreshSurchargeSummary($sid); + $this->assertSame($snapshot,app(SurchargeSettlementMatcher::class)->query('courier',$sid)->orderBy('row_no')->get()->toJson()); + } + public function test_daily_refresh_does_not_enable_legacy_bills_and_only_new_sources_are_counted(): void { $db=DB::connection('business_mirror');$store=app(CourierBillStore::class);