feat(快递对账): 按较低金额结算并补武进韵达重量差 #1774

Open
limeng wants to merge 1 commits from feature/limeng-courier-settlement-cap into main
13 changed files with 322 additions and 13 deletions

View File

@ -0,0 +1,114 @@
<?php
namespace App\Console\Commands;
use App\Models\Common\Company;
use App\Support\CourierBills\{Category, CourierBillMatcher, SummaryMapper, WeightDifferenceSubsidy};
use Illuminate\Console\Command;
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 = '按快递提供与核价较低值结算运费和附加费,并更新武进韵达重量差补款';
public function handle(CourierBillMatcher $matcher, WeightDifferenceSubsidy $subsidy): int
{
if (! $this->option('all-open') && $this->option('statement') === []) {
$this->error('请选择对账单或 --all-open');
return self::FAILURE;
}
if (app()->environment('production') && ! env('FINANCE_BATCH_CONTAINER')) {
$this->error('请通过 run-finance-batch.sh 执行');
return self::FAILURE;
}
Company::findOrFail((int) $this->option('company'))->makeCurrent(true);
$lock = Cache::lock('courier-bills:refresh-settlement', 3900);
if (! $lock->get()) { $this->error('结算刷新正在运行'); return self::FAILURE; }
$started = microtime(true);
$queries = 0; $sqlMs = 0.0;
DB::listen(static function ($query) use (&$queries, &$sqlMs): void { $queries++; $sqlMs += $query->time; });
$db = CourierBillMatcher::db();
$folder = 'private/courier-settlement/' . gmdate('Ymd-His') . '-' . bin2hex(random_bytes(4));
try {
$ids = $db->table('courier_bill_statements')->where('status', '<>', 'confirmed')
->when(! $this->option('all-open'), fn ($q) => $q->whereIn('id', $this->option('statement')))
->where('line_count', '>', 0)->orderBy('id')->pluck('id');
foreach ($ids as $id) {
$result = $db->transaction(function () use ($db, $id, $matcher, $subsidy, $folder) {
$statement = $db->table('courier_bill_statements')->where('id', $id)->lockForUpdate()->first();
if (! $statement || $statement->status === 'confirmed') return ['statement' => $id, 'skipped' => true];
$beforeSummary = $db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('id')->get();
$beforeFees = $db->table('bill_surcharge_matches')->where('scope', 'courier')->where('owner_id', $id)->orderBy('id')->get();
$stream = null;
if ($this->option('apply')) {
$path = $folder . '/' . $id . '.ndjson';
Storage::disk('local')->put($path, '');
$stream = fopen(Storage::disk('local')->path($path), 'wb');
if (! $stream) throw new \RuntimeException('无法保存备份');
fwrite($stream, json_encode(['statement' => $statement, 'summary' => $beforeSummary, 'surcharges' => $beforeFees], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR) . "\n");
}
$changed = 0; $decrease = 0.0; $scanned = 0;
try {
foreach ($db->table('courier_bill_lines')->where('statement_id', $id)->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);
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]);
}
} finally { if ($stream) fclose($stream); }
$weight = $subsidy->summary((int) $id);
$existing = $beforeSummary->firstWhere('label', WeightDifferenceSubsidy::LABEL);
$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) {
$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),
'match_note' => $fee->match_note . ';快递提供金额较低,按快递金额结算',
]);
}
}
if ($this->option('apply') && ($changed > 0 || $subsidyChanged || $feeChanges > 0)) {
$matcher->refreshSummary((int) $id, false);
// 只允许报价核价金额按较低的快递提供金额下调。
$fields = ['file_id', 'sheet', 'row_no', 'waybill_no', 'item', 'bill_amount', 'self_amount'];
$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, '.', '');
return $copy;
});
$afterFees = $db->table('bill_surcharge_matches')->where('scope', 'courier')->where('owner_id', $id)->get();
if ($normalize($expectedFees) != $normalize($afterFees)) throw new \RuntimeException('附加费来源发生变化,本张账单已回退');
$protected = static fn ($rows) => $rows->filter(fn ($r) => $r->manual || ($r->label !== WeightDifferenceSubsidy::LABEL
&& in_array(SummaryMapper::classify($r->label), ['AL', 'supplement'], true)))
->map(fn ($r) => [$r->label, $r->bill_amount === null ? null : (float) $r->bill_amount,
$r->self_amount === null ? null : (float) $r->self_amount, (bool) $r->manual])
->sortBy(fn ($r) => json_encode($r))->values()->all();
if ($protected($beforeSummary) != $protected($db->table('courier_bill_summary_items')->where('statement_id', $id)->get())) {
throw new \RuntimeException('人工金额、配件扣款或补记账发生变化,本张账单已回退');
}
}
return ['statement' => $id, 'month' => $statement->bill_month, 'scanned' => $scanned,
'changed' => $changed, 'settlement_decrease' => round($decrease, 2), 'weight_subsidy' => $weight,
'fee_changes' => $feeChanges, 'fee_decrease' => round($feeDecrease, 2),
'applied' => (bool) $this->option('apply')];
});
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
}
$this->info(json_encode(['backup' => $this->option('apply') ? $folder : null,
'seconds' => round(microtime(true) - $started, 3), 'peak_mib' => round(memory_get_peak_usage(true) / 1048576, 2),
'queries' => $queries, 'sql_ms' => round($sqlMs, 2)], JSON_UNESCAPED_UNICODE));
return self::SUCCESS;
} catch (\Throwable $e) {
report($e); $this->error($e->getMessage());
return self::FAILURE;
} finally { $lock->release(); }
}
}

