快递账单保留历史记账明细并展示退回补款核对 (#1734)

This commit is contained in:
limeng 2026-12-04 15:59:03 +08:00
parent ffcd457d12
commit eeb3b33d64
7 changed files with 359 additions and 24 deletions

View File

@ -384,7 +384,9 @@ final class CourierBillMatcher
return;
}
foreach (Rebooks::totals($plan['rows']) as $deductMonth => $amount) {
$totals = Rebooks::totals($plan['rows']);
foreach (array_unique(array_column($plan['rows'], 'deduct_month')) as $deductMonth) {
$amount = $totals[$deductMonth] ?? 0.0;
$label = Rebooks::label($deductMonth);
$items[$label] = ['bill' => null, 'self' => $amount, 'sort' => 9100 + (int) substr($deductMonth, 5, 2)];
$kinds[$label] = 'rebook:' . (int) substr($deductMonth, 5, 2);

View File

@ -0,0 +1,80 @@
<?php
namespace App\Support\CourierBills;
use Illuminate\Support\Facades\Schema;
/** 仅用于补记账复核;原始退回和记账记录均保持不变。 */
final class RebookReturns
{
/** @param list<array<string,mixed>> $rows @return list<array<string,mixed>> */
public function annotate(array $rows): array
{
$wanted = [];
foreach ($rows as $row) {
foreach (self::numbers($row) as $number) {
$wanted[self::key($number)] = true;
}
}
$db = Rebooks::db();
$available = $wanted !== [] && Schema::connection($db->getName())->hasTable('courier_returned_parcels');
$found = [];
if ($available) {
// 按主键分批读取窄列,一次遍历,不能对每个工单循环模糊扫全表。
foreach ($db->table('courier_returned_parcels')->where('returned_qty', '>', 0)
->select(['source_id', 'waybill', 'received_at'])->lazyById(1000, 'source_id') as $record) {
$key = self::key((string) $record->waybill);
if ($key !== null && isset($wanted[$key])) {
$found[$key][] = ['waybill' => trim((string) $record->waybill), 'received_at' => (string) $record->received_at];
}
}
}
foreach ($rows as &$row) {
$exact = $fuzzy = [];
foreach (self::numbers($row) as $number) {
foreach ($found[self::key($number)] ?? [] as $record) {
$fuzzy[] = $record;
if ($number === $record['waybill']) {
$exact[] = $record;
}
}
}
$matches = $exact ?: $fuzzy;
$analysis = trim((string) ($row['analysis'] ?? ''));
$historicReturn = str_contains($analysis, '已退回') || str_contains($analysis, '原单退回改0') || str_contains($analysis, '换单退回');
$row['_return_status'] = $matches !== [] ? '已退回' : ($historicReturn ? '历史记账已记退回' : ($available ? '未匹配退回记录' : '退回数据未就绪'));
$row['_return_method'] = $exact !== [] ? '精确匹配' : ($fuzzy !== [] ? '模糊匹配(格式或T前缀)' : '');
$row['_matched_return_no'] = implode('、', array_unique(array_column($matches, 'waybill')));
$row['_return_received_at'] = $matches === [] ? '' : max(array_column($matches, 'received_at'));
// 只重判此前“未退回”的行,不覆盖未发出、取消记账等已有财务判定。
if ($analysis === '未退回' && $matches !== []) {
$lossFreight = preg_match('/丢件|双面单|违规件|站点异常/u', (string) ($row['bookkeeping_reason'] ?? '')) === 1;
$cost = $row['cost'] ?? null;
$freight = $row['settle_freight'] ?? null;
if (! $lossFreight || (is_numeric($cost) && is_numeric($freight))) {
$row['_return_current'] = $lossFreight ? round((float) $freight + round((float) $cost * .2, 2), 2) : 0.0;
$row['_return_analysis'] = $lossFreight ? '记账损耗+运费' : '原单退回改0';
} else {
$row['_return_status'] = '已退回,成本或结算运费缺失待核对';
}
}
}
unset($row);
return $rows;
}
/** @return list<string> */
private static function numbers(array $row): array
{
return array_values(array_unique(array_filter(array_map(static fn ($v): string => trim((string) $v),
[$row['tracking_no_clean'] ?? '', $row['tracking_no'] ?? '', $row['return_no'] ?? '']), static fn (string $v): bool => self::key($v) !== null)));
}
private static function key(string $number): ?string
{
$number = Waybill::normalize(mb_convert_kana($number, 'as'));
return $number === null ? null : (preg_match('/^T\d{10,30}$/', $number) ? substr($number, 1) : $number);
}
}

View File

@ -186,18 +186,25 @@ final class Rebooks
{
$names = array_flip($names);
$deductions = [];
$sourceRows = [];
foreach ($this->bookkeeping($window) as $row) {
$carrier = trim((string) ($row['carrier'] ?? ''));
if (! isset($names[$carrier])) {
continue;
}
$sourceRows[] = $row;
}
$sourceRows = app(RebookReturns::class)->annotate($sourceRows);
foreach ($sourceRows as $row) {
$carrier = trim((string) ($row['carrier'] ?? ''));
$waybill = Waybill::normalize((string) (($row['tracking_no_clean'] ?? '') ?: ($row['tracking_no'] ?? '')));
if ($waybill === null) {
continue;
}
$key = $waybill . '|' . $row['summary_month'];
$deductions[$key] ??= ['deduct_month' => (string) $row['summary_month'], 'waybill' => $waybill, 'carrier' => $carrier,
'deducted' => '0', 'info' => $row];
'deducted' => '0', 'info' => $row, 'sources' => []];
$deductions[$key]['sources'][] = $row;
$deductions[$key]['deducted'] = bcadd($deductions[$key]['deducted'], (string) (($row['settle_bookkeeping'] ?? '') ?: '0'), 4);
}
if ($deductions === []) {
@ -232,6 +239,7 @@ final class Rebooks
$current >= $deducted => ['仍应扣,不补', 0.0],
default => ['本期补款', round($deducted - $current, 2)],
};
$d['info']['_rebook_sources'] = $d['sources'];
$rows[] = ['deduct_month' => $d['deduct_month'], 'waybill' => $d['waybill'], 'carrier' => $d['carrier'],
'deducted' => $deducted, 'refunded' => $done === null ? null : round($done['amount'], 2), 'current' => $current,
'amount' => $amount, 'status' => $status, 'info' => $d['info']];

View File

@ -3,6 +3,7 @@
namespace App\Support\CourierBills;
use Illuminate\Support\Facades\Storage;
use Modules\EcommerceFinance\Services\CourierBookkeepingRegistry;
/**
* 对账单导出(内部版)。一张账单拆成了几家(合并账单)时,几家一起导出成一个文件:汇总页每家一个小汇总,
@ -182,7 +183,7 @@ final class StatementExporter
}
/**
* 补记账子表:本期要补的单(当时扣的 − 现在应扣),表名照手工版「补9月记账」「2026.8-9月记账补款」。
* 补记账子表:全部历史记账及本期差额(已补记录不重复计入),表名照手工版「补9月记账」「2026.8-9月记账补款」。
*
* @param list<int> $ids
* @param list<string> $tail
@ -190,8 +191,6 @@ final class StatementExporter
*/
private function writeRebooks(StreamingWorkbook $book, array $ids, array $tail, array $groupNames, bool $multi): void
{
$info = ['线上订单号' => 'online_order_no', '记账原因' => 'bookkeeping_reason', '商品编码' => 'product_code', '商品名称' => 'product_name',
'发起时间' => 'started_at', '店铺名称' => 'shop_name', '订单发货仓库' => 'shipping_warehouse', '退回单号' => 'return_no', '记账分析' => 'analysis'];
$plans = [];
$window = [];
foreach ($ids as $id) {
@ -201,10 +200,10 @@ final class StatementExporter
report($error);
continue;
}
$rows = array_values(array_filter($plan['rows'], static fn (array $r): bool => $r['amount'] > 0));
if ($rows !== []) {
$plans[$id] = $rows;
$window = array_values(array_unique([...$window, ...array_column($rows, 'deduct_month')]));
if ($plan['window'] !== []) {
// 全部历史记账都展示,已补、未退回等仅供核对,不重复计入本期金额。
$plans[$id] = $plan['rows'];
$window = array_values(array_unique([...$window, ...$plan['window']]));
}
}
if ($plans === []) {
@ -212,14 +211,86 @@ final class StatementExporter
}
sort($window);
$name = Rebooks::sheetName($window);
$book->row($name, ['扣款月份', '物流单号', '物流公司', ...array_keys($info), '当时扣(结算记账)', '现在应扣', '本期补款', ...$tail], true);
foreach ($plans as $id => $rows) {
foreach ($rows as $r) {
$book->row($name, [$r['deduct_month'], $r['waybill'], $r['carrier'],
...array_map(static fn (string $f): ?string => ($r['info'][$f] ?? '') === '' ? null : (string) $r['info'][$f], array_values($info)),
$r['deducted'], $r['current'], $r['amount'], ...($multi ? [$groupNames[$id] ?? ''] : [])]);
$fields = ['summary_month' => ['label' => '月份', 'type' => 'text']];
foreach (app(CourierBookkeepingRegistry::class)->fields() as $field => $definition) {
$fields[$field] = $definition;
if ($field === 'settle_bookkeeping') {
$fields['current_bookkeeping'] = ['label' => '现结算记账金额', 'type' => 'number'];
$fields['rebook_amount'] = ['label' => '需补款记账金额', 'type' => 'number'];
}
}
foreach (['return_status' => '退回核对状态', 'return_match' => '退回匹配方式', 'matched_return' => '匹配退回单号',
'received_at' => '退回进仓时间', 'refund_status' => '补款状态'] as $field => $label) {
$fields[$field] = ['label' => $label, 'type' => 'text'];
}
$fields['refunded'] = ['label' => '历史已补金额', 'type' => 'number'];
$fields['payable_refund'] = ['label' => '本期补款金额', 'type' => 'number'];
$book->row($name, [...array_column($fields, 'label'), ...$tail], true);
$rowNumber = 1;
$settleColumn = array_search('settle_bookkeeping', array_keys($fields), true) + 1;
$currentColumn = $settleColumn + 1;
foreach ($plans as $id => $rows) {
foreach ($rows as $r) {
$sources = $r['info']['_rebook_sources'] ?? [$r['info']];
$remainingCurrent = (float) ($r['current'] ?? $r['deducted']);
$remainingRefund = (float) $r['amount'];
$last = array_key_last($sources);
$historyWritten = false;
foreach ($sources as $index => $source) {
$rowNumber++;
$values = $source;
$old = (float) ($source['settle_bookkeeping'] ?? $r['deducted']);
$share = $r['deducted'] > 0 ? $old / $r['deducted'] : 0;
$current = $r['current'] === null ? (float) ($source['_return_current'] ?? $old)
: ($index === $last ? $remainingCurrent : round((float) $r['current'] * $share, 2));
$payable = $index === $last ? $remainingRefund : round((float) $r['amount'] * $share, 2);
$remainingCurrent = round($remainingCurrent - $current, 2);
$remainingRefund = round($remainingRefund - $payable, 2);
$values['summary_month'] = $r['deduct_month'];
$values['tracking_no'] = $values['tracking_no'] ?? $r['waybill'];
$values['tracking_no_clean'] = $r['waybill'];
$values['carrier'] = $source['carrier'] ?? $r['carrier'];
$values['settle_bookkeeping'] = $old;
$values['current_bookkeeping'] = $current;
if (isset($source['_return_analysis'])) {
$values['analysis'] = $source['_return_analysis'];
}
$values['rebook_amount'] = new XlsxFormula(
self::columnName($settleColumn) . $rowNumber . '-' . self::columnName($currentColumn) . $rowNumber,
round($old - $current, 2),
);
$values['return_status'] = $source['_return_status'] ?? '';
$values['return_match'] = $source['_return_method'] ?? '';
$values['matched_return'] = $source['_matched_return_no'] ?? '';
$values['received_at'] = $source['_return_received_at'] ?? '';
$values['refund_status'] = $r['status'] === '待复核' && isset($source['_return_current'])
? '已退回待复核,暂未计入补款' : $r['status'];
$values['refunded'] = $historyWritten ? null : $r['refunded'];
$historyWritten = true;
$values['payable_refund'] = $payable;
$cells = [];
foreach ($fields as $field => $definition) {
$value = $values[$field] ?? null;
$cells[] = $value instanceof XlsxFormula ? $value : ($definition['type'] === 'number'
? ($value === null || $value === '' ? null : (float) $value)
: ($value === null || $value === '' ? null : (string) $value));
}
$book->row($name, [...$cells, ...($multi ? [$groupNames[$id] ?? ''] : [])]);
}
}
}
}
private static function columnName(int $column): string
{
$name = '';
while ($column > 0) {
$column--;
$name = chr(65 + $column % 26) . $name;
$column = intdiv($column, 26);
}
return $name;
}
/**

View File

@ -85,7 +85,7 @@ final class CourierBillRebookIntegrityTest extends FeatureTestCase
try {
$sheet = $book->getSheetByName('补10月记账');
$this->assertNotNull($sheet);
$this->assertEquals([100, 0, 100], array_slice($sheet->toArray(null, false, false)[1], -3));
$this->assertEquals([100, 0, 100], array_slice($sheet->toArray(null, true, false)[1], 28, 3));
} finally { $book->disconnectWorksheets(); }
} finally { @unlink($path); }
}

View File

@ -113,14 +113,20 @@ final class CourierBillRebooksTest extends FeatureTestCase
$book = IOFactory::createReader('Xlsx')->load($path);
$sheet = $book->getSheetByName('2026.9-10月记账补款');
$this->assertNotNull($sheet);
$rows = $sheet->toArray(null, false, false);
$this->assertSame(['扣款月份', '物流单号', '物流公司', '线上订单号'], array_slice($rows[0], 0, 4));
$this->assertSame(['当时扣(结算记账)', '现在应扣', '本期补款'], array_slice($rows[0], -3));
$this->assertSame(['2026-09', 'YT0001', '苏北宿迁圆通', '6919047515577462663'], array_slice($rows[1], 0, 4));
$this->assertEquals([100, 0, 100], array_slice($rows[1], -3));
$this->assertEquals(['2026-10', 'YT0003'], array_slice($rows[2], 0, 2));
$this->assertEquals([80, 20, 60], array_slice($rows[2], -3));
$this->assertCount(3, $rows);
$rows = $sheet->toArray(null, true, false);
$this->assertSame(['月份', '物流单号', '快递单号整理', '物流公司', '线上订单号'], array_slice($rows[0], 0, 5));
$this->assertSame(['结算记账', '现结算记账金额', '需补款记账金额', '结算运费'], array_slice($rows[0], 28, 4));
$this->assertSame(['2026-09', 'YT0001', 'YT0001', '苏北宿迁圆通', '6919047515577462663'], array_slice($rows[1], 0, 5));
$this->assertEquals([100, 0, 100], array_slice($rows[1], 28, 3));
$splitRows = array_values(array_filter(array_slice($rows, 1), static fn ($r) => $r[1] === 'YT0003'));
$this->assertCount(2, $splitRows);
$this->assertEquals([50, 12.5, 37.5], array_slice($splitRows[0], 28, 3));
$this->assertEquals([30, 7.5, 22.5], array_slice($splitRows[1], 28, 3));
$this->assertSame('原单退回', $rows[1][5]);
$this->assertSame('已退回,不记', $rows[1][32]);
$this->assertSame('=AC2-AD2', $sheet->getCell('AE2')->getValue());
$this->assertContains($sheet->getCell('E2')->getDataType(), [DataType::TYPE_STRING, DataType::TYPE_INLINE]);
$this->assertCount(7, $rows);
$this->assertSame('汇总', $book->getSheetNames()[0]);
$book->disconnectWorksheets();
@ -180,6 +186,94 @@ final class CourierBillRebooksTest extends FeatureTestCase
$this->get($page(['cb_view' => 'statement', 'statement' => $statementId]))->assertOk()->assertSeeText('补记账:不补');
}
public function test_already_refunded_records_remain_visible_but_do_not_add_to_summary(): void
{
$store = app(CourierBillStore::class);
$group = $store->saveGroup(null, ['name' => '新北中通测试', 'express_names' => ['新北中通测试'], 'rebook_months' => 2]);
$store->saveSummaryTemplates([['title' => '新北中通测试11月', 'labels' => ['运费11月', '2026.9-10月记账补款'], 'group' => '新北中通测试']], '2026-11');
$this->bookkeeping([['2026-09', 'PAID100', '新北中通测试', 100, 'ORDER100']]);
Rebooks::db()->table('courier_bill_rebooks')->insert([
'waybill_no' => 'PAID100', 'deduct_month' => '2026-09', 'refund_month' => '2026-10',
'amount' => 100, 'source' => 'import', 'created_at' => now(),
]);
$id = Rebooks::db()->table('courier_bill_statements')->insertGetId([
'group_id' => $group, 'bill_month' => '2026-11', 'status' => 'open', 'created_at' => now(), 'updated_at' => now(),
]);
app(CourierBillMatcher::class)->refreshSummary($id);
$amount = Rebooks::db()->table('courier_bill_summary_items')->where('statement_id', $id)
->where('label', '2026.9-10月记账补款')->value('self_amount');
$this->assertNotNull($amount);
$this->assertEquals(0, $amount);
$path = tempnam(sys_get_temp_dir(), 'rebook_zero_');
$this->temp[] = $path;
$output = fopen($path, 'wb');
try { app(StatementExporter::class)->export($id, $output); } finally { fclose($output); }
$book = IOFactory::createReader('Xlsx')->load($path);
try {
$sheet = $book->getSheetByName('2026.9-10月记账补款');
$this->assertNotNull($sheet);
$this->assertSame(2, $sheet->getHighestDataRow());
$this->assertSame('需补款记账金额', (string) $sheet->getCell('AE1')->getValue());
$this->assertSame('PAID100', (string) $sheet->getCell('B2')->getValue());
$headers = array_map('strval', $sheet->rangeToArray('A1:AR1')[0]);
$this->assertSame('已补(2026-10)', (string) $sheet->getCell([array_search('补款状态', $headers, true) + 1, 2])->getValue());
$this->assertEquals(0, $sheet->getCell([array_search('本期补款金额', $headers, true) + 1, 2])->getValue());
} finally { $book->disconnectWorksheets(); }
}
public function test_rebook_analysis_preserves_reason_and_uses_required_keywords(): void
{
$db = Rebooks::db();
if (! \Illuminate\Support\Facades\Schema::connection($db->getName())->hasTable('courier_returned_parcels')) {
\Illuminate\Support\Facades\Schema::connection($db->getName())->create('courier_returned_parcels', function ($table): void {
$table->unsignedBigInteger('source_id')->primary();
$table->string('waybill');
$table->dateTime('received_at');
$table->decimal('returned_qty', 12, 4);
});
}
$store = app(CourierBillStore::class);
$group = $store->saveGroup(null, ['name' => '原因验证', 'express_names' => ['原因验证'], 'rebook_months' => 1]);
$reasons = ['快递丢件', '双面单', '违规件', '站点异常', '运输破损'];
$connection = DB::connection(config('database.supplier_payable_maintenance_connection'));
foreach ($reasons as $i => $reason) {
$connection->table('supplier_payable_overrides')->insert([
'company_id' => $this->company->id, 'dataset' => Rebooks::BOOKKEEPING_DATASET, 'record_key' => 'reason-'.$i,
'values' => json_encode(['summary_month' => '2026-10', 'tracking_no' => 'REASON'.$i, 'carrier' => '原因验证',
'settle_bookkeeping' => '100', 'cost' => '40', 'loss' => '8', 'settle_freight' => '7',
'bookkeeping_reason' => $reason, 'analysis' => '未退回', 'product_code' => '000123'], JSON_UNESCAPED_UNICODE),
'created_at' => now(), 'updated_at' => now(),
]);
Rebooks::db()->table('courier_bill_rebook_reviews')->insert([
'waybill_no' => 'REASON'.$i, 'deduct_month' => '2026-10', 'current_amount' => $i < 4 ? 15 : 0, 'updated_at' => now(),
]);
$returned = ['source_id' => 500 + $i, 'waybill' => 'REASON'.$i, 'received_at' => '2026-12-02 10:00:00', 'returned_qty' => 1];
if (\Illuminate\Support\Facades\Schema::connection($db->getName())->hasColumn('courier_returned_parcels', 'generation')) {
$returned += ['generation' => 'test', 'synced_at' => now()];
}
$db->table('courier_returned_parcels')->insert($returned);
}
$id = Rebooks::db()->table('courier_bill_statements')->insertGetId([
'group_id' => $group, 'bill_month' => '2026-11', 'status' => 'open', 'created_at' => now(), 'updated_at' => now(),
]);
app(CourierBillMatcher::class)->refreshSummary($id);
$path = tempnam(sys_get_temp_dir(), 'rebook_reasons_');
$this->temp[] = $path;
$output = fopen($path, 'wb');
try { app(StatementExporter::class)->export($id, $output); } finally { fclose($output); }
$book = IOFactory::createReader('Xlsx')->load($path);
try {
$sheet = $book->getSheetByName('补10月记账');
foreach ($reasons as $i => $reason) {
$r = $i + 2;
$this->assertSame($reason, (string) $sheet->getCell('F'.$r)->getValue());
$this->assertSame($i < 4 ? '记账损耗+运费' : '原单退回改0', (string) $sheet->getCell('AG'.$r)->getValue());
$this->assertSame('000123', (string) $sheet->getCell('G'.$r)->getValue());
$this->assertEquals($i < 4 ? 85 : 100, $sheet->getCell('AE'.$r)->getCalculatedValue());
}
} finally { $book->disconnectWorksheets(); }
}
/** @param list<array{string,string,string,float|int,string}> $rows 扣款月份、物流单号、物流公司、结算记账、线上订单号 */
private function bookkeeping(array $rows): void
{

View File

@ -0,0 +1,80 @@
<?php
namespace Tests\Feature\Business;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\Rebooks;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Tests\Feature\FeatureTestCase;
final class CourierRebookReturnReviewTest extends FeatureTestCase
{
public function test_four_carrier_names_returns_fuzzy_match_and_prior_refund_are_accounted_once(): void
{
$db = Rebooks::db();
if (! Schema::connection($db->getName())->hasTable('courier_returned_parcels')) {
Schema::connection($db->getName())->create('courier_returned_parcels', function ($table): void {
$table->unsignedBigInteger('source_id')->primary();
$table->string('waybill');
$table->dateTime('received_at');
$table->decimal('returned_qty', 12, 4);
});
}
$names = ['新北中通', '新北中通其他', '新北中通配件', '新北中通其他配件'];
$group = app(CourierBillStore::class)->saveGroup(null, ['name' => '新北分组', 'express_names' => $names, 'rebook_months' => 2]);
$reasons = ['快递丢件', '双面单', '买家原因', '站点异常'];
$nums = ['301233122220', '301233122221', '301233122222', '301233122223'];
$store = DB::connection(config('database.supplier_payable_maintenance_connection'));
foreach ($names as $i => $name) {
$row = ['summary_month' => '2026-10', 'tracking_no' => $nums[$i], 'carrier' => $name,
'settle_bookkeeping' => '100', 'analysis' => '未退回', 'bookkeeping_reason' => $reasons[$i], 'cost' => '40', 'settle_freight' => '7'];
$store->table('supplier_payable_overrides')->insert(['company_id' => $this->company->id, 'dataset' => Rebooks::BOOKKEEPING_DATASET,
'record_key' => 'return-'.$i, 'values' => json_encode($row), 'created_at' => now(), 'updated_at' => now()]);
if ($i === 0) {
$store->table('supplier_payable_overrides')->insert(['company_id' => $this->company->id, 'dataset' => Rebooks::BOOKKEEPING_DATASET,
'record_key' => 'duplicate-source', 'values' => json_encode($row), 'created_at' => now(), 'updated_at' => now()]);
}
// 第二票通过去掉 T 前缀匹配;第四票未实际退回,不能触发补款。
$return = ['source_id' => 100 + $i, 'waybill' => $i === 1 ? 'T'.$nums[$i] : $nums[$i],
'received_at' => '2026-12-02 10:00:00', 'returned_qty' => $i === 3 ? 0 : 1];
if (Schema::connection($db->getName())->hasColumn('courier_returned_parcels', 'generation')) {
$return += ['generation' => 'test', 'synced_at' => now()];
}
$db->table('courier_returned_parcels')->insert($return);
}
$db->table('courier_bill_rebooks')->insert(['waybill_no' => $nums[0], 'deduct_month' => '2026-10',
'refund_month' => '2026-10', 'amount' => 85, 'source' => 'import', 'created_at' => now()]);
// 结算仍由已复核金额驱动;退回匹配不能擅自把其他分组未复核金额计入应付。
foreach ([0 => 15, 1 => 15, 2 => 0] as $i => $amount) {
$db->table('courier_bill_rebook_reviews')->insert(['waybill_no' => $nums[$i], 'deduct_month' => '2026-10',
'current_amount' => $amount, 'updated_at' => now()]);
}
$id = $db->table('courier_bill_statements')->insertGetId(['group_id' => $group, 'bill_month' => '2026-11', 'status' => 'open',
'created_at' => now(), 'updated_at' => now()]);
$plan = app(Rebooks::class)->forStatement($id);
$rows = collect($plan['rows'])->keyBy('waybill');
$this->assertCount(4, $rows);
$this->assertSame(200.0, $rows[$nums[0]]['deducted']);
$this->assertCount(2, $rows[$nums[0]]['info']['_rebook_sources']);
$this->assertSame(0.0, $rows[$nums[0]]['amount']);
$this->assertSame(15.0, $rows[$nums[0]]['current']);
$this->assertSame(85.0, $rows[$nums[1]]['amount']);
$this->assertSame('模糊匹配(格式或T前缀)', $rows[$nums[1]]['info']['_rebook_sources'][0]['_return_method']);
$this->assertSame(100.0, $rows[$nums[2]]['amount']);
$this->assertSame(0.0, $rows[$nums[3]]['amount']);
$this->assertSame(['2026-10' => 185.0], Rebooks::totals($plan['rows']));
$this->assertSame(15.0, $rows[$nums[1]]['info']['_rebook_sources'][0]['_return_current']);
$this->assertSame(0.0, $rows[$nums[2]]['info']['_rebook_sources'][0]['_return_current']);
$this->assertArrayNotHasKey('_return_current', $rows[$nums[3]]['info']['_rebook_sources'][0]);
$annotated = app(\App\Support\CourierBills\RebookReturns::class)->annotate([
['tracking_no' => $nums[0], 'analysis' => '未退回', 'bookkeeping_reason' => '丢件', 'cost' => null, 'settle_freight' => 7],
['tracking_no' => $nums[0], 'analysis' => '已退回,记账损耗+运费', 'bookkeeping_reason' => '丢件', 'cost' => 40, 'settle_freight' => 7],
]);
$this->assertSame('已退回,成本或结算运费缺失待核对', $annotated[0]['_return_status']);
$this->assertArrayNotHasKey('_return_current', $annotated[0]);
$this->assertSame('已退回,记账损耗+运费', $annotated[1]['analysis']);
$this->assertArrayNotHasKey('_return_analysis', $annotated[1]);
}
}