fix(附加费对账): 按工单买家原因核算拦截费 #1732

Closed
limeng wants to merge 1 commits from fix/limeng-intercept-fee-alias into main
6 changed files with 127 additions and 13 deletions

View File

@ -30,7 +30,8 @@ final class BillSurchargeQuoteCalculator
$shipping = app(ShippingLookup::class);
$ships = $shipping->details($waybills);
$freights = $shipping->summaries($waybills);
$needsService = $rules->contains(fn ($r) => $r->mode === '聚工单客服核实');
$needsService = $rules->contains(fn ($r) => $r->mode === '聚工单客服核实'
|| ($r->mode === '取发出运费' && trim($r->condition) === '查件扣单并且买家原因'));
$workOrders = $needsService ? $this->workOrders($waybills, $month) : [];
$rows = $notes = $metadata = [];
$window = self::window($month);
@ -53,6 +54,8 @@ final class BillSurchargeQuoteCalculator
$notes[$wb][$type] = $candidates->isEmpty() ? '该快递没有启用的对应费用报价' : '发货日期未达到报价生效日或没有发货记录';
continue;
}
// 买家原因必须按当前工单核验,缺少依据时不能回退到旧结算金额。
if ($rule->mode === '取发出运费' && trim($rule->condition) === '查件扣单并且买家原因') $rows[$wb][$type] = [];
if ($date < $window['from']) {
$notes[$wb][$type] = '发货日期超出匹配范围:' . $window['from'] . ' 至 ' . Carbon::parse($window['until'])->subDay()->toDateString();
continue;
@ -73,11 +76,18 @@ final class BillSurchargeQuoteCalculator
private function price(object $rule, string $type, array $ship, array $freight, array $orders): array|string
{
if ($rule->mode === '取发出运费') {
if (! in_array(trim($rule->condition), ['取发出运费', '等于发出运费'], true)) return '计费条件尚未支持自动核验';
if (! in_array(trim($rule->condition), ['取发出运费', '等于发出运费', '查件扣单并且买家原因'], true)) return '计费条件尚未支持自动核验';
if (! in_array(trim($rule->standard), ['取发出运费', '等于发出运费'], true)) return '计价标准尚未支持自动核验';
$evidence = '';
if (trim($rule->condition) === '查件扣单并且买家原因') {
$reason = $this->buyerReason($rule, $orders);
if (is_string($reason)) return $reason;
if (! $reason['eligible']) return [['settlement_amount' => 0, 'evidence' => $reason['evidence']]];
$evidence = $reason['evidence'] . ';';
}
if (($freight['calc_freight'] ?? null) === null) return '发出运费尚未核算完成';
$amount = round($freight['calc_freight'], 2);
return [['settlement_amount' => $amount, 'evidence' => '取本票已核算发出运费 ' . number_format($amount, 2, '.', '') . ' 元']];
return [['settlement_amount' => $amount, 'evidence' => $evidence . '取本票已核算发出运费 ' . number_format($amount, 2, '.', '') . ' 元']];
}
if ($rule->mode === '按尺寸/最长边') {
if (! preg_match('/^(?:单边超|最长边超过?)\s*(\d+(?:\.\d+)?)\s*(?:cm|厘米)$/iu', trim($rule->condition), $threshold)
@ -105,9 +115,7 @@ final class BillSurchargeQuoteCalculator
$cents = 0;
foreach ($fields[ServiceFees::FEE_TABLE]['childFieldList'] ?? [] as $line) {
$v = array_column($line, 'value', 'fieldId');
$actualType = match (trim((string) ($v[ServiceFees::FEE_TYPE] ?? ''))) {
'拦截退回运费' => '退回费', default => SurchargeSettlementMatcher::type((string) ($v[ServiceFees::FEE_TYPE] ?? '')),
};
$actualType = SurchargeSettlementMatcher::type((string) ($v[ServiceFees::FEE_TYPE] ?? ''));
if ($actualType !== $type) continue;
$found = true;
if (($v[ServiceFees::FEE_APPROVAL] ?? '') !== '通过') continue;
@ -122,6 +130,28 @@ final class BillSurchargeQuoteCalculator
return $result ?: ($found ? '对应工单附加费未审核通过' : '未找到对应单号、费用类型和快递的客服费用明细');
}
private function buyerReason(object $rule, array $orders): array|string
{
$reasons = [];
foreach ($orders as $order) {
$fields = array_column(json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [], 'value', 'fieldId');
if (($fields['logisticsField'] ?? '') !== $rule->courier
|| substr($order->created, 0, 10) < substr($rule->effective_at, 0, 10)
|| in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true)) continue;
$reasons[] = ['order' => $order, 'reason' => trim((string) ($fields['SELECT_CASCADEField1413856620250813172526'] ?? ''))];
}
if ($reasons === []) return '未找到有效的同快递查件工单,无法核实买家原因';
// 同票多工单以最新扣单原因核验;其他查件操作不覆盖扣单原因,费用仍按票只计一次。
usort($reasons, fn ($a, $b) => [$b['order']->created, $b['order']->source_id] <=> [$a['order']->created, $a['order']->source_id]);
$deductions = array_values(array_filter($reasons, fn ($r) => trim(explode('/', $r['reason'], 2)[0]) === '扣单'));
$latest = $deductions[0] ?? $reasons[0];
[$operation, $cause] = array_map('trim', array_pad(explode('/', $latest['reason'], 2), 2, ''));
if ($operation === '' || $cause === '' || $cause === '买家-') return '查件工单原因不完整,无法核实买家原因';
$eligible = $operation === '扣单' && str_starts_with($cause, '买家-');
return ['eligible' => $eligible, 'evidence' => '聚工单 ' . $latest['order']->woNo . ' 原因:' . $latest['reason']
. ($eligible ? ',符合买家原因条件' : ',不符合扣单且买家原因条件,不计费')];
}
private function workOrders(array $waybills, string $month): array
{
if (! app(WorkOrderWaybillLookup::class)->ready()) return [];
@ -129,7 +159,7 @@ final class BillSurchargeQuoteCalculator
->table(WorkOrderWaybillLookup::TABLE . ' as l')->join(WorkOrderWaybillLookup::SOURCE . ' as w', 'w._mirror_key', '=', 'l.mirror_key')
->whereIn('l.waybill', $waybills)->where('w.created', '>=', self::window($month)['from'])
->where('w.created', '<', self::window($month)['until'])
->orderBy('w.Id')->get(['l.waybill', 'w.woNo', 'w.created', 'w.status', 'w.businessFieldList']);
->orderBy('w.Id')->get(['l.waybill', 'w.Id as source_id', 'w.woNo', 'w.created', 'w.status', 'w.businessFieldList']);
$result = [];
foreach ($rows as $row) $result[strtoupper($row->waybill)][$row->woNo] = $row;
return $result;

View File

@ -23,7 +23,7 @@ class SurchargeSettlementMatcher
return match ($type) {
'改地址费','改址费','改址' => '改地址',
'上楼','直客上楼费' => '上楼费', '超长' => '超长费',
'退件费','退货费','退回运费' => '退回费', '拦截','拦截退回' => '拦截费',
'退件费','退货费','退回运费' => '退回费', '拦截','拦截退回','拦截退回运费' => '拦截费',
'派送费','派件费','直客派送费' => '送货费', '保价费' => '保费',
'入仓费' => '进仓费', '直客超区费' => '超区费', default => $type,
};
@ -182,7 +182,7 @@ class SurchargeSettlementMatcher
}));
$priced=array_values(array_filter($calculated['rows'][$wb][$type]??[],fn($r)=>in_array($r->courier_name,$allowed,true)));
// 已支持的报价按票核价优先,避免同单号多张出库记录把每票费用重复累加。
if($priced!==[])$rows=$priced;
if(array_key_exists($type,$calculated['rows'][$wb]??[]))$rows=$priced;
if($rows===[]){
if(isset($calculated['notes'][$wb][$type])&&(!$factory||$allowed!==[]))$row['match_note']=$calculated['notes'][$wb][$type];
if(!$factory||$allowed!==[])$row=array_replace($row,$calculated['metadata'][$wb]??[]);

View File

@ -10,6 +10,8 @@
查询/校准不会写上游报价或来源费用;删除账单文件时清除其派生匹配结果。真实账单、备份与生产日志保留在 Git 忽略的私有目录。
结算表没有对应结果时,导入及重新匹配会按本票实际快递、报价适用范围和生效日自动核价,并从发货镜像补齐商品、店铺和订单信息。已接入“取发出运费”(按本票全部包裹核算运费合计)、“按尺寸/最长边”及“聚工单客服核实”。账单“拦截退回”对应“拦截费”;客服明细“拦截退回运费”对应“退回费”。其他计费方式或尚未接入的附加条件保留空值并显示具体原因,不推测金额。
结算表没有对应结果时,导入及重新匹配会按本票实际快递、报价适用范围和生效日自动核价,并从发货镜像补齐商品、店铺和订单信息。已接入“取发出运费”(按本票全部包裹核算运费合计)、“按尺寸/最长边”及“聚工单客服核实”。账单及客服明细的“拦截”“拦截退回”“拦截退回运费”统一对应“拦截费”。其他计费方式或尚未接入的附加条件保留空值并显示具体原因,不推测金额。
“取发出运费”的“查件扣单并且买家原因”条件,按同一单号、同一快递、匹配时间范围内的有效查件工单核验原因分类,要求为“扣单/买家-具体原因”,不要求退回进仓。多个扣单工单采用最新有效工单(创建时间、来源ID排序),取消工单不参与;明确非买家原因计0,缺工单或原因不完整保持未匹配。核对说明保留工单号和原始原因,每票发出运费只计一次。
客服费用通过现有单号索引读取共享工单,要求同一快递、费用类型一致、逐项审核通过且工单在账单月份结束前创建;按工单归集,不按商品数重复计费。“重量60kg以上”先检查本票已核算计费重量,低于门槛计0;缺重量、缺审核、无报价分别显示原因。原始账单、报价和发货运费均不改写。

View File

@ -384,6 +384,9 @@ class CourierSurchargeSettlementMirrorRepository
'退货件' => '退回费',
'超长' => '超长费',
'改地址费' => '改地址',
'拦截' => '拦截费',
'拦截退回' => '拦截费',
'拦截退回运费' => '拦截费',
][$type] ?? $type;
}

