From 0a5f8744ce4c50a796414028ea87f14d4d17d41f Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Fri, 4 Dec 2026 14:29:18 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E9=99=84=E5=8A=A0=E8=B4=B9=E5=AF=B9?= =?UTF-8?q?=E8=B4=A6):=20=E7=BB=9F=E4=B8=80=E5=8C=B9=E9=85=8D=E8=B4=A6?= =?UTF-8?q?=E5=8D=95=E5=BD=93=E6=9C=88=E8=B5=B7=E4=B8=89=E4=B8=AA=E6=9C=88?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=20(#1731)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BillSurchargeQuoteCalculator.php | 18 ++++++++++++- .../SurchargeSettlementMatcher.php | 14 ++++++++--- docs/附加费账单匹配.md | 2 +- .../partials/surcharge-matches.blade.php | 2 +- .../Business/BillSurchargeMatchingTest.php | 25 +++++++++++++++++++ 5 files changed, 54 insertions(+), 7 deletions(-) diff --git a/app/Support/CourierBills/BillSurchargeQuoteCalculator.php b/app/Support/CourierBills/BillSurchargeQuoteCalculator.php index a6fe0daa7..bc46e4f97 100644 --- a/app/Support/CourierBills/BillSurchargeQuoteCalculator.php +++ b/app/Support/CourierBills/BillSurchargeQuoteCalculator.php @@ -3,12 +3,22 @@ namespace App\Support\CourierBills; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Carbon; use Modules\EcommerceFinance\Services\CustomerServiceSurchargeSynchronizer as ServiceFees; use Modules\EcommerceFinance\Services\WorkOrderWaybillLookup; /** 账单按票核价:只读现有报价及共享镜像,不将账单金额当作结算依据。 */ final class BillSurchargeQuoteCalculator { + /** 所有附加费均按自然月含账单当月,匹配最近3个月。 */ + public static function window(string $month): array + { + $start = Carbon::parse($month . '-01')->startOfMonth(); + $months = 3; + return ['from' => $start->copy()->subMonthsNoOverflow($months - 1)->toDateString(), + 'until' => $start->copy()->addMonth()->toDateString(), 'months' => $months]; + } + public function calculate(array $input, string $scope, string $month, array $allowedCouriers): array { if ($input === [] || $allowedCouriers === []) return ['rows' => [], 'notes' => [], 'metadata' => []]; @@ -23,6 +33,7 @@ final class BillSurchargeQuoteCalculator $needsService = $rules->contains(fn ($r) => $r->mode === '聚工单客服核实'); $workOrders = $needsService ? $this->workOrders($waybills, $month) : []; $rows = $notes = $metadata = []; + $window = self::window($month); foreach ($input as $fee) { $wb = strtoupper($fee['waybill_no']); $type = SurchargeSettlementMatcher::type($fee['item']); $ship = $ships[$wb] ?? []; $courier = $ship['express_name1'] ?? ''; @@ -42,6 +53,10 @@ final class BillSurchargeQuoteCalculator $notes[$wb][$type] = $candidates->isEmpty() ? '该快递没有启用的对应费用报价' : '发货日期未达到报价生效日或没有发货记录'; continue; } + if ($date < $window['from']) { + $notes[$wb][$type] = '发货日期超出匹配范围:' . $window['from'] . ' 至 ' . Carbon::parse($window['until'])->subDay()->toDateString(); + 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, @@ -112,7 +127,8 @@ final class BillSurchargeQuoteCalculator 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'))) + ->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']); $result = []; foreach ($rows as $row) $result[strtoupper($row->waybill)][$row->woNo] = $row; diff --git a/app/Support/CourierBills/SurchargeSettlementMatcher.php b/app/Support/CourierBills/SurchargeSettlementMatcher.php index ea6b4a6eb..44835222d 100644 --- a/app/Support/CourierBills/SurchargeSettlementMatcher.php +++ b/app/Support/CourierBills/SurchargeSettlementMatcher.php @@ -136,10 +136,10 @@ class SurchargeSettlementMatcher $source=[]; if($db->getSchemaBuilder()->hasTable('courier_surcharge_settlement_rows')){ $sourceQuery=$db->table('courier_surcharge_settlement_rows')->whereIn('waybill',$waybills)->where('settlement_status','已计算'); - $end=date('Y-m-d',strtotime($month.'-01 +1 month')); + $window=BillSurchargeQuoteCalculator::window($month);$end=$window['until']; if($db->getSchemaBuilder()->hasColumn('courier_surcharge_settlement_rows','source_created_at')){ - $sourceQuery->where(fn($q)=>$q->whereRaw('COALESCE(source_created_at,shipped_at) < ?',[$end])->orWhere(fn($q)=>$q->whereNull('source_created_at')->whereNull('shipped_at'))); - }else{$sourceQuery->where(fn($q)=>$q->whereNull('shipped_at')->orWhere('shipped_at','<',$end));} + $sourceQuery->whereRaw('COALESCE(source_created_at,shipped_at) >= ?',[$window['from']])->whereRaw('COALESCE(source_created_at,shipped_at) < ?',[$end]); + }else{$sourceQuery->where('shipped_at','>=',$window['from'])->where('shipped_at','<',$end);} foreach($sourceQuery ->orderBy('id')->get() as $r)$source[strtoupper($r->waybill)][self::type($r->surcharge_type)][]=$r; } @@ -173,7 +173,13 @@ class SurchargeSettlementMatcher $belongs=$allowed!==[]; if(!$belongs)$row['match_note']='无法确认该单属于本厂家代发快递及仓库'; } - $rows=array_values(array_filter($rows,fn($r)=>in_array($r->courier_name,$allowed,true))); + $window=BillSurchargeQuoteCalculator::window($month); + $rows=array_values(array_filter($rows,function($r)use($allowed,$window){ + $date=substr((string)($r->source_created_at??$r->shipped_at??''),0,10); + $shipped=substr((string)($r->shipped_at??''),0,10); + return in_array($r->courier_name,$allowed,true)&&$date!==''&&$date>=$window['from']&&$date<$window['until'] + &&($shipped===''||($shipped>=$window['from']&&$shipped<$window['until'])); + })); $priced=array_values(array_filter($calculated['rows'][$wb][$type]??[],fn($r)=>in_array($r->courier_name,$allowed,true))); // 已支持的报价按票核价优先,避免同单号多张出库记录把每票费用重复累加。 if($priced!==[])$rows=$priced; diff --git a/docs/附加费账单匹配.md b/docs/附加费账单匹配.md index 177731848..ff93da13e 100644 --- a/docs/附加费账单匹配.md +++ b/docs/附加费账单匹配.md @@ -1,6 +1,6 @@ # 附加费账单匹配 -快递账单和代发账单以账单月份归集附加费。按完整快递单号、规范化费用类型、快递归属匹配 `courier_surcharge_settlement_rows` 中“已计算”的金额;允许匹配以前月份费用,不把账单金额当自算金额。客服费用以工单创建时间、其他费用以发货时间确定上界,不取账期之后的费用。 +快递账单和代发账单以账单月份归集附加费。按完整快递单号、规范化费用类型、快递归属匹配 `courier_surcharge_settlement_rows` 中“已计算”的金额;统一匹配包含账单当月在内最近3个自然月,不把账单金额当自算金额。例如11月账单匹配9月1日(含)至12月1日(不含)的数据,跨年同样按自然月计算。发货记录、客服工单和来源结算均受此时间范围限制;无日期记录不自动计费。已计入其他账单的费用仍去重,不因跨月重复结算。 新文件导入时自动匹配,已有账单可用 `courier-surcharge:match-bills --month=2026-11 --statement=11` 或 `--factory=厂家ID` 校准,也可 `--all` 处理当月未确认账单。命令省略月份时取北京时间上月,生产每天 07:05 使用 `--all --existing-only` 更新已经建立匹配的账单;首次历史回补单独确认,部署和定时任务不会自动启用旧账单。命令必须走 `run-finance-batch.sh`,共用上游互斥锁和独立批容器,PHP 512 MiB、容器 1 GiB、最长 3600 秒,失败按同范围重跑。每份账单的更新在事务内;不改已确认快递账单或厂家确认状态,不重算原运费行,手工小汇总优先。 diff --git a/resources/views/business/pages/courier-payables/partials/surcharge-matches.blade.php b/resources/views/business/pages/courier-payables/partials/surcharge-matches.blade.php index 58bc1412c..f40054903 100644 --- a/resources/views/business/pages/courier-payables/partials/surcharge-matches.blade.php +++ b/resources/views/business/pages/courier-payables/partials/surcharge-matches.blade.php @@ -1,7 +1,7 @@ @if ($surchargeRows !== null && $surchargeRows->total() > 0)

附加费核对明细

-

按账单月份归集,以单号、附加费类型和快递归属匹配结算金额,可匹配以前月份的费用。未匹配的金额留空,重复费用不再计入;不会将对方金额作为自算金额。

+

按账单月份归集,以单号、附加费类型和快递归属匹配最近3个月(含账单当月)的结算金额。未匹配的金额留空,重复费用不再计入;不会将对方金额作为自算金额。

@foreach (['来源工作表','快递单号','附加费类型','对方金额','自算金额','差额','匹配状态','快递名称','平台商品ID','商品编码','店铺名称','线上订单号','说明'] as $label)@endforeach@foreach ($surchargeRows as $fee) diff --git a/tests/Feature/Business/BillSurchargeMatchingTest.php b/tests/Feature/Business/BillSurchargeMatchingTest.php index d8b86b6b6..3a5416130 100644 --- a/tests/Feature/Business/BillSurchargeMatchingTest.php +++ b/tests/Feature/Business/BillSurchargeMatchingTest.php @@ -257,4 +257,29 @@ class BillSurchargeMatchingTest extends FeatureTestCase $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']); } + + public function test_all_fees_use_three_calendar_months_including_the_bill_month(): void + { + $calc=app(\App\Support\CourierBills\BillSurchargeQuoteCalculator::class); + $this->assertSame(['from'=>'2026-09-01','until'=>'2026-12-01','months'=>3],$calc::window('2026-11')); + $this->assertSame(['from'=>'2026-11-01','until'=>'2027-02-01','months'=>3],$calc::window('2027-01')); + $this->quote('测试快递','拦截费','取发出运费','等于发出运费','取发出运费','自有快递'); + $this->quote('测试快递','上楼费','聚工单客服核实','读取聚工单附加费明细','聚工单客服回复通过','自有快递'); + $db=DB::connection('business_mirror');$input=[]; + foreach(['2026-08-31 23:59:59','2026-09-01 00:00:00','2026-10-31 23:59:59','2026-11-30 23:59:59','2026-12-01 00:00:00'] as $i=>$date){ + $no='WINDOW000'.$i;$this->ship($no,'测试快递');$db->table('jst_oms_shipping')->where('express_no',$no)->update(['ship_time'=>$date]); + $this->workOrder($no,'测试快递','上楼费','5','通过',$date); + $input[]=['waybill_no'=>$no,'item'=>'拦截费'];$input[]=['waybill_no'=>$no,'item'=>'上楼费']; + } + $result=$calc->calculate($input,'courier','2026-11',['测试快递']); + foreach([1,2,3] as $i){$this->assertEquals(10,$result['rows']['WINDOW000'.$i]['拦截费'][0]->settlement_amount);$this->assertEquals(5,$result['rows']['WINDOW000'.$i]['上楼费'][0]->settlement_amount);} + $this->assertArrayNotHasKey('WINDOW0000',$result['rows']);$this->assertArrayNotHasKey('WINDOW0004',$result['rows']); + // 已生成结算明细走同一日期范围,不能绕过下界。 + $store=app(CourierBillStore::class);$store->saveGroup(null,['name'=>'来源快递','express_names'=>['来源快递']]); + foreach(['2026-08-31','2026-09-01','2026-11-30','2026-12-01'] as $i=>$date)$this->fee('SOURCE000'.$i,'上楼费',7,'来源快递',$date); + $path=$this->book(['账单'=>[['单号','运费'],['SOURCE0001',10]],'附加费'=>[['快递单号','附加费金额','附加费类型'],['SOURCE0000',7,'上楼费'],['SOURCE0001',7,'上楼费'],['SOURCE0002',7,'上楼费'],['SOURCE0003',7,'上楼费']]]); + $fid=$store->upload([new UploadedFile($path,'来源快递11月.xlsx',null,null,true)],'2026-11',[],'测试')[0];$sid=$db->table('courier_bill_files')->where('id',$fid)->value('statement_id'); + $rows=app(SurchargeSettlementMatcher::class)->query('courier',$sid)->orderBy('row_no')->get(); + $this->assertSame([null,7.0,7.0,null],$rows->map(fn($r)=>$r->self_amount===null?null:(float)$r->self_amount)->all()); + } }
{{ $label }}