View File

@ -153,13 +153,14 @@ final class CourierBillMatcher
return [Category::DIFF, null];
}
/** 自算金额:处理结果优先;否则一致类和前月补提供按核算运费,其余为 0。 */
/** 自算金额:处理结果优先;正常应付按快递提供与核算运费较低者结算,缺少核算依据保持空白。 */
public static function selfAmount(string $category, ?float $calcFreight, mixed $billAmount, ?string $resolution): ?float
{
return match ($resolution) {
'agree' => $billAmount === null ? null : (float) $billAmount,
'exclude', 'defer' => 0.0,
default => in_array($category, [...Category::PAYABLE, Category::PRIOR], true) ? $calcFreight : 0.0,
default => in_array($category, [...Category::PAYABLE, Category::PRIOR], true)
? ($calcFreight !== null && $billAmount !== null ? min($calcFreight, round((float) $billAmount, 2)) : $calcFreight) : 0.0,
};
}
@ -196,7 +197,7 @@ final class CourierBillMatcher
* 重建自动小汇总行(手工行保留)。项目名称照财务习惯写,保证归集规则落到正确的列:
* 「X月运费」→ 成品;「跨月订单-X月,本月不结算」「快递不符(未匹配本快递发货数据)」→ 匹配不到。
*/
public function refreshSummary(int $statementId): void
public function refreshSummary(int $statementId, bool $refreshSources = true): void
{
$db = self::db();
$month = (string) $db->table('courier_bill_statements')->where('id', $statementId)->value('bill_month');
@ -255,17 +256,32 @@ final class CourierBillMatcher
}
}
uasort($items, static fn (array $a, array $b): int => $a['sort'] <=> $b['sort']);
$this->addAccessoryDeduction($statementId, $month, $items);
if ($refreshSources) {
$this->addAccessoryDeduction($statementId, $month, $items);
} else {
// 仅调整结算口径时,沿用已保存的配件扣款和补记账,不重新读取来源。
foreach ($db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', false)->get() as $saved) {
if ($saved->label !== WeightDifferenceSubsidy::LABEL && in_array(SummaryMapper::classify($saved->label), ['AL', 'supplement'], true)) {
$items[$saved->label] = ['bill' => $saved->bill_amount, 'self' => $saved->self_amount, 'sort' => $saved->sort];
$kinds[$saved->label] = 'saved';
}
}
}
$manualLabels = $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('manual', true)->pluck('label')
->map(static fn ($label): string => preg_replace('/\s+/u', '', (string) $label) ?? '')->flip();
$subsidy = app(WeightDifferenceSubsidy::class)->summary($statementId);
if ($subsidy['count'] > 0 && ! isset($manualLabels[WeightDifferenceSubsidy::LABEL])) {
$items[WeightDifferenceSubsidy::LABEL] = ['bill' => null, 'self' => $subsidy['amount'], 'sort' => 9200];
$kinds[WeightDifferenceSubsidy::LABEL] = 'weight-subsidy';
}
$kinds['配件补发扣款'] = 'accessory';
$surchargeMatcher=app(SurchargeSettlementMatcher::class);
$surchargeMatcher->courier($statementId);
if ($refreshSources) $surchargeMatcher->courier($statementId);
$matchedFees=$surchargeMatcher->ready()?$surchargeMatcher->query('courier',$statementId)
->selectRaw('summary_label, SUM(self_amount) AS amount')->groupBy('summary_label')->pluck('amount','summary_label')->all():[];
$fees = $this->surchargeItems($statementId);
$template = $this->templateFor($statementId);
$this->addRebooks($statementId, $template, $manualLabels, $items, $kinds);
if ($refreshSources) $this->addRebooks($statementId, $template, $manualLabels, $items, $kinds);
$sort = 8000;
foreach ($fees as $item => $sum) {
if (($template !== null || ! isset($manualLabels[$item])) && ! isset($items[$item])) {
@ -301,7 +317,7 @@ final class CourierBillMatcher
foreach ($items as $name => $item) {
$db->table('courier_bill_summary_items')->insert([
'statement_id' => $statementId, 'label' => $name, 'bill_amount' => $item['bill'] === null ? null : round($item['bill'], 4),
'self_amount' => round($item['self'], 2), 'manual' => false, 'sort' => ++$sort,
'self_amount' => $item['self'] === null ? null : round($item['self'], 2), 'manual' => false, 'sort' => ++$sort,
]);
}
}

View File

@ -109,7 +109,7 @@ final class StatementExporter
[$sources, $original] = $this->originalHeaders($ids);
$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];
$fullHeader = [...$original, ...array_keys(self::FRONT), ...array_values($rest), '结算运费', '差异原因', '处理结果', ...$tail];
// 原始账单:底文件原封不动;第 2 个及以后的文件按值复制
$originals = $this->writeOriginal($book, $files, $baseFileId);
@ -138,6 +138,7 @@ final class StatementExporter
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)]);
@ -180,6 +181,21 @@ final class StatementExporter
});
$this->writeRebooks($book, $ids, $tail, $groupNames, $multi);
$subsidy = app(WeightDifferenceSubsidy::class);
foreach ($ids as $id) {
if (! $db->table('courier_bill_summary_items')->where('statement_id', $id)->where('label', WeightDifferenceSubsidy::LABEL)->where('manual', false)->exists()) continue;
$summary = $subsidy->summary($id);
if ($summary['count'] === 0) continue;
$sheet = '重量差补款-' . $id;
$book->row($sheet, ['快递单号', '快递重量', '我方计费重量', '重量差(快递-我方)', '快递运费', '核算运费', '可补运费差额'], true);
foreach ($subsidy->query($id)->orderBy('id')->lazyById(500) as $line) {
$book->row($sheet, [$line->waybill_no, (float) $line->bill_weight, (float) $line->charge_weight,
round((float) $line->bill_weight - (float) $line->charge_weight, 4), (float) $line->bill_amount,
(float) $line->calc_freight, round((float) $line->bill_amount - (float) $line->calc_freight, 4)]);
}
$book->row($sheet, ['差额合计', null, null, null, null, null, $summary['difference']], true);
$book->row($sheet, ['差额合计×50%,补给快递', null, null, null, null, null, $summary['amount']], true);
}
foreach($ids as $id) app(SurchargeSettlementMatcher::class)->write($book,'courier',$id);
$this->writeNotes($book, $ids, $originals);
$book->writeTo($output);

