From 882447989d7b8be2c148a28d220f7afd790f9f63 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Sun, 6 Dec 2026 14:33:50 +0800 Subject: [PATCH 1/4] =?UTF-8?q?=E5=BF=AB=E9=80=92=E5=BA=94=E4=BB=98?= =?UTF-8?q?=E6=B1=87=E6=80=BB=EF=BC=9A=E8=87=AA=E5=8A=A8=E5=AE=9E=E4=BB=98?= =?UTF-8?q?=E3=80=81=E5=90=88=E5=90=8C=E6=97=A5=E6=9C=9F=E4=B8=8E=E5=AF=B9?= =?UTF-8?q?=E8=B4=A6=E7=8A=B6=E6=80=81=E7=AD=9B=E9=80=89=20(#1776)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Business/CourierContractPageData.php | 30 +++ app/Support/CourierBills/PayableSummary.php | 17 +- app/Support/CourierBills/SummaryMapper.php | 5 +- .../courier-payable-summary.blade.php | 14 +- .../Feature/Business/CourierBillPagesTest.php | 2 +- .../CourierPayableSummaryRulesTest.php | 197 ++++++++++++++++++ 6 files changed, 256 insertions(+), 9 deletions(-) create mode 100644 tests/Feature/Business/CourierPayableSummaryRulesTest.php diff --git a/app/Business/CourierContractPageData.php b/app/Business/CourierContractPageData.php index a5a5d1e12..1be548e21 100644 --- a/app/Business/CourierContractPageData.php +++ b/app/Business/CourierContractPageData.php @@ -96,6 +96,36 @@ class CourierContractPageData } } + /** @return array 同名快递取最新归档合作合同的日期。 */ + public function datesByCourierNames(array $names): array + { + $names = array_values(array_unique(array_filter(array_map('trim', $names)))); + if ($names === [] || ! Schema::hasTable('business_courier_agreement_signatures')) { + return []; + } + + $dates = []; + foreach (array_chunk($names, 500) as $chunk) { + $signatures = CourierAgreementSignature::query()->where('company_id', (int) company_id()) + ->where('document_type', 'cooperation-contract')->where('status', CourierAgreementSignature::STATUS_ARCHIVED) + ->whereIn('courier_name', $chunk) + ->select(['id', 'courier_name', 'payload', 'document_type', 'status']) + ->orderByDesc('archived_at')->orderByDesc('id')->cursor(); + foreach ($signatures as $signature) { + $name = trim((string) $signature->courier_name); + if (isset($dates[$name]) || ($payload = $signature->archivedCourierContractPayload()) === null) { + continue; + } + $dates[$name] = [ + 'start_date' => $this->date($payload['cooperation_start_date'] ?? null), + 'end_date' => $this->date($payload['cooperation_end_date'] ?? null), + ]; + } + } + + return $dates; + } + private function filters(): array { $search = request()->query('contract_search'); diff --git a/app/Support/CourierBills/PayableSummary.php b/app/Support/CourierBills/PayableSummary.php index 036d12ec0..a182ae302 100644 --- a/app/Support/CourierBills/PayableSummary.php +++ b/app/Support/CourierBills/PayableSummary.php @@ -2,6 +2,7 @@ namespace App\Support\CourierBills; +use App\Business\CourierContractPageData; use Illuminate\Database\ConnectionInterface; use Modules\EcommerceFinance\Repositories\CourierInformationMirrorRepository; use RuntimeException; @@ -38,7 +39,10 @@ final class PayableSummary /** 有对账单时由小汇总覆盖的列。 */ private const FROM_STATEMENTS = ['J', 'K', 'L', 'N', 'O', 'P', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT']; - public function __construct(private readonly CourierInformationMirrorRepository $couriers) {} + public function __construct( + private readonly CourierInformationMirrorRepository $couriers, + private readonly CourierContractPageData $contractDates, + ) {} public function db(): ConnectionInterface { @@ -66,6 +70,7 @@ final class PayableSummary report($error); $contracts = []; } + $contractDates = $this->contractDates->datesByCourierNames($stored->pluck('carrier')->all()); $today = now()->toDateString(); $rows = []; foreach ($stored as $row) { @@ -77,6 +82,9 @@ final class PayableSummary $cells['C'] = $contract['company'] !== '' ? $contract['company'] : ($cells['C'] ?? null); $cells['G'] = $contract['body'] !== '' ? $contract['body'] : ($cells['G'] ?? null); } + $dates = $contractDates[$row->carrier] ?? []; + $cells['A'] = $dates['start_date'] ?? ($cells['A'] ?? null); + $cells['B'] = $dates['end_date'] ?? ($cells['B'] ?? null); $mine = $statements[$row->carrier] ?? []; // 导入的汇总里已经有金额(手工做完的月份):以导入为准,对账单算出来的只用来比对; // 新建的月份金额是空的,才用对账单的小汇总填。 @@ -182,6 +190,13 @@ final class PayableSummary if ($row === null) { throw new RuntimeException('汇总行不存在。'); } + if ($column === 'S') { + foreach ($this->rows((string) $row->month) as $current) { + if ($current['id'] === $rowId && $current['cells']['R'] > 0) { + throw new RuntimeException('本月应付金额大于 0 时,本次实付金额自动等于本月应付金额,无需手工修改。'); + } + } + } $cells = (array) json_decode((string) $row->cells, true); if (in_array($column, self::MONEY, true)) { $number = BillParser::number($value); diff --git a/app/Support/CourierBills/SummaryMapper.php b/app/Support/CourierBills/SummaryMapper.php index aacfa184f..e52893645 100644 --- a/app/Support/CourierBills/SummaryMapper.php +++ b/app/Support/CourierBills/SummaryMapper.php @@ -126,12 +126,15 @@ final class SummaryMapper ]; } - /** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L。 */ + /** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L;R > 0 时实付 S = R。 */ public static function totals(array $cells): array { $n = static fn (string $key): float => (float) ($cells[$key] ?? 0); $cells['M'] = round($n('K') - $n('L'), 2); $cells['R'] = round($n('K') - $n('L') - $n('N') - $n('O') - $n('P') + $n('Q') + $n('J') + $n('I'), 2); + if ($cells['R'] > 0) { + $cells['S'] = $cells['R']; + } return $cells; } diff --git a/resources/views/business/pages/courier-payables/courier-payable-summary.blade.php b/resources/views/business/pages/courier-payables/courier-payable-summary.blade.php index 81b70c065..a9a676510 100644 --- a/resources/views/business/pages/courier-payables/courier-payable-summary.blade.php +++ b/resources/views/business/pages/courier-payables/courier-payable-summary.blade.php @@ -33,8 +33,8 @@ + - @if ($psStatus)@endif @@ -80,7 +80,7 @@ {{ $c['H'] ?? '' }} {{ $row['status'] === '已确认' ? '核对无误' : $row['status'] }} @foreach ($main as $k) - @if (isset($editable[$k])) + @if (isset($editable[$k]) && ! ($k === 'S' && ($c['R'] ?? 0) > 0)) @else {{ $money($c[$k] ?? 0) }} @@ -106,7 +106,7 @@ - + @endif @@ -148,7 +148,8 @@

已用 10 月 36 份手工对账表里的 42 个小汇总验证:按下面的规则归集,与手工快递汇总表逐行、逐列一致。小汇总里的项目名称决定归到哪一列,依次判断,命中即停。

- + + @@ -167,7 +168,8 @@ - + +
合同开始/截止时间、签订公司、快递公司主体名称取「快递资料」(按承运商名称);快递资料里没有的保留导入值。截止时间早于今天标「已到期」。
合同开始/截止时间优先取「快递资料 → 合同管理」中同名承运商最新归档合作合同的日期;未填写的日期沿用快递资料或导入值。截止时间早于今天标「已到期」。
签订公司、快递公司主体名称取「快递资料」(按承运商名称);快递资料里没有的保留导入值。
月初结余上月「本月应付金额 − 本次实付金额」结转(没填实付按 0 算);可手工改。签署完结后再按工作平台状态自动判断,细则后定。
原单补发配件项目名称含「补发配件」或「配件补发」(排在第一条,「成品补发配件扣快递」也算这里)。
补给快递以「补」开头、含「记账补款」或以「需补」结尾的项目,取正数;名称含「记账」的同时计入「记账补款金额」。不进差异明细。
对账差异金额差异明细 13 列合计 − 违约金 − 借支。
核对确定金额快递提供金额 − 对账差异金额。
本月应付金额快递提供 − 对账差异 − 面单 − 借支 − 赔付 + 其他补款 + 补给快递 + 月初结余。
其他补款、本次实付金额手工填。
其他补款手工填。
本次实付金额本月应付金额大于 0 时自动等于本月应付金额,随应付金额重算;本月应付金额为 0 或负数时保留原值,可手工填。
@@ -223,7 +225,7 @@ if (!response.ok) throw new Error((await response.json().catch(() => ({})))?.message || 'save'); await swap(location.href); const next = document.querySelector('[data-ps-status]'); - if (next) next.textContent = '已保存,本月应付已重算。'; + if (next) next.textContent = '已保存,本月应付及正数应付对应的本次实付已重算。'; } catch (error) { input.disabled = false; if (status) status.textContent = '保存失败:' + (error.message === 'save' ? '请刷新后重试' : error.message); diff --git a/tests/Feature/Business/CourierBillPagesTest.php b/tests/Feature/Business/CourierBillPagesTest.php index d67d873c1..2f1d025b4 100644 --- a/tests/Feature/Business/CourierBillPagesTest.php +++ b/tests/Feature/Business/CourierBillPagesTest.php @@ -81,7 +81,7 @@ final class CourierBillPagesTest extends FeatureTestCase $this->post(route("business.$section.courier-payable-summary.import"), ['month' => '2026-10', 'summary' => $this->summaryFile()])->assertRedirect(); $row = $db->table('courier_payable_summary_rows')->where('carrier', '河北中通')->sole(); $this->get($summary . '?month=2026-10')->assertOk()->assertSeeText('河北中通')->assertSeeText('核对无误')->assertSeeText('上楼费5元'); - $this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $row->id]), ['column' => 'S', 'value' => '13'])->assertOk(); + $this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $row->id]), ['column' => 'S', 'value' => '13'])->assertUnprocessable(); $this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $row->id]), ['column' => 'K', 'value' => '1'])->assertUnprocessable(); $this->post(route("business.$section.courier-payable-summary.create-month"), ['month' => '2026-11'])->assertRedirect(); $this->get(route("business.$section.courier-payable-summary.export", ['month' => '2026-11']))->assertOk(); diff --git a/tests/Feature/Business/CourierPayableSummaryRulesTest.php b/tests/Feature/Business/CourierPayableSummaryRulesTest.php new file mode 100644 index 000000000..381d7c88e --- /dev/null +++ b/tests/Feature/Business/CourierPayableSummaryRulesTest.php @@ -0,0 +1,197 @@ +shouldReceive('contractsByName')->andReturn([ + '合同快递' => ['contract_start' => '2025-01-01', 'contract_end' => '2025-12-31', 'company' => '原签订公司', 'body' => '原合同主体'], + ]); + $this->app->instance(CourierInformationMirrorRepository::class, $mirror); + } + + public function test_positive_payables_drive_paid_amount_export_and_next_month_balance(): void + { + $service = app(PayableSummary::class); + $expected = []; + foreach ([ + ['正数快递', ['K' => 2000, 'L' => 50, 'I' => 100.5, 'S' => 1000], 2050.5, 2050.5], + ['一分钱快递', ['K' => 0.01, 'S' => null], 0.01, 0.01], + ['零数快递', ['K' => 0.004, 'S' => 9], 0.0, 9.0], + ['负数快递', ['I' => -50, 'S' => -5], -50.0, -5.0], + ['空值快递', ['I' => -20], -20.0, null], + ] as [$carrier, $cells, $payable, $paid]) { + $this->row($carrier, $cells); + $expected[$carrier] = [$payable, $paid]; + } + $rows = $service->rows('2026-11'); + foreach ($rows as $row) { + [$payable, $paid] = $expected[$row['cells']['H']]; + $this->assertSame($payable, $row['cells']['R']); + $this->assertSame($paid, $row['cells']['S'] ?? null); + } + $stored = json_decode($service->db()->table('courier_payable_summary_rows')->where('carrier', '正数快递')->value('cells'), true); + $this->assertSame(1000, $stored['S']); + + $file = tempnam(sys_get_temp_dir(), 'courier-auto-paid-'); + try { + $handle = fopen($file, 'wb'); + $service->export('2026-11', $handle); + fclose($handle); + $book = IOFactory::load($file); + $sheet = $book->getSheetByName('汇总'); + $this->assertEquals(2050.5, $sheet->getCell('R4')->getValue()); + $this->assertEquals(2050.5, $sheet->getCell('S4')->getValue()); + $this->assertEquals(9, $sheet->getCell('S6')->getValue()); + $this->assertEquals(2054.51, $sheet->getCell('S9')->getValue()); + $book->disconnectWorksheets(); + } finally { + @unlink($file); + } + + $this->assertSame(5, $service->createMonth('2026-12')); + $next = collect($service->rows('2026-12'))->keyBy('cells.H'); + $this->assertSame(0.0, $next['正数快递']['cells']['I']); + $this->assertSame(0.0, $next['一分钱快递']['cells']['I']); + $this->assertSame(-9.0, $next['零数快递']['cells']['I']); + $this->assertSame(-45.0, $next['负数快递']['cells']['I']); + $this->assertSame(-20.0, $next['空值快递']['cells']['I']); + } + + public function test_pages_and_updates_keep_positive_paid_amount_automatic(): void + { + $positive = $this->row('正数快递', ['K' => 100, 'S' => 7]); + $negative = $this->row('负数快递', ['I' => -10, 'S' => 2]); + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $this->loginAs(); + foreach (['courier-payables', 'courier-payables-final'] as $section) { + $page = route('business.pages.show', ['section' => $section, 'page' => 'courier-payable-summary', 'month' => '2026-11']); + $response = $this->get($page)->assertOk() + ->assertDontSee('aria-label="正数快递 本次实付金额"', false) + ->assertSee('aria-label="负数快递 本次实付金额"', false); + $this->assertSame(102.0, $response->viewData('content')['psTotals']['S']); + $this->withExceptionHandling(); + $this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $positive]), ['column' => 'S', 'value' => '5']) + ->assertUnprocessable()->assertJsonValidationErrors('courier_summary'); + } + $update = fn (int $id) => route('business.courier-payables.courier-payable-summary.update', ['row' => $id]); + $this->postJson($update($positive), ['column' => 'Q', 'value' => '12.34'])->assertOk(); + $this->postJson($update($negative), ['column' => 'S', 'value' => '-3'])->assertOk(); + $rows = collect(app(PayableSummary::class)->rows('2026-11'))->keyBy('cells.H'); + $this->assertSame(112.34, $rows['正数快递']['cells']['R']); + $this->assertSame(112.34, $rows['正数快递']['cells']['S']); + $this->assertSame(-3.0, $rows['负数快递']['cells']['S']); + } + + public function test_reconciliation_status_filter_combines_with_other_filters_and_updates_totals(): void + { + $this->row('已确认快递', ['K' => 100, 'Y' => '已确认', 'C' => '甲公司', 'D' => '负责人甲', 'E' => '承运']); + $this->row('待处理快递', ['K' => 80, 'C' => '甲公司', 'D' => '负责人甲', 'E' => '承运']); + $this->row('旧账快递', ['I' => -20]); + $this->row('无账单快递', []); + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + $this->loginAs(); + foreach (['courier-payables', 'courier-payables-final'] as $section) { + $url = route('business.pages.show', ['section' => $section, 'page' => 'courier-payable-summary', 'month' => '2026-11']); + $response = $this->get($url . '&' . http_build_query(['status' => '已确认', 'company' => '甲公司', 'owner' => '负责人甲', 'state' => '承运', 'q' => '快递'])) + ->assertOk()->assertSee(' -
-@forelse($dfLines as $r)@empty@endforelse +
快递单号发货 / 快递厂家运费我方核算最终结算差额分类 / 说明厂家反馈
{{ $r['waybill'] }}{{ $r['ship_time'] }}
{{ $r['express'] }}
{{ $money($r['bill']) }}{{ $money($r['calc']) }}{{ $money($r['final']??$r['settle']) }}{{ $r['bill']===null?'':$money($r['bill']-(float)($r['final']??$r['settle'])) }}{{ $r['label'] }}
{{ $r['note'] }}
@if(isset($dfDisputeMap[$r['waybill']])){{ isset($dfDisputeMap[$r['waybill']]['decision'])?'查看处理':'待处理异议' }}@else—@endif
当前筛选没有明细。
+@forelse($dfLines as $r)@foreach(['bill_weight','charge_weight','weight_diff'] as $weightKey)@endforeach@empty@endforelse
快递单号发货 / 快递厂家重量(kg)我方计费重量(kg)重量差(kg)厂家运费我方核算最终结算差额分类 / 说明厂家反馈
{{ $r['waybill'] }}{{ $r['ship_time'] }}
{{ $r['express'] }}
{{ $r[$weightKey]===null?'—':rtrim(rtrim(number_format($r[$weightKey],4,'.',''),'0'),'.') }}{{ $money($r['bill']) }}{{ $money($r['calc']) }}{{ $money($r['final']??$r['settle']) }}{{ $r['bill']===null?'':$money($r['bill']-(float)($r['final']??$r['settle'])) }}{{ $r['label'] }}@if($r['diff_kind'])
{{ ['weight_diff'=>'重量差','price_diff'=>'价格差','missing_weight'=>'重量待补充'][$r['diff_kind']] }}
@endif
{{ $r['note'] }}
@if(isset($dfDisputeMap[$r['waybill']])){{ isset($dfDisputeMap[$r['waybill']]['decision'])?'查看处理':'待处理异议' }}@else—@endif
当前筛选没有明细。
{{ $dfLines->links() }}
@if(($dfSurchargeSummary??collect())->isNotEmpty())

附加费核对

@foreach($dfSurchargeSummary as $fee)@endforeach
项目厂家金额自算金额
{{ $fee->item }}{{ $money($fee->bill) }}{{ $money($fee->self) }}
@endif @include('business.pages.courier-payables.partials.surcharge-matches',['surchargeRows'=>$dfSurchargeRows??null]) diff --git a/tests/Feature/Business/DropshipWeightTest.php b/tests/Feature/Business/DropshipWeightTest.php new file mode 100644 index 000000000..72aadad7f --- /dev/null +++ b/tests/Feature/Business/DropshipWeightTest.php @@ -0,0 +1,101 @@ +parse($path, 'csv')['lines']; + $this->assertEquals(11, $rows['WB0001']['amount']); + $this->assertEquals(5, $rows['WB0001']['weight']); + $this->assertNull($rows['WB0002']['weight']); + $this->assertSame(0.0, $rows['WB0003']['weight']); + $this->assertNull($rows['WB0004']['weight']); + $this->assertNull(FactoryBillParser::findColumns(['单号','运费','我方计费重量','重量差'])['weight']); + } finally { @unlink($path); } + } + + public function test_weight_difference_uses_unique_packages_and_is_visible_in_page_filter_and_export(): void + { + Storage::fake('local'); $store=app(DropshipFreightStore::class); $db=$store->db(); + $id=$store->saveFactory(null,['name'=>'重量测试','warehouse'=>'测试代发仓','keywords'=>'测试']); + $path=tempnam(sys_get_temp_dir(),'weights').'.xlsx';$book=new StreamingWorkbook(); + $book->row('账单',['单号','运费','重量'],true); + foreach([['WB0001',12,5],['WB0002',12,3],['WB0003',8,null],['OLD4',12,2],['WB0005',12,1]] as $row)$book->row('账单',$row); + $handle=fopen($path,'wb');$book->writeTo($handle);fclose($handle); + try { + $file=$store->upload([new UploadedFile($path,'重量测试.xlsx',null,null,true)],'2026-11','测试')[0]; + $shipping=app(ShippingLookup::class)->connection(); + foreach([['WB0001',1,2,5],['WB0001',1,2,5],['WB0001',2,1,5],['WB0002',3,3,10],['WB0003',4,3,10],['NEWB0004',5,2,10],['WB0005',6,3,10]] as $n=>[$no,$source,$weight,$amount]) { + $shipping->table('jst_oms_shipping')->insert(['express_no'=>$no,'source_id'=>$source,'sku_source_id'=>$n+1,'warehouse_name'=>'测试代发仓','express_name1'=>'测试快递','ship_time'=>'2026-11-03 09:00:00','front_no'=>$no==='NEWB0004'?'OLD4':null]); + $shipping->table('jst_oms_shipping_freight')->updateOrInsert(['source_id'=>$source],['charge_weight'=>$weight,'freight'=>$amount,'status'=>'OK']); + } + $factory=collect($store->factories())->firstWhere('id',$id);$result=app(DropshipReconciler::class)->factoryMonth($factory,'2026-11'); + $rows=collect($result['rows'])->keyBy('waybill'); + $this->assertEquals(3,$rows['WB0001']['charge_weight']); + $this->assertEquals(2,$rows['WB0001']['weight_diff']); + $this->assertSame('price_diff',$rows['WB0002']['diff_kind']); + $this->assertSame('missing_weight',$rows['WB0003']['diff_kind']); + $this->assertNull($rows['WB0003']['weight_diff']); + $this->assertEquals(0,$rows['OLD4']['weight_diff']); + $this->assertEquals(-2,$rows['WB0005']['weight_diff']); + $this->assertEquals(48,$result['summary']['settle']); + $this->assertSame(['weight_diff'=>2,'price_diff'=>2,'missing_weight'=>1],$result['summary']['diff_counts']); + $this->user->attachPermission(\App\Models\Auth\Permission::where('name','read-admin-panel')->firstOrFail()); + $this->loginAs(); + $url=route('business.pages.show',['section'=>'courier-payables','page'=>DropshipFreightController::PAGE,'df_view'=>'factory','factory'=>$id,'month'=>'2026-11','status'=>'weight_diff']); + $this->get($url)->assertOk()->assertSeeText('厂家重量(kg)')->assertSeeText('重量差(kg)')->assertSeeText('WB0001')->assertSeeText('WB0005')->assertDontSeeText('WB0002'); + $out=tempnam(sys_get_temp_dir(),'weight-export');$handle=fopen($out,'wb'); + try{app(DropshipExporter::class)->export($factory,'2026-11',$handle);}finally{fclose($handle);} + try{ + $export=IOFactory::load($out);$grid=$export->getSheetByName('对账')->toArray(null,false,false);$headers=array_shift($grid);$weightCol=array_search('重量差',$headers,true);$wbCol=array_search('快递单号',$headers,true); + $w1=collect($grid)->first(fn($r)=>$r[$wbCol]==='WB0001');$this->assertEquals(2,$w1[$weightCol]); + $this->assertNotFalse(array_search('厂家重量(kg)',$headers,true));$export->disconnectWorksheets(); + }finally{@unlink($out);} + $this->assertEquals(5,$db->table('dropship_bill_lines')->where('file_id',$file)->where('waybill_no','WB0001')->value('bill_weight')); + } finally {@unlink($path);} + } + + public function test_backfill_preserves_amounts_and_skips_changed_source_and_is_idempotent(): void + { + Storage::fake('local');$store=app(DropshipFreightStore::class);$db=$store->db(); + $store->saveFactory(null,['name'=>'重量测试','warehouse'=>'测试代发仓','keywords'=>'测试']); + $csv="单号,运费,重量\n";for($i=0;$i<1001;$i++)$csv.="BACK{$i},8,3\n"; + $file=$store->upload([UploadedFile::fake()->createWithContent('重量测试.csv',$csv)],'2026-11','测试')[0]; + $db->table('dropship_bill_lines')->where('file_id',$file)->update(['bill_weight'=>null]); + $db->table('dropship_bill_lines')->where('waybill_no','BACK0')->update(['amount'=>9]); + $this->artisan('dropship-freight:backfill-weights',['--all'=>true])->assertSuccessful(); + $this->assertSame(0,$db->table('dropship_bill_lines')->whereNotNull('bill_weight')->count()); + $this->artisan('dropship-freight:backfill-weights',['--all'=>true,'--apply'=>true])->assertSuccessful(); + $this->assertSame(1000,$db->table('dropship_bill_lines')->whereNotNull('bill_weight')->count()); + $this->assertEquals(8009,$db->table('dropship_bill_lines')->sum('amount')); + $this->assertNull($db->table('dropship_bill_lines')->where('waybill_no','BACK0')->value('bill_weight')); + $this->assertNotEmpty(Storage::disk('local')->allFiles('private/dropship-weight')); + $this->artisan('dropship-freight:backfill-weights',['--all'=>true,'--apply'=>true])->assertSuccessful(); + $this->assertSame(1000,$db->table('dropship_bill_lines')->whereNotNull('bill_weight')->count()); + } + + public function test_backfill_skips_confirmed_factory_bills(): void + { + Storage::fake('local');$store=app(DropshipFreightStore::class);$db=$store->db(); + $id=$store->saveFactory(null,['name'=>'重量测试','warehouse'=>'测试代发仓','keywords'=>'测试']); + $file=$store->upload([UploadedFile::fake()->createWithContent('重量测试.csv',"单号,运费,重量\nCONFIRM1,8,3\n")],'2026-11','测试')[0]; + $db->table('dropship_bill_lines')->where('file_id',$file)->update(['bill_weight'=>null]); + app(\Modules\EcommerceFinance\Services\SupplierPayableOverrideStore::class)->save('dropship-freight-confirm','2026-11|'.$id, + ['status'=>'confirmed','month'=>'2026-11','factory_id'=>$id],(int)$this->company->id,null,'test'); + $this->artisan('dropship-freight:backfill-weights',['--all'=>true,'--company'=>$this->company->id,'--apply'=>true])->assertSuccessful(); + $this->assertNull($db->table('dropship_bill_lines')->value('bill_weight')); + } +} From ff0a450e672d5d061a51e304530078339ce50c1c Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Sun, 6 Dec 2026 14:52:55 +0800 Subject: [PATCH 3/4] =?UTF-8?q?=E5=BF=AB=E9=80=92=E5=BA=94=E4=BB=98?= =?UTF-8?q?=E6=B1=87=E6=80=BB=EF=BC=9A=E5=85=81=E8=AE=B8=E6=89=8B=E5=B7=A5?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E8=87=AA=E5=8A=A8=E5=B8=A6=E5=87=BA=E7=9A=84?= =?UTF-8?q?=E5=AE=9E=E4=BB=98=E9=87=91=E9=A2=9D=20(#1778)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Support/CourierBills/PayableSummary.php | 11 ++---- app/Support/CourierBills/SummaryMapper.php | 4 +- .../courier-payable-summary.blade.php | 8 ++-- .../Feature/Business/CourierBillPagesTest.php | 2 +- .../CourierPayableSummaryRulesTest.php | 39 ++++++++++++++++--- 5 files changed, 45 insertions(+), 19 deletions(-) diff --git a/app/Support/CourierBills/PayableSummary.php b/app/Support/CourierBills/PayableSummary.php index a182ae302..1efc22dd1 100644 --- a/app/Support/CourierBills/PayableSummary.php +++ b/app/Support/CourierBills/PayableSummary.php @@ -190,13 +190,6 @@ final class PayableSummary if ($row === null) { throw new RuntimeException('汇总行不存在。'); } - if ($column === 'S') { - foreach ($this->rows((string) $row->month) as $current) { - if ($current['id'] === $rowId && $current['cells']['R'] > 0) { - throw new RuntimeException('本月应付金额大于 0 时,本次实付金额自动等于本月应付金额,无需手工修改。'); - } - } - } $cells = (array) json_decode((string) $row->cells, true); if (in_array($column, self::MONEY, true)) { $number = BillParser::number($value); @@ -204,6 +197,10 @@ final class PayableSummary throw new RuntimeException(self::COLUMNS[$column] . '须为数字。'); } $cells[$column] = $number; + if ($column === 'S') { + // 手工实付(含 0)优先保留;清空后恢复按应付金额自动带出。 + $cells['_paid_manual'] = $number !== null; + } } else { $cells[$column] = $value === null ? null : mb_substr(trim($value), 0, 500); } diff --git a/app/Support/CourierBills/SummaryMapper.php b/app/Support/CourierBills/SummaryMapper.php index e52893645..5e65fe82e 100644 --- a/app/Support/CourierBills/SummaryMapper.php +++ b/app/Support/CourierBills/SummaryMapper.php @@ -126,13 +126,13 @@ final class SummaryMapper ]; } - /** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L;R > 0 时实付 S = R。 */ + /** 本月应付 R = K − L − N − O − P + Q + J + I;核对确定 M = K − L;未手工填写时,R > 0 则实付 S = R。 */ public static function totals(array $cells): array { $n = static fn (string $key): float => (float) ($cells[$key] ?? 0); $cells['M'] = round($n('K') - $n('L'), 2); $cells['R'] = round($n('K') - $n('L') - $n('N') - $n('O') - $n('P') + $n('Q') + $n('J') + $n('I'), 2); - if ($cells['R'] > 0) { + if ($cells['R'] > 0 && empty($cells['_paid_manual'])) { $cells['S'] = $cells['R']; } diff --git a/resources/views/business/pages/courier-payables/courier-payable-summary.blade.php b/resources/views/business/pages/courier-payables/courier-payable-summary.blade.php index a9a676510..91049fa15 100644 --- a/resources/views/business/pages/courier-payables/courier-payable-summary.blade.php +++ b/resources/views/business/pages/courier-payables/courier-payable-summary.blade.php @@ -80,7 +80,7 @@ {{ $c['H'] ?? '' }} {{ $row['status'] === '已确认' ? '核对无误' : $row['status'] }} @foreach ($main as $k) - @if (isset($editable[$k]) && ! ($k === 'S' && ($c['R'] ?? 0) > 0)) + @if (isset($editable[$k])) @else {{ $money($c[$k] ?? 0) }} @@ -106,7 +106,7 @@ - + @endif @@ -169,7 +169,7 @@ 核对确定金额快递提供金额 − 对账差异金额。 本月应付金额快递提供 − 对账差异 − 面单 − 借支 − 赔付 + 其他补款 + 补给快递 + 月初结余。 其他补款手工填。 - 本次实付金额本月应付金额大于 0 时自动等于本月应付金额,随应付金额重算;本月应付金额为 0 或负数时保留原值,可手工填。 + 本次实付金额本月应付金额大于 0 时默认自动等额带出,可手工修改(含 0);手工值优先保留,清空后恢复自动带出。本月应付金额为 0 或负数时保留原值。 @@ -225,7 +225,7 @@ if (!response.ok) throw new Error((await response.json().catch(() => ({})))?.message || 'save'); await swap(location.href); const next = document.querySelector('[data-ps-status]'); - if (next) next.textContent = '已保存,本月应付及正数应付对应的本次实付已重算。'; + if (next) next.textContent = '已保存,手工实付优先保留,未手工填写的正数应付自动带出实付。'; } catch (error) { input.disabled = false; if (status) status.textContent = '保存失败:' + (error.message === 'save' ? '请刷新后重试' : error.message); diff --git a/tests/Feature/Business/CourierBillPagesTest.php b/tests/Feature/Business/CourierBillPagesTest.php index 2f1d025b4..d67d873c1 100644 --- a/tests/Feature/Business/CourierBillPagesTest.php +++ b/tests/Feature/Business/CourierBillPagesTest.php @@ -81,7 +81,7 @@ final class CourierBillPagesTest extends FeatureTestCase $this->post(route("business.$section.courier-payable-summary.import"), ['month' => '2026-10', 'summary' => $this->summaryFile()])->assertRedirect(); $row = $db->table('courier_payable_summary_rows')->where('carrier', '河北中通')->sole(); $this->get($summary . '?month=2026-10')->assertOk()->assertSeeText('河北中通')->assertSeeText('核对无误')->assertSeeText('上楼费5元'); - $this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $row->id]), ['column' => 'S', 'value' => '13'])->assertUnprocessable(); + $this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $row->id]), ['column' => 'S', 'value' => '13'])->assertOk(); $this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $row->id]), ['column' => 'K', 'value' => '1'])->assertUnprocessable(); $this->post(route("business.$section.courier-payable-summary.create-month"), ['month' => '2026-11'])->assertRedirect(); $this->get(route("business.$section.courier-payable-summary.export", ['month' => '2026-11']))->assertOk(); diff --git a/tests/Feature/Business/CourierPayableSummaryRulesTest.php b/tests/Feature/Business/CourierPayableSummaryRulesTest.php index 381d7c88e..bd02b2775 100644 --- a/tests/Feature/Business/CourierPayableSummaryRulesTest.php +++ b/tests/Feature/Business/CourierPayableSummaryRulesTest.php @@ -72,7 +72,7 @@ final class CourierPayableSummaryRulesTest extends FeatureTestCase $this->assertSame(-20.0, $next['空值快递']['cells']['I']); } - public function test_pages_and_updates_keep_positive_paid_amount_automatic(): void + public function test_manual_paid_amount_is_editable_and_survives_recalculation(): void { $positive = $this->row('正数快递', ['K' => 100, 'S' => 7]); $negative = $this->row('负数快递', ['I' => -10, 'S' => 2]); @@ -81,20 +81,49 @@ final class CourierPayableSummaryRulesTest extends FeatureTestCase foreach (['courier-payables', 'courier-payables-final'] as $section) { $page = route('business.pages.show', ['section' => $section, 'page' => 'courier-payable-summary', 'month' => '2026-11']); $response = $this->get($page)->assertOk() - ->assertDontSee('aria-label="正数快递 本次实付金额"', false) + ->assertSee('aria-label="正数快递 本次实付金额"', false) ->assertSee('aria-label="负数快递 本次实付金额"', false); - $this->assertSame(102.0, $response->viewData('content')['psTotals']['S']); + $this->assertSame($section === 'courier-payables' ? 102.0 : 7.0, $response->viewData('content')['psTotals']['S']); $this->withExceptionHandling(); $this->postJson(route("business.$section.courier-payable-summary.update", ['row' => $positive]), ['column' => 'S', 'value' => '5']) - ->assertUnprocessable()->assertJsonValidationErrors('courier_summary'); + ->assertOk(); } $update = fn (int $id) => route('business.courier-payables.courier-payable-summary.update', ['row' => $id]); $this->postJson($update($positive), ['column' => 'Q', 'value' => '12.34'])->assertOk(); $this->postJson($update($negative), ['column' => 'S', 'value' => '-3'])->assertOk(); $rows = collect(app(PayableSummary::class)->rows('2026-11'))->keyBy('cells.H'); $this->assertSame(112.34, $rows['正数快递']['cells']['R']); - $this->assertSame(112.34, $rows['正数快递']['cells']['S']); + $this->assertSame(5.0, $rows['正数快递']['cells']['S']); $this->assertSame(-3.0, $rows['负数快递']['cells']['S']); + + $this->postJson($update($positive), ['column' => 'S', 'value' => 'not-a-number']) + ->assertUnprocessable()->assertJsonValidationErrors('courier_summary'); + $this->assertSame(5.0, app(PayableSummary::class)->rows('2026-11')[0]['cells']['S']); + $this->postJson($update($positive), ['column' => 'S', 'value' => '0'])->assertOk(); + $this->postJson($update($positive), ['column' => 'Q', 'value' => '20'])->assertOk(); + $this->assertSame(0.0, app(PayableSummary::class)->rows('2026-11')[0]['cells']['S']); + $this->postJson($update($positive), ['column' => 'S', 'value' => ''])->assertOk(); + $this->assertSame(120.0, app(PayableSummary::class)->rows('2026-11')[0]['cells']['S']); + $this->postJson($update($positive), ['column' => 'S', 'value' => '25.55'])->assertOk(); + + $file = tempnam(sys_get_temp_dir(), 'courier-manual-paid-'); + try { + $handle = fopen($file, 'wb'); + app(PayableSummary::class)->export('2026-11', $handle); + fclose($handle); + $book = IOFactory::load($file); + $sheet = $book->getSheetByName('汇总'); + $this->assertEquals(25.55, $sheet->getCell('S4')->getValue()); + $this->assertEquals(22.55, $sheet->getCell('S6')->getValue()); + $book->disconnectWorksheets(); + } finally { + @unlink($file); + } + app(PayableSummary::class)->createMonth('2026-12'); + $next = app(PayableSummary::class)->rows('2026-12'); + $this->assertSame(94.45, $next[0]['cells']['I']); + $this->assertSame(94.45, $next[0]['cells']['S']); + $this->assertArrayNotHasKey('_paid_manual', $next[0]['cells']); } public function test_reconciliation_status_filter_combines_with_other_filters_and_updates_totals(): void From 85f8eda9ffd59f99aacc348c525a6e84aa7a1de1 Mon Sep 17 00:00:00 2001 From: limeng <1131177064@qq.com> Date: Sun, 6 Dec 2026 15:01:33 +0800 Subject: [PATCH 4/4] =?UTF-8?q?fix(=E5=BF=AB=E9=80=92=E5=AF=B9=E8=B4=A6):?= =?UTF-8?q?=20=E4=B8=AD=E9=93=81=E7=89=A9=E6=B5=81=E5=92=8C=E6=AD=A6?= =?UTF-8?q?=E8=BF=9B=E5=AE=89=E8=83=BD=E6=8C=89=E6=A0=B8=E7=AE=97=E8=BF=90?= =?UTF-8?q?=E8=B4=B9=E7=BB=93=E7=AE=97=20(#1779)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Commands/RefreshCourierSettlement.php | 14 +++--- .../CourierBills/CourierBillMatcher.php | 16 +++--- .../CourierBills/StatementExporter.php | 17 +++++-- .../courier-bills/details.blade.php | 4 +- .../courier-bills/statement.blade.php | 8 +-- .../CourierBillReconciliationTest.php | 2 +- .../Business/CourierSettlementRulesTest.php | 50 +++++++++++++++++++ 7 files changed, 88 insertions(+), 23 deletions(-) diff --git a/app/Console/Commands/RefreshCourierSettlement.php b/app/Console/Commands/RefreshCourierSettlement.php index ffa82ed75..0c6187de2 100644 --- a/app/Console/Commands/RefreshCourierSettlement.php +++ b/app/Console/Commands/RefreshCourierSettlement.php @@ -10,8 +10,8 @@ use Illuminate\Support\Facades\{Cache, DB, Storage}; /** 只重新应用结算口径,不重算报价或覆盖人工处理。 */ final class RefreshCourierSettlement extends Command { - protected $signature = 'courier-bills:refresh-settlement {--statement=*} {--all-open} {--company=1} {--apply : 备份后更新未确认账单}'; - protected $description = '按快递提供与核价较低值结算运费和附加费,并更新武进韵达重量差补款'; + protected $signature = 'courier-bills:refresh-settlement {--statement=*} {--all-open} {--express=* : 仅刷新指定快递的运费,保留附加费} {--company=1} {--apply : 备份后更新未确认账单}'; + protected $description = '应用快递运费结算口径(含按核算值结算的例外),并刷新附加费及武进韵达补款'; public function handle(CourierBillMatcher $matcher, WeightDifferenceSubsidy $subsidy): int { @@ -51,11 +51,13 @@ final class RefreshCourierSettlement extends Command } $changed = 0; $decrease = 0.0; $scanned = 0; try { - foreach ($db->table('courier_bill_lines')->where('statement_id', $id)->orderBy('id')->lazyById(500) as $line) { + foreach ($db->table('courier_bill_lines')->where('statement_id', $id) + ->when($this->option('express') !== [], fn ($q) => $q->whereIn('express_name', $this->option('express'))) + ->orderBy('id')->lazyById(500) as $line) { $scanned++; if ($stream) fwrite($stream, json_encode(['line' => $line], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n"); if ($line->resolution !== null || ! in_array($line->category, [...Category::PAYABLE, Category::PRIOR], true)) continue; - $amount = CourierBillMatcher::selfAmount((string) $line->category, $line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $line->resolution); + $amount = CourierBillMatcher::selfAmount((string) $line->category, $line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $line->resolution, $line->express_name); if (($amount === null) === ($line->self_amount === null) && ($amount === null || abs($amount - (float) $line->self_amount) < 0.00001)) continue; $changed++; $decrease += (float) $line->self_amount - (float) $amount; if ($this->option('apply')) $db->table('courier_bill_lines')->where('id', $line->id)->update(['self_amount' => $amount]); @@ -66,7 +68,7 @@ final class RefreshCourierSettlement extends Command $subsidyChanged = ! ($existing?->manual) && abs((float) ($existing?->self_amount ?? 0) - $weight['amount']) > 0.00001; $feeChanges = 0; $feeDecrease = 0.0; foreach ($beforeFees as $fee) { - if ($fee->self_amount !== null && $fee->bill_amount !== null && (float) $fee->bill_amount < (float) $fee->self_amount) { + if ($this->option('express') === [] && $fee->self_amount !== null && $fee->bill_amount !== null && (float) $fee->bill_amount < (float) $fee->self_amount) { $feeChanges++; $feeDecrease += (float) $fee->self_amount - round((float) $fee->bill_amount, 2); if ($this->option('apply')) $db->table('bill_surcharge_matches')->where('id', $fee->id)->update([ 'self_amount' => round((float) $fee->bill_amount, 2), @@ -81,7 +83,7 @@ final class RefreshCourierSettlement extends Command $normalize = static fn ($rows) => $rows->map(fn ($r) => array_intersect_key((array) $r, array_flip($fields)))->sortBy(fn ($r) => json_encode($r))->values()->all(); $expectedFees = $beforeFees->map(function ($fee) { $copy = clone $fee; - if ($copy->self_amount !== null && $copy->bill_amount !== null && (float) $copy->bill_amount < (float) $copy->self_amount) $copy->self_amount = number_format((float) $copy->bill_amount, 2, '.', ''); + if ($this->option('express') === [] && $copy->self_amount !== null && $copy->bill_amount !== null && (float) $copy->bill_amount < (float) $copy->self_amount) $copy->self_amount = number_format((float) $copy->bill_amount, 2, '.', ''); return $copy; }); $afterFees = $db->table('bill_surcharge_matches')->where('scope', 'courier')->where('owner_id', $id)->get(); diff --git a/app/Support/CourierBills/CourierBillMatcher.php b/app/Support/CourierBills/CourierBillMatcher.php index 41499dc9c..1b1de6e18 100644 --- a/app/Support/CourierBills/CourierBillMatcher.php +++ b/app/Support/CourierBills/CourierBillMatcher.php @@ -12,6 +12,9 @@ use RuntimeException; */ final class CourierBillMatcher { + /** 这两家运费按我方核算结算,不能因合并分组而影响同组其他快递。 */ + public const ACTUAL_FREIGHT_EXPRESSES = ['中铁物流', '武进安能']; + private ?AccessoryDeductions $deductions = null; public function __construct( @@ -83,7 +86,7 @@ final class CourierBillMatcher 'calc_freight' => $ship['calc_freight'] ?? null, 'charge_weight' => $ship['charge_weight'] ?? null, 'unshipped_sources' => isset($unshipped[$key]) ? mb_substr(implode('、', $unshipped[$key]), 0, 128) : null, - 'self_amount' => self::selfAmount($category, $ship['calc_freight'] ?? null, $line->bill_amount, $line->resolution), + 'self_amount' => self::selfAmount($category, $ship['calc_freight'] ?? null, $line->bill_amount, $line->resolution, $ship['express_name'] ?? null), ]; } @@ -153,14 +156,15 @@ final class CourierBillMatcher return [Category::DIFF, null]; } - /** 自算金额:处理结果优先;正常应付按快递提供与核算运费较低者结算,缺少核算依据保持空白。 */ - public static function selfAmount(string $category, ?float $calcFreight, mixed $billAmount, ?string $resolution): ?float + /** 人工处理优先;中铁物流、武进安能运费取核算值,其他正常应付取较低值,缺少核算依据保持空白。 */ + public static function selfAmount(string $category, ?float $calcFreight, mixed $billAmount, ?string $resolution, ?string $expressName = null): ?float { return match ($resolution) { 'agree' => $billAmount === null ? null : (float) $billAmount, 'exclude', 'defer' => 0.0, default => in_array($category, [...Category::PAYABLE, Category::PRIOR], true) - ? ($calcFreight !== null && $billAmount !== null ? min($calcFreight, round((float) $billAmount, 2)) : $calcFreight) : 0.0, + ? (in_array(trim((string) $expressName), self::ACTUAL_FREIGHT_EXPRESSES, true) ? $calcFreight + : ($calcFreight !== null && $billAmount !== null ? min($calcFreight, round((float) $billAmount, 2)) : $calcFreight)) : 0.0, }; } @@ -175,14 +179,14 @@ final class CourierBillMatcher $db->transaction(function () use ($db, $statementId, $lineIds, $resolution, $user, &$count): void { foreach (array_chunk($lineIds, 500) as $chunk) { $lines = $db->table('courier_bill_lines')->where('statement_id', $statementId)->whereIn('id', $chunk) - ->get(['id', 'category', 'calc_freight', 'bill_amount']); + ->get(['id', 'category', 'calc_freight', 'bill_amount', 'express_name']); foreach ($lines as $line) { $db->table('courier_bill_lines')->where('id', $line->id)->update([ 'resolution' => $resolution, 'resolved_by' => $resolution === null ? null : $user, 'resolved_at' => $resolution === null ? null : now(), 'self_amount' => self::selfAmount((string) $line->category, - $line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $resolution), + $line->calc_freight === null ? null : (float) $line->calc_freight, $line->bill_amount, $resolution, $line->express_name), ]); $count++; } diff --git a/app/Support/CourierBills/StatementExporter.php b/app/Support/CourierBills/StatementExporter.php index 21059e9c4..b32dcbb8f 100644 --- a/app/Support/CourierBills/StatementExporter.php +++ b/app/Support/CourierBills/StatementExporter.php @@ -108,8 +108,14 @@ final class StatementExporter $groupCell = static fn (object $line): array => $multi ? [$groupNames[(int) $line->statement_id] ?? ''] : []; [$sources, $original] = $this->originalHeaders($ids); + $front = []; + foreach (self::FRONT as $label => $field) { + $front[$label] = $field; + if ($field === 'qc_freight') $front['结算运费'] = '_settlement'; + } $rest = array_diff_key(ShippingLookup::COLUMNS, array_flip(array_filter(self::FRONT, static fn ($f) => $f[0] !== '_'))); - $fullHeader = [...$original, ...array_keys(self::FRONT), ...array_values($rest), '结算运费', '差异原因', '处理结果', ...$tail]; + $rest['settle_freight'] = '发货数据结算运费'; + $fullHeader = [...$original, ...array_keys($front), ...array_values($rest), '差异原因', '处理结果', ...$tail]; // 原始账单:底文件原封不动;第 2 个及以后的文件按值复制 $originals = $this->writeOriginal($book, $files, $baseFileId); @@ -123,7 +129,7 @@ final class StatementExporter } foreach ($sheets as $name => $filter) { $headerWritten = false; - $this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $rest, $fullHeader, $groupCell, $expressNames, &$headerWritten): void { + $this->lines($ids, $filter, function (array $lines) use ($book, $name, $sources, $original, $front, $rest, $fullHeader, $groupCell, $expressNames, &$headerWritten): void { if (! $headerWritten) { $book->row($name, $fullHeader, true); $headerWritten = true; @@ -132,13 +138,16 @@ final class StatementExporter foreach ($lines as $line) { $ship = $details[strtoupper($line->waybill_no)] ?? []; $cells = $this->originalCells($line, $sources, $original); - foreach (self::FRONT as $field) { + foreach ($front as $field) { + if ($field === '_settlement') { + $cells[] = $line->self_amount === null ? null : (float) $line->self_amount; + continue; + } $cells[] = $this->front($field, $line, $ship); } foreach (array_keys($rest) as $field) { $cells[] = self::value($field, $ship[$field] ?? null); } - $cells[] = $line->self_amount === null ? null : (float) $line->self_amount; $cells[] = CourierBillMatcher::diffReason((string) $line->category, $line->bill_weight, $line->charge_weight); $cells[] = Category::RESOLUTIONS[$line->resolution] ?? null; $book->row($name, [...$cells, ...$groupCell($line)]); diff --git a/resources/views/business/pages/courier-payables/courier-bills/details.blade.php b/resources/views/business/pages/courier-payables/courier-bills/details.blade.php index 7ab59c0d2..47b78121b 100644 --- a/resources/views/business/pages/courier-payables/courier-bills/details.blade.php +++ b/resources/views/business/pages/courier-payables/courier-bills/details.blade.php @@ -29,7 +29,7 @@ 账单月份对账分组负责人快递单号分类 - 快递运费核算运费自算金额差异 + 快递运费核算运费结算运费差异 发货时间发货数据快递名称1处理结果 @@ -63,4 +63,4 @@ 共 {{ number_format($cbLines->total()) }} 条,每页 50 条 {{ $cbLines->links('business.partials.previous-next-pagination') }} -

正常应付运费取快递提供与我方核算的较低金额。处理结果:同意付款 = 自算金额取快递金额;已与快递确认剔除 / 转下月 = 本月自算金额为 0。武进韵达重量多报超过1公斤的正向运费差额,合计后补50%,在小汇总单列。改完对应对账单的小汇总和快递应付汇总自动重算。

+

正常应付运费取快递提供与我方核算的较低金额;中铁物流、武进安能按我方实际核算运费结算。处理结果:同意付款 = 自算金额取快递金额;已与快递确认剔除 / 转下月 = 本月自算金额为 0。武进韵达重量多报超过1公斤的正向运费差额,合计后补50%,在小汇总单列。改完对应对账单的小汇总和快递应付汇总自动重算。

diff --git a/resources/views/business/pages/courier-payables/courier-bills/statement.blade.php b/resources/views/business/pages/courier-payables/courier-bills/statement.blade.php index a7b34d025..d906614f2 100644 --- a/resources/views/business/pages/courier-payables/courier-bills/statement.blade.php +++ b/resources/views/business/pages/courier-payables/courier-bills/statement.blade.php @@ -47,7 +47,7 @@

小汇总

-

正常应付运费与已核价附加费取快递提供和我方核算的较低金额,已有手工处理优先。武进韵达:快递重量超过我方计费重量1公斤的单据,快递多报的运费差额合计的50%单列补给快递。

+

正常应付运费与已核价附加费取快递提供和我方核算的较低金额;中铁物流、武进安能的运费按我方实际核算值结算,已有手工处理优先。武进韵达:快递重量超过我方计费重量1公斤的单据,快递多报的运费差额合计的50%单列补给快递。

@@ -111,8 +111,8 @@ @else @if ($open)@endif - - + + @endif @@ -128,10 +128,10 @@ + - diff --git a/tests/Feature/Business/CourierBillReconciliationTest.php b/tests/Feature/Business/CourierBillReconciliationTest.php index c29a03218..570780425 100644 --- a/tests/Feature/Business/CourierBillReconciliationTest.php +++ b/tests/Feature/Business/CourierBillReconciliationTest.php @@ -317,7 +317,7 @@ final class CourierBillReconciliationTest extends FeatureTestCase $this->assertSame('13800000000', (string) $recon->getCell('C2')->getValue()); $this->assertNotSame(DataType::TYPE_NUMERIC, $recon->getCell('C2')->getDataType()); $this->assertSame('ZT001', (string) $recon->getCell('G2')->getValue()); // 快递单号(25 列里的第 4 列) - $this->assertEquals(0, $recon->getCell('Q2')->getValue()); // 运费差 = 10 − 核算 10 + $this->assertEquals(0, $recon->getCell('R2')->getValue()); // 运费差 = 10 − 核算 10,核算后新增结算列 $book->disconnectWorksheets(); } diff --git a/tests/Feature/Business/CourierSettlementRulesTest.php b/tests/Feature/Business/CourierSettlementRulesTest.php index f5a34e86d..cc7eb383f 100644 --- a/tests/Feature/Business/CourierSettlementRulesTest.php +++ b/tests/Feature/Business/CourierSettlementRulesTest.php @@ -25,6 +25,56 @@ class CourierSettlementRulesTest extends FeatureTestCase $this->assertEquals(8.01, CourierBillMatcher::selfAmount(Category::DIFF, 10, 8.006, null)); } + public function test_actual_freight_exceptions_are_exact_names_and_preserve_manual_decisions(): void + { + foreach (['中铁物流', '武进安能'] as $name) { + foreach ([Category::MATCH, Category::DIFF, Category::PRIOR] as $category) { + foreach ([0, 8, 12, null] as $bill) $this->assertSame(10.0, CourierBillMatcher::selfAmount($category, 10, $bill, null, $name)); + } + $this->assertNull(CourierBillMatcher::selfAmount(Category::UNCALCULATED, null, 8, null, $name)); + $this->assertSame(8.0, CourierBillMatcher::selfAmount(Category::DIFF, 10, 8, 'agree', $name)); + foreach (['exclude', 'defer'] as $resolution) $this->assertSame(0.0, CourierBillMatcher::selfAmount(Category::DIFF, 10, 8, $resolution, $name)); + $this->assertSame(0.0, CourierBillMatcher::selfAmount(Category::DUPLICATE, 10, 8, null, $name)); + } + foreach (['中铁客退', '中铁物流其他', '武进安能其他'] as $name) $this->assertEquals(8, CourierBillMatcher::selfAmount(Category::DIFF, 10, 8, null, $name)); + } + + public function test_actual_freight_rule_applies_to_matching_manual_reset_and_scoped_historical_refresh(): void + { + Storage::fake('local');$db=CourierBillMatcher::db();$store=app(CourierBillStore::class); + $store->saveGroup(null,['name'=>'中铁物流','express_names'=>['中铁物流','武进安能','中铁客退']]); + $shipping=app(\App\Support\CourierBills\ShippingLookup::class)->connection(); + foreach (['中铁物流','武进安能','中铁客退'] as $i=>$name) { + $shipping->table('jst_oms_shipping')->insert(['source_id'=>$i+1,'express_no'=>'ACTUAL'.($i+1),'express_name1'=>$name,'ship_time'=>'2026-11-03 09:00:00']); + $shipping->table('jst_oms_shipping_freight')->insert(['source_id'=>$i+1,'status'=>'OK','freight'=>10,'charge_weight'=>2]); + } + $path=tempnam(sys_get_temp_dir(),'actual').'.csv';file_put_contents($path,"单号,运费\nACTUAL1,8\nACTUAL2,8\nACTUAL3,8\n"); + try {$file=$store->upload([new \Illuminate\Http\UploadedFile($path,'中铁物流.csv',null,null,true)],'2026-11',[],'测试')[0];} + finally {@unlink($path);} + $id=(int)$db->table('courier_bill_files')->where('id',$file)->value('statement_id'); + $this->assertEquals([10,10,8],$db->table('courier_bill_lines')->where('statement_id',$id)->orderBy('row_no')->pluck('self_amount')->all()); + $line=(int)$db->table('courier_bill_lines')->where('waybill_no','ACTUAL1')->value('id'); + app(CourierBillMatcher::class)->resolve($id,[$line],'agree','测试'); + $this->assertEquals(8,$db->table('courier_bill_lines')->where('id',$line)->value('self_amount')); + app(CourierBillMatcher::class)->resolve($id,[$line],null,'测试'); + $this->assertEquals(10,$db->table('courier_bill_lines')->where('id',$line)->value('self_amount')); + $db->table('courier_bill_lines')->where('statement_id',$id)->update(['self_amount'=>8]); + $db->table('bill_surcharge_matches')->insert(['scope'=>'courier','owner_id'=>$id,'file_id'=>$file,'sheet'=>'附加费','row_no'=>5,'bill_month'=>'2026-11','waybill_no'=>'ACTUAL1','item'=>'上楼费','summary_label'=>'附加费','bill_amount'=>5,'self_amount'=>9,'match_status'=>'已匹配','match_note'=>'保持核价']); + $options=['--statement'=>[$id],'--express'=>['中铁物流','武进安能']]; + $this->artisan('courier-bills:refresh-settlement',$options)->assertSuccessful(); + $this->assertEquals(24,$db->table('courier_bill_lines')->sum('self_amount')); + $this->artisan('courier-bills:refresh-settlement',$options+['--apply'=>true])->assertSuccessful(); + $this->assertEquals([10,10,8],$db->table('courier_bill_lines')->orderBy('row_no')->pluck('self_amount')->all()); + $this->assertEquals(9,$db->table('bill_surcharge_matches')->value('self_amount')); + $out=tmpfile();app(StatementExporter::class)->export($id,$out);rewind($out);$path=tempnam(sys_get_temp_dir(),'actual-export');file_put_contents($path,stream_get_contents($out));fclose($out); + try { + $book=IOFactory::load($path);$grid=$book->getSheetByName('对账')->toArray(null,false,false);$headers=$grid[0]; + $calcCol=array_search('核算运费',$headers,true);$settleCol=array_search('结算运费',$headers,true); + $this->assertSame($calcCol+1,$settleCol);$this->assertEquals(10,$grid[1][$settleCol]); + $this->assertSame(1,count(array_filter($headers,fn($h)=>$h==='结算运费')));$book->disconnectWorksheets(); + } finally {@unlink($path);} + } + public function test_wujin_subsidy_is_directional_summed_once_and_exported_separately(): void { Storage::fake('local');
项目快递提供金额自算金额差异归到汇总列
快递单号快递运费快递重量发货时间发货数据快递名称1核算运费计费重量运费差重量差自算金额未发出来源处理结果发货时间发货数据快递名称1核算运费结算运费计费重量运费差重量差未发出来源处理结果
{{ $line->ship_time ? substr((string) $line->ship_time, 0, 16) : '' }} {{ $line->express_name }} {{ $money($line->calc_freight) }}{{ $money($line->self_amount) }} {{ $line->charge_weight === null ? '' : rtrim(rtrim(number_format((float) $line->charge_weight, 3), '0'), '.') }} {{ $line->bill_amount !== null && $line->calc_freight !== null ? $money((float) $line->bill_amount - (float) $line->calc_freight) : '' }} {{ $line->bill_weight !== null && $line->charge_weight !== null ? round((float) $line->bill_weight - (float) $line->charge_weight, 3) : '' }}{{ $money($line->self_amount) }} {{ $line->unshipped_sources }} {{ \App\Support\CourierBills\Category::RESOLUTIONS[$line->resolution] ?? '' }}{{ $line->resolved_by ? ' · ' . $line->resolved_by : '' }}