diff --git a/app/Support/CourierBills/BillSurchargeQuoteCalculator.php b/app/Support/CourierBills/BillSurchargeQuoteCalculator.php new file mode 100644 index 000000000..a6fe0daa7 --- /dev/null +++ b/app/Support/CourierBills/BillSurchargeQuoteCalculator.php @@ -0,0 +1,121 @@ + [], 'notes' => [], 'metadata' => []]; + $rules = DB::table('business_courier_surcharge_quotes')->where('company_id', (int) (company_id() ?: 1)) + ->where('status', 'active')->whereNull('deleted_at')->whereIn('courier', $allowedCouriers) + ->where('scope', $scope === 'dropship' ? '代发仓' : '自有快递') + ->orderByDesc('effective_at')->orderByDesc('id')->get(); + $waybills = array_values(array_unique(array_column($input, 'waybill_no'))); + $shipping = app(ShippingLookup::class); + $ships = $shipping->details($waybills); + $freights = $shipping->summaries($waybills); + $needsService = $rules->contains(fn ($r) => $r->mode === '聚工单客服核实'); + $workOrders = $needsService ? $this->workOrders($waybills, $month) : []; + $rows = $notes = $metadata = []; + foreach ($input as $fee) { + $wb = strtoupper($fee['waybill_no']); $type = SurchargeSettlementMatcher::type($fee['item']); + $ship = $ships[$wb] ?? []; $courier = $ship['express_name1'] ?? ''; + $date = substr((string) ($ship['ship_time'] ?? ''), 0, 10); + $metadata[$wb] = ['courier_name' => $courier ?: null, 'platform_product_id' => $ship['item_id'] ?? null, + 'product_code' => $ship['barcode'] ?? null, 'shop_name' => $ship['shop_name'] ?? null, + 'online_order_no' => $ship['trade_no'] ?? null]; + if($date !== '' && $date >= date('Y-m-d', strtotime($month . '-01 +1 month'))){ + $notes[$wb][$type]='发货日期晚于账单月份,未计入本月'; + continue; + } + $candidates = $rules->filter(fn ($r) => $r->courier === $courier + && in_array($type, array_map([SurchargeSettlementMatcher::class, 'type'], json_decode($r->types, true) ?: []), true)); + $rule = $candidates->first(fn ($r) => $date !== '' && substr($r->effective_at, 0, 10) + <= ($r->mode === '聚工单客服核实' ? $month . '-31' : $date)); + if ($rule === null) { + $notes[$wb][$type] = $candidates->isEmpty() ? '该快递没有启用的对应费用报价' : '发货日期未达到报价生效日或没有发货记录'; + continue; + } + $base = ['rule_id' => $rule->id, 'courier_name' => $courier, 'waybill' => $wb, 'surcharge_type' => $type, + 'shipped_at' => $ship['ship_time'] ?? null, 'source_created_at' => null, + 'platform_product_id' => $ship['item_id'] ?? null, 'product_code' => $ship['barcode'] ?? null, + 'shop_name' => $ship['shop_name'] ?? null, 'online_order_no' => $ship['trade_no'] ?? null, + 'source_kind' => 'bill_quote', 'source_key' => $wb . '|' . $type, 'outbound_io_id' => null]; + $result = $this->price($rule, $type, $ship, $freights[$wb] ?? [], $workOrders[$wb] ?? []); + if (is_string($result)) { $notes[$wb][$type] = '报价 #' . $rule->id . ':' . $result; continue; } + foreach ($result as $price) $rows[$wb][$type][] = (object) array_replace($base, $price, + ['settlement_status' => '已计算', 'evidence' => '报价 #' . $rule->id . ';' . $price['evidence']]); + } + return compact('rows', 'notes', 'metadata'); + } + + 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->standard), ['取发出运费', '等于发出运费'], true)) return '计价标准尚未支持自动核验'; + if (($freight['calc_freight'] ?? null) === null) return '发出运费尚未核算完成'; + $amount = round($freight['calc_freight'], 2); + return [['settlement_amount' => $amount, 'evidence' => '取本票已核算发出运费 ' . number_format($amount, 2, '.', '') . ' 元']]; + } + if ($rule->mode === '按尺寸/最长边') { + if (! preg_match('/^(?:单边超|最长边超过?)\s*(\d+(?:\.\d+)?)\s*(?:cm|厘米)$/iu', trim($rule->condition), $threshold) + || ! preg_match('/^(\d+(?:\.\d+)?)\s*元?\s*\/\s*单$/u', trim($rule->standard), $price)) return '尺寸计费条件或单价尚未支持自动核验'; + $sides = [(float) ($ship['length_cm'] ?? 0), (float) ($ship['width_cm'] ?? 0), (float) ($ship['height_cm'] ?? 0)]; + if (min($sides) <= 0) return '发货商品缺少完整尺寸'; + $max = max($sides); $amount = $max > (float) $threshold[1] ? (float) $price[1] : 0; + return [['settlement_amount' => $amount, 'evidence' => '最长边 ' . $max . 'cm,报价阈值 ' . $threshold[1] . 'cm,按票计费']]; + } + if ($rule->mode !== '聚工单客服核实') return '计费方式“' . $rule->mode . '”尚未接入账单自动核价'; + if (trim($rule->standard) !== '读取聚工单附加费明细') return '客服计价标准尚未支持自动核验'; + $condition = trim($rule->condition); + if (preg_match('/^重量\s*(\d+(?:\.\d+)?)\s*(?:kg|公斤|千克)以上[,,、]?上楼费聚工单客服回复通过$/iu', $condition, $weight)) { + if (($freight['charge_weight'] ?? null) === null) return '缺少已核算计费重量,无法检查上楼费门槛'; + if ((float) $freight['charge_weight'] < (float) $weight[1]) return [['settlement_amount' => 0, + 'evidence' => '本票计费重量 ' . $freight['charge_weight'] . 'kg,未达到 ' . $weight[1] . 'kg 门槛,不计费']]; + } elseif (! in_array($condition, ['聚工单客服回复通过', '改地址客服回复通过'], true)) return '客服附加条件尚未支持自动核验'; + $result = []; $found = false; + foreach ($orders as $order) { + $fields = []; + foreach (json_decode($order->businessFieldList, true, 512, JSON_THROW_ON_ERROR) ?: [] as $f) if (isset($f['fieldId'])) $fields[$f['fieldId']] = $f; + if (($fields['logisticsField']['value'] ?? '') !== $rule->courier + || substr($order->created, 0, 10) < substr($rule->effective_at, 0, 10) + || in_array($order->status, ['CANCELLED', 'CANCELED', 'DELETED', '取消', '已取消'], true)) continue; + $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] ?? '')), + }; + if ($actualType !== $type) continue; + $found = true; + if (($v[ServiceFees::FEE_APPROVAL] ?? '') !== '通过') continue; + $amount = trim((string) ($v[ServiceFees::FEE_AMOUNT] ?? '')); + if (! preg_match('/^\d{1,9}(?:\.\d{1,2})?$/D', $amount)) return '客服已通过的费用金额无效'; + $cents += (int) round((float) $amount * 100); + } + if ($cents > 0) $result[] = ['settlement_amount' => $cents / 100, + 'source_kind' => ServiceFees::KIND, 'source_key' => $order->woNo, 'source_created_at' => $order->created, + 'evidence' => '聚工单 ' . $order->woNo . ' 附加费明细逐项审核通过']; + } + return $result ?: ($found ? '对应工单附加费未审核通过' : '未找到对应单号、费用类型和快递的客服费用明细'); + } + + private function workOrders(array $waybills, string $month): array + { + if (! app(WorkOrderWaybillLookup::class)->ready()) return []; + $rows = DB::connection(config('upstream_mirrors.connection', 'business_mirror')) + ->table(WorkOrderWaybillLookup::TABLE . ' as l')->join(WorkOrderWaybillLookup::SOURCE . ' as w', 'w._mirror_key', '=', 'l.mirror_key') + ->whereIn('l.waybill', $waybills)->where('w.created', '<', date('Y-m-d', strtotime($month . '-01 +1 month'))) + ->orderBy('w.Id')->get(['l.waybill', 'w.woNo', 'w.created', 'w.status', 'w.businessFieldList']); + $result = []; + foreach ($rows as $row) $result[strtoupper($row->waybill)][$row->woNo] = $row; + return $result; + } +} diff --git a/app/Support/CourierBills/SurchargeSettlementMatcher.php b/app/Support/CourierBills/SurchargeSettlementMatcher.php index ceac3dd90..abbf5b4e8 100644 --- a/app/Support/CourierBills/SurchargeSettlementMatcher.php +++ b/app/Support/CourierBills/SurchargeSettlementMatcher.php @@ -23,7 +23,7 @@ class SurchargeSettlementMatcher return match ($type) { '改地址费','改址费','改址' => '改地址', '上楼','直客上楼费' => '上楼费', '超长' => '超长费', - '退件费','退货费','退回运费' => '退回费', '拦截' => '拦截费', + '退件费','退货费','退回运费' => '退回费', '拦截','拦截退回' => '拦截费', '派送费','派件费','直客派送费' => '送货费', '保价费' => '保费', '入仓费' => '进仓费', '直客超区费' => '超区费', default => $type, }; @@ -150,6 +150,15 @@ class SurchargeSettlementMatcher foreach(json_decode($r->settlement_ids??'[]',true)?:[] as $sid)$prior[$sid]=$r->bill_month; $ships=$factory?$this->ships($waybills):[]; $own=$factory?array_fill_keys(app(DropshipFreightStore::class)->ownExpressNames(),true):[]; + $allowedCouriers=$names; + if($factory){ + $keywords=DropshipFreightStore::splitKeywords($factory->keywords); + foreach($ships as $ship)foreach(array_keys($ship['pairs'][$factory->warehouse]??[]) as $express) + if(!isset($own[$express])&&array_filter($keywords,fn($k)=>str_contains($express,$k))!==[])$allowedCouriers[]=$express; + } + $unresolved=array_values(array_filter($input,fn($f)=>array_filter($source[strtoupper($f['waybill_no'])][self::type($f['item'])]??[], + fn($r)=>in_array($r->courier_name,$allowedCouriers,true))===[])); + $calculated=app(BillSurchargeQuoteCalculator::class)->calculate($unresolved,$scope,$month,array_values(array_unique($allowedCouriers))); $output=[]; foreach($input as $f){ $type=self::type($f['item']);$wb=strtoupper($f['waybill_no']);$rows=$source[$wb][$type]??[]; @@ -167,6 +176,11 @@ class SurchargeSettlementMatcher if(!$belongs)$row['match_note']='无法确认该单属于本厂家代发快递及仓库'; } $rows=array_values(array_filter($rows,fn($r)=>in_array($r->courier_name,$allowed,true))); + if($rows===[]){ + $rows=array_values(array_filter($calculated['rows'][$wb][$type]??[],fn($r)=>in_array($r->courier_name,$allowed,true))); + 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]??[]); + } $identity=$wb.'|'.$type; if(isset($seen[$identity])){$row['self_amount']=0;$row['match_status']='重复';$row['match_note']='本月账单已提供该单号及费用类型,不重复结算';} elseif($rows!==[]){ @@ -185,10 +199,12 @@ class SurchargeSettlementMatcher $seen[$identity]=true;$row['self_amount']=round(array_sum(array_map(fn($r)=>(float)$r->settlement_amount,$rows)),2); $row['match_status']='已匹配';$row['settlement_ids']=json_encode(array_map($keyOf,$rows)); $row['match_note']='按单号、费用类型及快递匹配;归入'.$month.'账单'.($partlyPaid?';已扣除其他账单已计入费用':''); + $evidence=array_values(array_unique(array_filter(array_map(fn($r)=>$r->evidence??null,$rows)))); + if($evidence!==[])$row['match_note'].=';'.implode(';',$evidence); foreach(['courier_name','platform_product_id','product_code','shop_name','online_order_no'] as $key) $row[$key]=implode('、',array_values(array_unique(array_filter(array_map(fn($r)=>trim((string)($r->$key??'')),$rows))))); } - } elseif($rows===[] && ($source[$wb]??[])!==[]) $row['match_note']='单号存在,但费用类型或快递归属不符'; + } elseif($rows===[] && ($source[$wb]??[])!==[]&&!isset($calculated['notes'][$wb][$type])) $row['match_note']='单号存在,但费用类型或快递归属不符'; $output[]=$row; } $db->table(self::TABLE)->insert($output); diff --git a/docs/附加费账单匹配.md b/docs/附加费账单匹配.md index 78fb01a40..177731848 100644 --- a/docs/附加费账单匹配.md +++ b/docs/附加费账单匹配.md @@ -9,3 +9,7 @@ 同一账期重复提供的单号+费用类型只计一次;同一费用来源已被其他账单计入时不再计入,仅新出现的费用来源可继续计入。同一单号不同费用类型分别核对;匹配不到或快递归属不符时自算金额留空并显示原因。代发还要求发货仓库及快递名称同时属于该厂家,排除自有快递。多个商品信息去重后展示,金额按票汇总,不乘商品数。 查询/校准不会写上游报价或来源费用;删除账单文件时清除其派生匹配结果。真实账单、备份与生产日志保留在 Git 忽略的私有目录。 + +结算表没有对应结果时,导入及重新匹配会按本票实际快递、报价适用范围和生效日自动核价,并从发货镜像补齐商品、店铺和订单信息。已接入“取发出运费”(按本票全部包裹核算运费合计)、“按尺寸/最长边”及“聚工单客服核实”。账单“拦截退回”对应“拦截费”;客服明细“拦截退回运费”对应“退回费”。其他计费方式或尚未接入的附加条件保留空值并显示具体原因,不推测金额。 + +客服费用通过现有单号索引读取共享工单,要求同一快递、费用类型一致、逐项审核通过且工单在账单月份结束前创建;按工单归集,不按商品数重复计费。“重量60kg以上”先检查本票已核算计费重量,低于门槛计0;缺重量、缺审核、无报价分别显示原因。原始账单、报价和发货运费均不改写。 diff --git a/tests/Feature/Business/BillSurchargeMatchingTest.php b/tests/Feature/Business/BillSurchargeMatchingTest.php index a876aeda0..549b46524 100644 --- a/tests/Feature/Business/BillSurchargeMatchingTest.php +++ b/tests/Feature/Business/BillSurchargeMatchingTest.php @@ -169,4 +169,85 @@ class BillSurchargeMatchingTest extends FeatureTestCase } protected function tearDown(): void {foreach($this->temp as $path)@unlink($path);parent::tearDown();} + + private function quote(string $courier,string $type,string $mode,string $standard,string $condition,string $scope='代发仓'): int + { + return DB::table('business_courier_surcharge_quotes')->insertGetId(['company_id'=>(int)$this->company->id, + 'courier'=>$courier,'scope'=>$scope,'reconciler'=>'测试','types'=>json_encode([$type]),'mode'=>$mode, + '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 + { + $schema=Schema::connection('business_mirror'); + if(!$schema->hasTable('js_jst_work_order_info'))$schema->create('js_jst_work_order_info',function(Blueprint $t){ + $t->string('_mirror_key')->primary();$t->integer('Id');$t->string('woNo');$t->string('title');$t->string('status');$t->dateTime('created');$t->text('businessFieldList'); + }); + $fields=[['fieldId'=>'lIdField','value'=>$no],['fieldId'=>'logisticsField','value'=>$courier], + ['fieldId'=>\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::FEE_TABLE,'childFieldList'=>[[ + ['fieldId'=>\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::FEE_TYPE,'value'=>$type], + ['fieldId'=>\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::FEE_AMOUNT,'value'=>$amount], + ['fieldId'=>\Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer::FEE_APPROVAL,'value'=>$approved], + ]]]]; + $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)]; + $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()]); + } + + public function test_import_calculates_outbound_freight_and_does_not_apply_other_courier_rules(): void + { + $store=app(DropshipFreightStore::class);$id=$store->saveFactory(null,['name'=>'测试厂家','warehouse'=>'测试仓','keywords'=>'测试']); + $this->quote('测试圆通','拦截费','取发出运费','等于发出运费','取发出运费'); + $this->ship('YT11111111','测试圆通');$this->ship('ST11111111','测试申通'); + $db=$store->db();$db->table('jst_oms_shipping')->where('express_no','YT11111111')->update(['item_id'=>'12345678901234567890','barcode'=>'SKU001','shop_name'=>'测试店','trade_no'=>'ORDER001']); + $path=$this->book(['账单'=>[['单号','运费'],['YT11111111',2],['ST11111111',3]], + '附加费'=>[['快递单号','附加费金额','附加费类型'],['YT11111111',999,'拦截退回'],['YT11111111',999,'拦截费'],['ST11111111',999,'拦截退回']]]); + $store->uploadFor('测试厂家11月.xlsx',$path,'2026-11',$id,'测试'); + $rows=app(SurchargeSettlementMatcher::class)->query('dropship',$id,'2026-11')->orderBy('id')->get(); + $this->assertEquals(10,$rows[0]->self_amount);$this->assertEquals(0,$rows[1]->self_amount);$this->assertNull($rows[2]->self_amount); + $this->assertSame('重复',$rows[1]->match_status);$this->assertSame('SKU001',$rows[0]->product_code); + $this->assertSame('12345678901234567890',$rows[0]->platform_product_id);$this->assertSame('ORDER001',$rows[0]->online_order_no); + $this->assertStringContainsString('取本票已核算发出运费',$rows[0]->match_note); + $this->assertStringContainsString('没有启用',$rows[2]->match_note); + } + + 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'=>['测试德邦']]); + $this->quote('测试德邦','上楼费','聚工单客服核实','读取聚工单附加费明细','重量60kg以上,上楼费聚工单客服回复通过','自有快递'); + foreach(['DP11111111','DP22222222','DP33333333','DP44444444','DP55555555'] as $n)$this->ship($n,'测试德邦'); + $db=$store->db();$db->table('jst_oms_shipping_freight')->update(['charge_weight'=>60]); + $sid=$db->table('jst_oms_shipping')->where('express_no','DP22222222')->value('source_id');$db->table('jst_oms_shipping_freight')->where('source_id',$sid)->update(['charge_weight'=>59.99]); + $this->workOrder('DP11111111','测试德邦','上楼费','37.50','通过'); + $this->workOrder('DP22222222','测试德邦','上楼费','77','通过'); + $this->workOrder('DP33333333','测试德邦','上楼费','77',null); + $this->workOrder('DP44444444','测试德邦','上楼费','77','通过','2026-12-01 00:00:00'); + $path=$this->book(['账单'=>[['单号','运费'],['DP11111111',10]],'附加费'=>[['快递单号','附加费金额','附加费类型'], + ['DP11111111',99,'上楼费'],['DP22222222',99,'上楼费'],['DP33333333',99,'上楼费'],['DP44444444',99,'上楼费'],['DP55555555',99,'改地址费']]]); + $fid=$store->upload([new UploadedFile($path,'测试德邦11月.xlsx',null,null,true)],'2026-11',[],'测试')[0]; + $id=(int)$db->table('courier_bill_files')->where('id',$fid)->value('statement_id');$rows=app(SurchargeSettlementMatcher::class)->query('courier',$id)->orderBy('id')->get(); + $this->assertEquals(37.50,$rows[0]->self_amount);$this->assertEquals(0,$rows[1]->self_amount);$this->assertNull($rows[2]->self_amount);$this->assertNull($rows[3]->self_amount); + $this->assertStringContainsString('未达到',$rows[1]->match_note);$this->assertStringContainsString('未审核通过',$rows[2]->match_note); + $this->assertStringContainsString('没有启用',$rows[4]->match_note); + } + + public function test_quote_scope_effective_date_missing_freight_and_size_boundaries(): void + { + $this->ship('QA11111111','测试快递');$this->ship('QA22222222','测试快递'); + $this->quote('测试快递','超长费','按尺寸/最长边','7元/单','单边超160cm','自有快递'); + $db=DB::connection('business_mirror');$db->table('jst_oms_shipping')->update(['length_cm'=>160,'width_cm'=>20,'height_cm'=>20]); + $db->table('jst_oms_shipping')->where('express_no','QA22222222')->update(['length_cm'=>160.01]); + $input=[['waybill_no'=>'QA11111111','item'=>'超长费'],['waybill_no'=>'QA22222222','item'=>'超长费']];$calc=app(\App\Support\CourierBills\BillSurchargeQuoteCalculator::class); + $result=$calc->calculate($input,'courier','2026-11',['测试快递']);$this->assertEquals(0,$result['rows']['QA11111111']['超长费'][0]->settlement_amount);$this->assertEquals(7,$result['rows']['QA22222222']['超长费'][0]->settlement_amount); + $this->assertSame([],$calc->calculate($input,'dropship','2026-11',['测试快递'])['rows']); + DB::table('business_courier_surcharge_quotes')->update(['effective_at'=>'2026-12-01']);$this->assertSame([],$calc->calculate($input,'courier','2026-11',['测试快递'])['rows']); + DB::table('business_courier_surcharge_quotes')->update(['effective_at'=>'2026-01-01','mode'=>'取发出运费','standard'=>'等于发出运费','condition'=>'取发出运费']); + $db->table('jst_oms_shipping_freight')->update(['status'=>'FAILED']);$this->assertStringContainsString('尚未核算完成',$calc->calculate($input,'courier','2026-11',['测试快递'])['notes']['QA11111111']['超长费']); + $db->table('jst_oms_shipping')->where('express_no','QA11111111')->update(['ship_time'=>'2026-12-01 00:00:00']); + $this->assertStringContainsString('晚于账单月份',$calc->calculate($input,'courier','2026-11',['测试快递'])['notes']['QA11111111']['超长费']); + $db->table('jst_oms_shipping')->where('express_no','QA11111111')->update(['ship_time'=>'2026-11-02 00:00:00']); + DB::table('business_courier_surcharge_quotes')->update(['deleted_at'=>now()]);$this->assertSame([],$calc->calculate($input,'courier','2026-11',['测试快递'])['rows']); + } }