View File

@ -52,7 +52,7 @@ final class SummaryTemplate
$index = [];
foreach ($template as $label) {
$key = self::normalize($label);
if ($key === '') {
if ($key === '' || ($key === WeightDifferenceSubsidy::LABEL && ! isset($auto[$key]))) {
continue;
}
// 手工小汇总里同名的行可以有两行(如一正一负的车费),都留着;系统金额只填第一行
@ -97,7 +97,7 @@ final class SummaryTemplate
$result = [];
foreach ($labels as $label) {
$label = trim((string) $label);
if ($label !== '' && ! preg_match(self::TRANSIENT, $label)) {
if ($label !== '' && $label !== WeightDifferenceSubsidy::LABEL && ! preg_match(self::TRANSIENT, $label)) {
$result[] = self::roll($label, $delta);
}
}

View File

@ -208,6 +208,10 @@ class SurchargeSettlementMatcher
$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);
if ($scope === 'courier' && $row['bill_amount'] !== null && (float) $row['bill_amount'] < $row['self_amount']) {
$row['self_amount'] = round((float) $row['bill_amount'], 2);
$row['match_note'] .= ';快递提供金额较低,按快递金额结算';
}
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)))));
}

View File

@ -0,0 +1,29 @@
<?php
namespace App\Support\CourierBills;
use Illuminate\Database\Query\Builder;
/** 武进韵达重量多报超过1kg的运费差额,汇总后补给快递50%。 */
final class WeightDifferenceSubsidy
{
public const LABEL = '补武进韵达重量差运费(50%)';
public function query(int $statementId): Builder
{
return CourierBillMatcher::db()->table('courier_bill_lines')
->where('statement_id', $statementId)->where('express_name', '武进韵达')
->whereIn('category', [...Category::PAYABLE, Category::PRIOR])->whereNull('resolution')
->whereRaw('bill_weight - charge_weight > 1')
->whereColumn('bill_amount', '>', 'calc_freight');
}
/** 按差额合计计算一半,再四舍五入到分,避免逐行四舍五入累积误差。 */
public function summary(int $statementId): array
{
$sum = $this->query($statementId)->selectRaw('COUNT(*) AS n, SUM(bill_amount - calc_freight) AS difference')->first();
return ['count' => (int) $sum->n, 'difference' => round((float) $sum->difference, 4),
'amount' => round((float) $sum->difference / 2, 2)];
}
}