View File

@ -194,6 +194,6 @@ class CustomerServiceSurchargeSynchronizer
public static function normalizeType(string $type): string
{
return match ($type) { '改地址费' => '改地址', default => $type };
return match ($type) { '改地址费' => '改地址', '拦截','拦截退回','拦截退回运费' => '拦截费', default => $type };
}
}

View File

@ -177,7 +177,7 @@ class BillSurchargeMatchingTest extends FeatureTestCase
'standard'=>$standard,'condition'=>$condition,'effective_at'=>'2026-01-01','status'=>'active','created_at'=>now(),'updated_at'=>now()]);
}
private function workOrder(string $no,string $courier,string $type,string $amount,?string $approved,string $created='2026-11-03 10:00:00'): void
private function workOrder(string $no,string $courier,string $type,string $amount,?string $approved,string $created='2026-11-03 10:00:00',?string $reason=null,string $status='WAIT_CONFIRM'): void
{
$schema=Schema::connection('business_mirror');
if(!$schema->hasTable('js_jst_work_order_info'))$schema->create('js_jst_work_order_info',function(Blueprint $t){
@ -189,8 +189,9 @@ class BillSurchargeMatchingTest extends FeatureTestCase
['fieldId'=>\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::FEE_AMOUNT,'value'=>$amount],
['fieldId'=>\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::FEE_APPROVAL,'value'=>$approved],
]]]];
if($reason!==null)$fields[]=['fieldId'=>'SELECT_CASCADEField1413856620250813172526','value'=>$reason];
$db=DB::connection('business_mirror');$id=$db->table('js_jst_work_order_info')->count()+1;
$row=['_mirror_key'=>'work-'.$id,'Id'=>$id,'woNo'=>'GD-'.$id,'title'=>'查件','status'=>'WAIT_CONFIRM','created'=>$created,'businessFieldList'=>json_encode($fields)];
$row=['_mirror_key'=>'work-'.$id,'Id'=>$id,'woNo'=>'GD-'.$id,'title'=>'查件','status'=>$status,'created'=>$created,'businessFieldList'=>json_encode($fields)];
$db->table('js_jst_work_order_info')->insert($row);
app(\Modules\EcommerceFinance\Services\WorkOrderWaybillLookup::class)->storeBatch([$row]);
$db->table('work_order_waybill_lookup_states')->updateOrInsert(['id'=>1],['completed_at'=>now(),'updated_at'=>now()]);
@ -213,6 +214,84 @@ class BillSurchargeMatchingTest extends FeatureTestCase
$this->assertStringContainsString('没有启用',$rows[2]->match_note);
}
public function test_buyer_intercept_uses_structured_reason_without_requiring_a_return_or_approved_fee(): void
{
$store=app(DropshipFreightStore::class);$id=$store->saveFactory(null,['name'=>'测试厂家','warehouse'=>'测试仓','keywords'=>'测试']);
$this->quote('测试申通','拦截费','取发出运费','等于发出运费','查件扣单并且买家原因');
$cases=[['BUYER0001','扣单/买家-不想要',10],['BUYER0002','扣单/买家-冲动消费',10],
['BUYER0003','扣单/快递-破损',0],['BUYER0004','扣单/超时未更新物流信息【有揽收物流更新异常】',0],
['BUYER0005',null,null],['BUYER0006','扣单/',null],['BUYER0007','扣单/买家-',null],['BUYER0008','催件/买家-不想要',0]];
$fees=[['快递单号','附加费金额','附加费类型']];
foreach($cases as [$no,$reason,$amount]){
$this->ship($no,'测试申通');
if($reason!==null)$this->workOrder($no,'测试申通','', '',null,'2026-11-03 10:00:00',$reason);
$fees[]=[$no,999,'拦截退回'];
}
// 同票重复别名只付一次;旧结算结果不能绕过买家原因核验。
$fees[]=['BUYER0001',999,'拦截退回运费'];
$this->fee('BUYER0003','拦截费',99,'测试申通');$this->fee('BUYER0005','拦截费',99,'测试申通');
$path=$this->book(['账单'=>[['单号','运费'],['BUYER0001',10]],'附加费'=>$fees]);
$store->uploadFor('测试买家原因11月.xlsx',$path,'2026-11',$id,'测试');
$rows=app(SurchargeSettlementMatcher::class)->query('dropship',$id,'2026-11')->orderBy('row_no')->get();
foreach($cases as $i=>[$no,$reason,$amount]){
$this->assertSame($amount===null?null:(float)$amount,$rows[$i]->self_amount===null?null:(float)$rows[$i]->self_amount,$no);
$this->assertSame($amount===null?'未匹配':'已匹配',$rows[$i]->match_status,$no);
}
$this->assertStringContainsString('扣单/买家-不想要',$rows[0]->match_note);
$this->assertStringContainsString('快递-破损',$rows[2]->match_note);
$this->assertSame('重复',$rows[8]->match_status);$this->assertEquals(20,$rows->sum('self_amount'));
}
public function test_buyer_reason_requires_valid_courier_status_dates_and_latest_deduction(): void
{
$this->quote('测试申通','拦截费','取发出运费','等于发出运费','查件扣单并且买家原因');
$cases=[
['VALID0001','测试申通','2026-09-01 00:00:00','WAIT_CONFIRM',10],
['VALID0002','测试申通','2026-08-31 23:59:59','WAIT_CONFIRM',null],
['VALID0003','测试申通','2026-12-01 00:00:00','WAIT_CONFIRM',null],
['VALID0004','其他申通','2026-11-03 10:00:00','WAIT_CONFIRM',null],
['VALID0005','测试申通','2026-11-03 10:00:00','CANCELLED',null],
['VALID0006','测试申通','2026-11-30 23:59:59','FINISHED',10],
];$input=[];
foreach($cases as [$no,$courier,$date,$status,$amount]){
$this->ship($no,'测试申通');$this->workOrder($no,$courier,'','',null,$date,'扣单/买家-不想要',$status);
$input[]=['waybill_no'=>$no,'item'=>'拦截费'];
}
$this->ship('LATEST001','测试申通');$input[]=['waybill_no'=>'LATEST001','item'=>'拦截费'];
$this->workOrder('LATEST001','测试申通','','',null,'2026-11-02 10:00:00','扣单/买家-不想要');
$this->workOrder('LATEST001','测试申通','','',null,'2026-11-03 10:00:00','扣单/快递-破损');
$this->workOrder('LATEST001','测试申通','','',null,'2026-11-04 10:00:00','扣单/买家-冲动消费','CANCELLED');
$this->workOrder('LATEST001','测试申通','','',null,'2026-11-05 10:00:00','催件/买家-不想要');
$calc=app(\App\Support\CourierBills\BillSurchargeQuoteCalculator::class);
$result=$calc->calculate($input,'dropship','2026-11',['测试申通']);
foreach($cases as [$no,$courier,$date,$status,$amount]){
if($amount===null){$this->assertSame([],$result['rows'][$no]['拦截费']);$this->assertStringContainsString('无法核实',$result['notes'][$no]['拦截费']);}
else $this->assertEquals($amount,$result['rows'][$no]['拦截费'][0]->settlement_amount);
}
$this->assertEquals(0,$result['rows']['LATEST001']['拦截费'][0]->settlement_amount);
$this->assertStringContainsString('快递-破损',$result['rows']['LATEST001']['拦截费'][0]->evidence);
// 报价生效前的工单和未建完的单号索引都不能作为依据。
DB::table('business_courier_surcharge_quotes')->update(['effective_at'=>'2026-10-01']);
$this->assertStringContainsString('无法核实',$calc->calculate([$input[0]],'dropship','2026-11',['测试申通'])['notes']['VALID0001']['拦截费']);
DB::connection('business_mirror')->table('work_order_waybill_lookup_states')->update(['completed_at'=>null]);
$this->assertStringContainsString('无法核实',$calc->calculate([$input[5]],'dropship','2026-11',['测试申通'])['notes']['VALID0006']['拦截费']);
}
public function test_intercept_aliases_are_consistent_across_bill_customer_service_and_import(): void
{
$repository=app(\Modules\EcommerceFinance\Repositories\CourierSurchargeSettlementMirrorRepository::class);
$normalizer=new \ReflectionMethod($repository,'normalizeImportType');
foreach(['拦截','拦截退回','拦截退回运费','拦截费'] as $alias){
$this->assertSame('拦截费',SurchargeSettlementMatcher::type($alias));
$this->assertSame('拦截费',\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::normalizeType($alias));
$this->assertSame('拦截费',$normalizer->invoke($repository,$alias));
}
$this->quote('测试申通','拦截费','聚工单客服核实','读取聚工单附加费明细','聚工单客服回复通过');
$this->ship('ALIAS0001','测试申通');$this->workOrder('ALIAS0001','测试申通','拦截退回运费','8.25','通过');
$result=app(\App\Support\CourierBills\BillSurchargeQuoteCalculator::class)->calculate([['waybill_no'=>'ALIAS0001','item'=>'拦截退回']],'dropship','2026-11',['测试申通']);
$this->assertEquals(8.25,$result['rows']['ALIAS0001']['拦截费'][0]->settlement_amount);
}
public function test_customer_service_approval_weight_gate_and_missing_rule_are_explicit(): void
{
$store=app(CourierBillStore::class);$group=$store->saveGroup(null,['name'=>'测试德邦','express_names'=>['测试德邦']]);