View File

@ -1,5 +1,6 @@
[
"courier-bills:match-reverse",
"courier-bills:refresh-settlement",
"portal-freight:import-pending",
"courier-surcharge:match-bills",
"planting-reimbursement:auto-confirm",

View File

@ -8,7 +8,7 @@ is_import=0
CAIWU_BATCH_CALLER_DIR="$PWD"
export CAIWU_BATCH_CALLER_DIR
case "${1:-}" in
portal-freight:import-pending|courier-surcharge:match-bills|courier-bills:match-reverse) is_import=1 ;;
portal-freight:import-pending|courier-surcharge:match-bills|courier-bills:match-reverse|courier-bills:refresh-settlement) is_import=1 ;;
planting-reimbursement:auto-confirm) is_import=1 ;;
jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history|business-mirror:sync-returned-parcels|courier-surcharge:pull-customer-service) ;;

View File

@ -63,4 +63,4 @@
<span class="cbr-pager">共 {{ number_format($cbLines->total()) }} 条,每页 50 条 {{ $cbLines->links('business.partials.previous-next-pagination') }}</span>
</div>
</form>
<p class="cbr-muted">处理结果:同意付款 = 自算金额取快递金额;已与快递确认剔除 / 转下月 = 本月自算金额为 0。改完对应对账单的小汇总和快递应付汇总自动重算。</p>
<p class="cbr-muted">正常应付运费取快递提供与我方核算的较低金额。处理结果:同意付款 = 自算金额取快递金额;已与快递确认剔除 / 转下月 = 本月自算金额为 0。武进韵达重量多报超过1公斤的正向运费差额,合计后补50%,在小汇总单列。改完对应对账单的小汇总和快递应付汇总自动重算。</p>

View File

@ -47,6 +47,7 @@
<div class="fc-workspace"><div>
<section class="cbr-panel" aria-label="小汇总">
<h3>小汇总</h3>
<p class="cbr-muted cbr-panel-body">正常应付运费与已核价附加费取快递提供和我方核算的较低金额,已有手工处理优先。武进韵达:快递重量超过我方计费重量1公斤的单据,快递多报的运费差额合计的50%单列补给快递。</p>
<div class="cbr-scroll">
<table>
<thead><tr><th scope="col">项目</th><th scope="col" class="num">快递提供金额</th><th scope="col" class="num">自算金额</th><th scope="col" class="num">差异</th><th scope="col">归到汇总列</th><th scope="col"></th></tr></thead>

View File

@ -1,7 +1,7 @@
@if ($surchargeRows !== null && $surchargeRows->total() > 0)
<section class="cbr-panel" aria-label="附加费核对明细">
<h3>附加费核对明细</h3>
<p class="cbr-muted cbr-panel-body">按账单月份归集,以单号、附加费类型和快递归属匹配最近3个月(含账单当月)的结算金额。未匹配的金额留空,重复费用不再计入;不会将对方金额作为自算金额。</p>
<p class="cbr-muted cbr-panel-body">按账单月份归集,以单号、附加费类型和快递归属匹配最近3个月(含账单当月)的结算金额。未匹配的金额留空,重复费用不再计入。@if (isset($cbStatement))自有快递已核价附加费取对方金额与核算金额的较低值。@else按已核实的费用计算结算金额。@endif</p>
<div class="cbr-scroll"><table>
<thead><tr>@foreach (['来源工作表','快递单号','附加费类型','对方金额','自算金额','差额','匹配状态','快递名称','平台商品ID','商品编码','店铺名称','线上订单号','说明'] as $label)<th scope="col">{{ $label }}</th>@endforeach</tr></thead>
<tbody>@foreach ($surchargeRows as $fee)<tr>

View File

@ -170,6 +170,21 @@ class BillSurchargeMatchingTest extends FeatureTestCase
protected function tearDown(): void {foreach($this->temp as $path)@unlink($path);parent::tearDown();}
public function test_courier_surcharge_uses_lower_billed_amount_without_paying_unverified_fees(): void
{
$store=app(CourierBillStore::class);$store->saveGroup(null,['name'=>'封顶测试','express_names'=>['封顶测试']]);
foreach(['CAPFEE1','CAPFEE2','CAPFEE3']as$no)$this->ship($no,'封顶测试');
$this->quote('封顶测试','拦截费','固定单价','30元/单','按单收取','自有快递');
$path=$this->book(['账单'=>[['单号','运费'],['CAPFEE1',10],['CAPFEE2',10],['CAPFEE3',10]],
'附加费'=>[['快递单号','附加费金额','附加费类型'],['CAPFEE1',20,'拦截费'],['CAPFEE2',40,'拦截费'],['CAPFEE3',10,'包装费']]]);
$file=$store->upload([new UploadedFile($path,'封顶测试11月.xlsx',null,null,true)],'2026-11',[],'测试')[0];
$id=$store->db()->table('courier_bill_files')->where('id',$file)->value('statement_id');
$rows=app(SurchargeSettlementMatcher::class)->query('courier',$id)->orderBy('row_no')->get();
$this->assertEquals(20,$rows[0]->self_amount);$this->assertStringContainsString('按快递金额结算',$rows[0]->match_note);
$this->assertEquals(30,$rows[1]->self_amount);$this->assertNull($rows[2]->self_amount);
$this->assertEquals(50,$store->db()->table('courier_bill_summary_items')->where('statement_id',$id)->where('label','附加费')->value('self_amount'));
}
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,

View File

@ -0,0 +1,113 @@
<?php
namespace Tests\Feature\Business;
use App\Support\CourierBills\{Category, CourierBillMatcher, CourierBillStore, StatementExporter, SummaryMapper, SummaryTemplate, WeightDifferenceSubsidy};
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Tests\Feature\FeatureTestCase;
class CourierSettlementRulesTest extends FeatureTestCase
{
public function test_freight_settlement_caps_at_billed_amount_but_keeps_missing_values_and_manual_decisions(): void
{
foreach ([Category::MATCH, Category::DIFF, Category::UNCALCULATED, Category::PRIOR] as $category) {
$this->assertEquals(8, CourierBillMatcher::selfAmount($category, 10, 8, null));
$this->assertEquals(10, CourierBillMatcher::selfAmount($category, 10, 12, null));
$this->assertEquals(0, CourierBillMatcher::selfAmount($category, 10, 0, null));
$this->assertNull(CourierBillMatcher::selfAmount($category, null, 8, null));
$this->assertEquals(10, CourierBillMatcher::selfAmount($category, 10, null, null));
}
$this->assertEquals(12, CourierBillMatcher::selfAmount(Category::DIFF, 10, 12, 'agree'));
foreach (['exclude', 'defer'] as $resolution) $this->assertEquals(0, CourierBillMatcher::selfAmount(Category::DIFF, 10, 8, $resolution));
$this->assertEquals(0, CourierBillMatcher::selfAmount(Category::DUPLICATE, 10, 8, null));
$this->assertEquals(8, CourierBillMatcher::selfAmount(Category::DIFF, 10, 8.004, null));
$this->assertEquals(8.01, CourierBillMatcher::selfAmount(Category::DIFF, 10, 8.006, null));
}
public function test_wujin_subsidy_is_directional_summed_once_and_exported_separately(): void
{
Storage::fake('local');
$db = CourierBillMatcher::db();
$group = app(CourierBillStore::class)->saveGroup(null, ['name' => '武进韵达', 'express_names' => ['武进韵达']]);
$id = $db->table('courier_bill_statements')->insertGetId(['group_id' => $group, 'bill_month' => '2026-11', 'status' => 'open']);
$cases = [
['ELIGIBLE', '武进韵达', 12, 10, 120, 100, Category::DIFF, null],
['BOUNDARY', '武进韵达', 11, 10, 120, 100, Category::DIFF, null],
['REVERSED', '武进韵达', 8, 10, 120, 100, Category::DIFF, null],
['LOWBILL', '武进韵达', 12, 10, 80, 100, Category::DIFF, null],
['OTHER', '武进韵达快运', 12, 10, 120, 100, Category::DIFF, null],
['DUPLICATE', '武进韵达', 12, 10, 120, 100, Category::DUPLICATE, null],
['EXCLUDED', '武进韵达', 12, 10, 120, 100, Category::DIFF, 'exclude'],
['AGREED', '武进韵达', 12, 10, 120, 100, Category::DIFF, 'agree'],
['CENTS1', '武进韵达', 12, 10, 100.01, 100, Category::DIFF, null],
['CENTS2', '武进韵达', 12, 10, 100.01, 100, Category::DIFF, null],
];
foreach ($cases as $i => [$no,$courier,$billWeight,$chargeWeight,$bill,$calc,$category,$resolution]) {
$db->table('courier_bill_lines')->insert(['statement_id'=>$id,'file_id'=>0,'sheet'=>'账单','row_no'=>$i+1,'raw'=>'[]',
'waybill_no'=>$no,'express_name'=>$courier,'bill_weight'=>$billWeight,'charge_weight'=>$chargeWeight,
'bill_amount'=>$bill,'calc_freight'=>$calc,'category'=>$category,'resolution'=>$resolution,
'self_amount'=>CourierBillMatcher::selfAmount($category,$calc,$bill,$resolution)]);
}
$subsidy = app(WeightDifferenceSubsidy::class)->summary($id);
$this->assertSame(3, $subsidy['count']);
$this->assertEquals(20.02, $subsidy['difference']);
$this->assertEquals(10.01, $subsidy['amount']);
app(CourierBillMatcher::class)->refreshSummary($id);
$item = $db->table('courier_bill_summary_items')->where('statement_id',$id)->where('label',WeightDifferenceSubsidy::LABEL)->sole();
$this->assertEquals(10.01,$item->self_amount);
$this->assertNull($item->bill_amount);
$mapped = SummaryMapper::map([['label'=>$item->label,'bill'=>null,'self'=>(float)$item->self_amount]]);
$this->assertEquals(10.01,$mapped['J']);
$this->assertEquals(0,$mapped['AS']);
$this->assertSame([],SummaryTemplate::fromLabels([WeightDifferenceSubsidy::LABEL],1));
$this->assertSame([],SummaryTemplate::apply([WeightDifferenceSubsidy::LABEL],[],12));
$out = tmpfile();app(StatementExporter::class)->export($id,$out);rewind($out);
$path = tempnam(sys_get_temp_dir(),'subsidy');file_put_contents($path,stream_get_contents($out));fclose($out);
try {$book=IOFactory::load($path);$sheet=$book->getSheetByName('重量差补款-'.$id);$this->assertNotNull($sheet);$this->assertEquals(10.01,$sheet->getCell('G6')->getValue());$book->disconnectWorksheets();} finally {@unlink($path);}
$db->table('courier_bill_lines')->where('statement_id',$id)->update(['resolution'=>'exclude']);
app(CourierBillMatcher::class)->refreshSummary($id);
$this->assertSame(0,$db->table('courier_bill_summary_items')->where('statement_id',$id)->where('label',WeightDifferenceSubsidy::LABEL)->count());
}
public function test_refresh_streams_existing_lines_and_does_not_touch_confirmed_statements(): void
{
Storage::fake('local');$db=CourierBillMatcher::db();
$group=app(CourierBillStore::class)->saveGroup(null,['name'=>'测试快递','express_names'=>['测试快递']]);
$ids=[];foreach(['open','confirmed']as$status){$ids[$status]=$db->table('courier_bill_statements')->insertGetId(['group_id'=>$group,'bill_month'=>$status==='open'?'2026-11':'2026-10','status'=>$status,'line_count'=>1001]);}
$rows=[];for($i=1;$i<=1001;$i++)$rows[]=['statement_id'=>$ids['open'],'file_id'=>0,'sheet'=>'账单','row_no'=>$i,'raw'=>'[]','waybill_no'=>'CAP'.$i,'express_name'=>'测试快递','bill_amount'=>8,'calc_freight'=>10,'self_amount'=>10,'category'=>Category::DIFF];
foreach(array_chunk($rows,100)as$chunk)$db->table('courier_bill_lines')->insert($chunk);
$confirmed=$rows[0];$confirmed['statement_id']=$ids['confirmed'];$db->table('courier_bill_lines')->insert($confirmed);
$this->artisan('courier-bills:refresh-settlement',['--all-open'=>true])->assertSuccessful();
$this->assertEquals(10010,$db->table('courier_bill_lines')->where('statement_id',$ids['open'])->sum('self_amount'));
$this->artisan('courier-bills:refresh-settlement',['--all-open'=>true,'--apply'=>true])->assertSuccessful();
$this->assertEquals(8008,$db->table('courier_bill_lines')->where('statement_id',$ids['open'])->sum('self_amount'));
$this->assertEquals(10,$db->table('courier_bill_lines')->where('statement_id',$ids['confirmed'])->value('self_amount'));
$this->assertNotEmpty(Storage::disk('local')->allFiles('private/courier-settlement'));
$this->artisan('courier-bills:refresh-settlement',['--all-open'=>true,'--apply'=>true])->assertSuccessful();
$this->assertEquals(8008,$db->table('courier_bill_lines')->where('statement_id',$ids['open'])->sum('self_amount'));
}
public function test_refresh_caps_existing_surcharges_without_repricing_sources(): void
{
Storage::fake('local');$db=CourierBillMatcher::db();
$group=app(CourierBillStore::class)->saveGroup(null,['name'=>'测试快递','express_names'=>['测试快递']]);
$id=$db->table('courier_bill_statements')->insertGetId(['group_id'=>$group,'bill_month'=>'2026-11','status'=>'open','line_count'=>1]);
$db->table('courier_bill_lines')->insert(['statement_id'=>$id,'file_id'=>0,'sheet'=>'账单','row_no'=>1,'raw'=>'[]','waybill_no'=>'CAP1','bill_amount'=>8,'calc_freight'=>10,'self_amount'=>10,'category'=>Category::DIFF]);
$db->table('courier_bill_summary_items')->insert(['statement_id'=>$id,'label'=>'11月运费','bill_amount'=>8,'self_amount'=>10,'manual'=>false,'sort'=>1]);
$db->table('courier_bill_summary_items')->insert(['statement_id'=>$id,'label'=>'配件补发扣款','bill_amount'=>null,'self_amount'=>-12,'manual'=>false,'sort'=>2]);
$db->table('courier_bill_summary_items')->insert(['statement_id'=>$id,'label'=>'补10月记账','bill_amount'=>null,'self_amount'=>15,'manual'=>false,'sort'=>3]);
$db->table('courier_bill_summary_items')->insert(['statement_id'=>$id,'label'=>'手工调整','bill_amount'=>5,'self_amount'=>3,'manual'=>true,'sort'=>4]);
$db->table('courier_bill_files')->insert(['id'=>100,'statement_id'=>$id,'bill_month'=>'2026-11','original_name'=>'测试.xlsx','stored_path'=>'test.xlsx','status'=>'parsed']);
$db->table('courier_bill_lines')->where('statement_id',$id)->update(['file_id'=>100]);
$db->table('courier_bill_surcharges')->insert(['file_id'=>100,'sheet'=>'附加费','row_no'=>2,'waybill_no'=>'CAP1','item'=>'上楼费','amount'=>20]);
$db->table('bill_surcharge_matches')->insert(['scope'=>'courier','owner_id'=>$id,'file_id'=>0,'sheet'=>'附加费','row_no'=>2,'bill_month'=>'2026-11','waybill_no'=>'CAP1','item'=>'上楼费','summary_label'=>'附加费','bill_amount'=>20,'self_amount'=>30,'match_status'=>'已匹配','match_note'=>'已核实费用']);
$this->artisan('courier-bills:refresh-settlement',['--all-open'=>true,'--apply'=>true])->assertSuccessful();
$this->assertEquals(20,$db->table('bill_surcharge_matches')->value('self_amount'));
$this->assertEquals(20,$db->table('courier_bill_summary_items')->where('label','附加费')->value('self_amount'));
$this->assertEquals(8,$db->table('courier_bill_lines')->value('self_amount'));
$this->assertEquals(-12,$db->table('courier_bill_summary_items')->where('label','配件补发扣款')->value('self_amount'));
$this->assertEquals(15,$db->table('courier_bill_summary_items')->where('label','补10月记账')->value('self_amount'));
$this->assertEquals(3,$db->table('courier_bill_summary_items')->where('label','手工调整')->value('self_amount'));
}
}