CaiWuXiTong/tests/Feature/Business/CourierBillReconciliationTest.php
limeng e6b9775a24 快递账单支持合并导出、原始运费表和四位金额 (#1544)
按 0006、0007、0008 顺序整合;账单相关测试及隔离 MariaDB 迁移验证通过。
2026-11-28 11:31:38 +08:00

665 lines
42 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Tests\Feature\Business;
use App\Support\CourierBills\BillParser;
use App\Support\CourierBills\BillWorkbookReader;
use App\Support\CourierBills\Category;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\PayableSummary;
use App\Support\CourierBills\StatementExporter;
use App\Support\CourierBills\SummaryMapper;
use App\Support\CourierBills\Waybill;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Tests\Feature\FeatureTestCase;
final class CourierBillReconciliationTest extends FeatureTestCase
{
private array $temp = [];
protected function setUp(): void
{
parent::setUp();
Storage::fake('local');
}
protected function tearDown(): void
{
foreach ($this->temp as $path) {
@unlink($path);
}
parent::tearDown();
}
public function test_summary_mapper_follows_finance_rules(): void
{
$this->assertSame('AL', SummaryMapper::classify('成品补发配件扣快递'));
$this->assertSame('supplement', SummaryMapper::classify('补9月记账'));
$this->assertSame('supplement', SummaryMapper::classify('2026.8-9月记账补款'));
$this->assertSame('waybill', SummaryMapper::classify('面单'));
$this->assertSame('AP', SummaryMapper::classify('面单费'));
$this->assertSame('AM', SummaryMapper::classify('违约金'));
$this->assertSame('AJ', SummaryMapper::classify('已结算'));
$this->assertSame('AK', SummaryMapper::classify('记账'));
$this->assertSame('AH', SummaryMapper::classify('未发出'));
$this->assertSame('AR', SummaryMapper::classify('实际已发出未发出'));
$this->assertSame('AI', SummaryMapper::classify('11月运费,本月不结算'));
$this->assertSame('AI', SummaryMapper::classify('跨月订单-11月,本月不结算'));
$this->assertSame('AN', SummaryMapper::classify('退件费'));
$this->assertSame('AF', SummaryMapper::classify('运费-重量差'));
$this->assertSame('AF', SummaryMapper::classify('9月运费(前月补提供)'));
$this->assertSame('AR', SummaryMapper::classify('拉货到云仓的车费'));
$this->assertSame('AR', SummaryMapper::classify('货值需扣'));
$cells = SummaryMapper::map([
['label' => '运费', 'bill' => 1000.0, 'self' => 990.0],
['label' => '记账', 'bill' => null, 'self' => -50.0],
['label' => '违约金', 'bill' => null, 'self' => -30.0],
['label' => '补9月记账', 'bill' => null, 'self' => 20.0],
['label' => '面单', 'bill' => 100.0, 'self' => 0.0],
['label' => '拉货到云仓的车费', 'bill' => null, 'self' => -500.0],
['label' => '上楼费', 'bill' => 10.0, 'self' => 4.0],
]);
$this->assertSame(1110.0, $cells['K']);
$this->assertSame(20.0, $cells['J']);
$this->assertSame(20.0, $cells['AS']);
$this->assertSame(100.0, $cells['N']);
$this->assertSame(30.0, $cells['P']);
$this->assertSame(500.0, $cells['O']);
$this->assertSame(10.0, $cells['AF']);
$this->assertSame(50.0, $cells['AK']);
$this->assertSame(506.0, $cells['AR']);
// L = 差异明细合计 − 违约金 − 借支 = (10+50+30+506) − 30 − 500
$this->assertSame(66.0, $cells['L']);
$this->assertSame('拉货到云仓的车费500元;上楼费6元', $cells['AT']);
$totals = SummaryMapper::totals($cells + ['I' => 5.0, 'Q' => 0.0]);
$this->assertSame(1044.0, $totals['M']);
// R = K − L − N − O − P + Q + J + I
$this->assertSame(1110.0 - 66 - 100 - 500 - 30 + 0 + 20 + 5, $totals['R']);
}
public function test_waybill_normalization_rejects_truncated_scientific_notation(): void
{
$this->assertSame('YT123456789', Waybill::normalize(" @yt123456789 "));
$this->assertSame('79150812345678', Waybill::normalize('79150812345678.0'));
$this->assertSame('79150812345678', Waybill::normalize('7.9150812345678E+13'));
$this->assertNull(Waybill::normalize('7.91508E+13'));
$this->assertNull(Waybill::normalize('合计金额'));
}
public function test_parser_finds_header_below_title_and_skips_sheets_without_waybills(): void
{
$path = $this->workbook([
'说明' => [['这是快递自己的汇总页'], ['总金额', 100]],
'明细' => [
['北京韵达 2026年10月账单'],
[],
['序号', '运单编号', '目的省', '计费重量', '运费'],
[1, '4312345678901', '江苏', 1.5, 6.5],
[2, '7.91508E+13', '浙江', 2, 7],
[3, 'JT0001234567', '上海', '', '1,234.50'],
[4, '#N/A', '', '', ''],
['合计', '', '', '', 1248],
],
]);
$items = iterator_to_array(app(BillParser::class)->parse($path, 'xlsx'), false);
$sheets = array_values(array_filter($items, fn ($i) => $i['type'] === 'sheet'));
$this->assertSame('没有找到单号列,整表跳过', $sheets[0]['skipped']);
$this->assertSame(3, $sheets[1]['header_row']);
$lines = array_values(array_filter($items, fn ($i) => $i['type'] === 'line'));
$this->assertSame(['4312345678901', 'JT0001234567'], array_column($lines, 'waybill'));
$this->assertSame([6.5, 1234.5], array_column($lines, 'amount'));
$this->assertSame(1.5, $lines[0]['weight']);
$this->assertSame(['1', '4312345678901', '江苏', '1.5', '6.5'], $lines[0]['raw']);
$rejects = array_values(array_filter($items, fn ($i) => $i['type'] === 'reject'));
$this->assertSame(5, $rejects[0]['row']);
}
public function test_only_freight_sheets_are_read_when_the_bill_has_surcharge_sheets(): void
{
$path = $this->workbook([
'账单明细' => [['快递单号', '计费重量', '运费'], ['ZT001', 1, 10], ['合计', '', 10]],
'加收&上楼费' => [['列1', '运单号', '最新状态', '费用项目', '费用金额'], ['', 'ZT001', '已签收', '上楼费', 5]],
]);
$items = iterator_to_array(app(BillParser::class)->parse($path, 'xlsx'), false);
$lines = array_values(array_filter($items, fn ($i) => $i['type'] === 'line'));
$this->assertSame([['账单明细', 'ZT001', 10.0]], array_map(fn ($l) => [$l['sheet'], $l['waybill'], $l['amount']], $lines));
$skipped = array_values(array_filter($items, fn ($i) => $i['type'] === 'sheet' && isset($i['skipped'])));
$this->assertSame('加收&上楼费', $skipped[0]['sheet']);
// 没有一张表的金额列叫「运费」时,照旧读所有带单号和金额的表
$path = $this->workbook(['明细' => [['运单号', '金额'], ['ZT002', 8]]]);
$lines = array_values(array_filter(iterator_to_array(app(BillParser::class)->parse($path, 'xlsx'), false), fn ($i) => $i['type'] === 'line'));
$this->assertSame('ZT002', $lines[0]['waybill']);
}
public function test_csv_in_gbk_is_read(): void
{
$path = tempnam(sys_get_temp_dir(), 'bill_csv_');
$this->temp[] = $path;
file_put_contents($path, mb_convert_encoding("运单号,运费\nYD100000001,5.5\n", 'GB18030', 'UTF-8'));
$lines = array_values(array_filter(iterator_to_array(app(BillParser::class)->parse($path, 'csv'), false), fn ($i) => $i['type'] === 'line'));
$this->assertSame('YD100000001', $lines[0]['waybill']);
$this->assertSame(5.5, $lines[0]['amount']);
}
public function test_upload_classifies_lines_settles_and_flags_next_month_duplicates(): void
{
$this->seedShipping();
$store = app(CourierBillStore::class);
$groupId = $store->saveGroup(null, ['name' => '河北中通-江三/小件', 'express_names' => ['河北中通-江三', '河北中通小件-江三'],
'summary_carrier' => '河北中通', 'owner' => '张三', 'keywords' => '河北中通']);
$store->saveGroup(null, ['name' => '霸州百世快运-雅柏', 'express_names' => ['霸州百世快运-雅柏'], 'summary_carrier' => null, 'owner' => null, 'keywords' => null]);
$file = $this->upload('河北中通10月账单.xlsx', [
['运单编号', '重量', '运费'],
['ZT001', 2, 10], // 一致
['ZT002', 3, 12], // 运费有差(核算 11)
['ZT002', 3, 12], // 本账单重复
['ZT003', 1, 5], // 未发出
['ZT004', 1, 6], // 匹配不到
['ZT005', 1, 7], // 快递不符(百世)
['ZT006', 1, 8], // 前月补提供-9月
['ZT007', 1, 9], // 跨月订单-11月
['ZT008', 1, 4], // 一致(系统未核算)
]);
$ids = $store->upload([$file], '2026-10', [], 'tester');
$fileRow = $store->db()->table('courier_bill_files')->find($ids[0]);
$this->assertSame('parsed', $fileRow->status);
$this->assertSame($groupId, (int) $fileRow->group_id);
$statementId = (int) $fileRow->statement_id;
$categories = $store->db()->table('courier_bill_lines')->where('statement_id', $statementId)->orderBy('id')
->get(['waybill_no', 'category', 'category_month', 'self_amount'])
->map(fn ($l) => [$l->waybill_no, $l->category, $l->category_month, $l->self_amount === null ? null : (float) $l->self_amount])->all();
$this->assertSame([
['ZT001', Category::MATCH, null, 10.0],
['ZT002', Category::DIFF, null, 11.0],
['ZT002', Category::DUPLICATE, null, 0.0],
['ZT003', Category::UNSHIPPED, null, 0.0],
['ZT004', Category::UNMATCHED, null, 0.0],
['ZT005', Category::MISMATCH, null, 0.0],
['ZT006', Category::PRIOR, '2026-09', 6.0],
['ZT007', Category::LATER, '2026-11', 0.0],
['ZT008', Category::UNCALCULATED, null, null],
], $categories);
$this->assertSame(['ZT009'], $store->db()->table('courier_bill_unprovided')->where('statement_id', $statementId)->pluck('waybill_no')->all());
$summary = $store->db()->table('courier_bill_summary_items')->where('statement_id', $statementId)->orderBy('sort')
->get()->map(fn ($i) => [$i->label, (float) $i->bill_amount, (float) $i->self_amount])->all();
$this->assertSame([
['10月运费', 26.0, 21.0],
['9月运费(前月补提供)', 8.0, 6.0],
['跨月订单-11月,本月不结算', 9.0, 0.0],
['重复', 12.0, 0.0],
['未发出', 5.0, 0.0],
['匹配不到', 6.0, 0.0],
['快递不符(未匹配本快递发货数据)', 7.0, 0.0],
], $summary);
// 处理结果:同意付款按快递金额
$line = $store->db()->table('courier_bill_lines')->where('statement_id', $statementId)->where('waybill_no', 'ZT008')->first();
app(CourierBillMatcher::class)->resolve($statementId, [$line->id], 'agree', 'tester');
$this->assertSame(4.0, (float) $store->db()->table('courier_bill_lines')->where('id', $line->id)->value('self_amount'));
$store->addSummaryItem($statementId, '违约金', null, -30);
// 汇总:归集到「河北中通」
$summaryService = app(PayableSummary::class);
$store->db()->table('courier_payable_summary_rows')->insert([
'month' => '2026-10', 'sort' => 1, 'carrier' => '河北中通', 'created_at' => now(), 'updated_at' => now(),
'cells' => json_encode(['H' => '河北中通', 'E' => '承运', 'I' => 100, 'Q' => 0]),
]);
$row = $summaryService->rows('2026-10')[0];
$this->assertSame('待处理', $row['status']);
$this->assertSame(73.0, $row['cells']['K']);
$this->assertSame(30.0, $row['cells']['P']);
// 差异:运费 26−25=1、前月补提供 2 → 成品 3;跨月 9 + 快递不符 7 + 匹配不到 6 → 22;重复 12;未发出 5;违约金 30
$this->assertSame(3.0, $row['cells']['AF']);
$this->assertSame(22.0, $row['cells']['AI']);
$this->assertSame(42.0, $row['cells']['L']);
$this->assertSame(73.0 - 42 - 30 + 100, $row['cells']['R']);
// 确认结算 → 台账;下月账单再出现同一单号就是重复
$store->confirm($statementId, 'tester');
$this->assertSame('已确认', $summaryService->rows('2026-10')[0]['status']);
$this->assertEqualsCanonicalizing(['ZT001', 'ZT002', 'ZT006', 'ZT008'],
$store->db()->table('courier_bill_ledger')->where('statement_id', $statementId)->pluck('waybill_no')->all());
$next = $this->upload('河北中通11月.xlsx', [['运单编号', '运费'], ['ZT001', 10], ['ZT007', 9]]);
$ids = $store->upload([$next], '2026-11', [], 'tester');
$nextStatement = (int) $store->db()->table('courier_bill_files')->where('id', $ids[0])->value('statement_id');
$this->assertSame([[Category::DUPLICATE, '2026-10'], [Category::MATCH, null]],
$store->db()->table('courier_bill_lines')->where('statement_id', $nextStatement)->orderBy('id')->get()
->map(fn ($l) => [$l->category, $l->category_month])->all());
// 撤销确认后台账清掉
$store->unconfirm($statementId);
$this->assertSame(0, $store->db()->table('courier_bill_ledger')->where('statement_id', $statementId)->count());
}
public function test_unidentified_file_waits_for_group_and_export_omits_empty_sheets(): void
{
$this->seedShipping();
$store = app(CourierBillStore::class);
$groupId = $store->saveGroup(null, ['name' => '河北中通-江三/小件', 'express_names' => ['河北中通-江三'], 'summary_carrier' => null, 'owner' => null, 'keywords' => null]);
$ids = $store->upload([$this->upload('账单.xlsx', [['运单号', '运费', '收件人电话'], ['ZT001', 10, '13800000000'], ['ZT004', 6, '']])], '2026-10', [], 'tester');
$this->assertSame('pending_group', $store->db()->table('courier_bill_files')->where('id', $ids[0])->value('status'));
$store->assign($ids[0], $groupId);
$statementId = (int) $store->db()->table('courier_bill_files')->where('id', $ids[0])->value('statement_id');
$path = tempnam(sys_get_temp_dir(), 'bill_export_');
$this->temp[] = $path;
$handle = fopen($path, 'wb');
app(StatementExporter::class)->export($statementId, $handle);
fclose($handle);
$book = IOFactory::createReader('Xlsx')->load($path);
$this->assertSame(['汇总', '运费', '对账', '匹配不到', '未提供', '说明'], $book->getSheetNames());
$recon = $book->getSheetByName('对账');
$header = $recon->rangeToArray('A1:AE1')[0];
$this->assertSame(['运单号', '运费', '收件人电话', '称重重量', '首重'], array_slice($header, 0, 5));
$this->assertSame('ZT001', (string) $recon->getCell('A2')->getValue());
$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
$book->disconnectWorksheets();
}
public function test_payable_summary_imports_manual_table_and_carries_balance_forward(): void
{
$rows = [
[null, null, '示例公司2026年应付10月份快递、物流运费清单'],
['合同开始时间', '合同截止时间', '签订公司', '负责人', '承运状态', '序号', '快递公司主体名称', '承运商', '月初结余', '补给快递'],
[null, null, null, null, null, null, null, null, null, null, '快递提供金额', '对账差异金额', '核对确定金额', '面单', '借支', '赔付金额', '其他补款', '本月应付金额', '本次实付金额'],
[45944, 46309, '示例公司', '张三', '承运', 1, '示例物流有限公司', '示例快运', 0, 100.5, 2000, 50, 1950, 0, 0, 0, 0, 2050.5, 2050.5],
[0, 0, 0, '不合作', '停运', 2, 0, '旧账快递', -3000, 0, 0, 0, 0, 0, 0, 0, 0, -3000],
];
$path = $this->workbook(['汇总' => $rows, '附加费' => [['x']]]);
$service = app(PayableSummary::class);
$this->assertSame(2, $service->import($path, '2026-10')['rows']);
$october = $service->rows('2026-10');
$this->assertSame('2025-10-14', $october[0]['cells']['A']);
$this->assertSame(2050.5, $october[0]['cells']['R']);
$this->assertSame('待处理', $october[0]['status']);
$this->assertSame('旧账挂账', $october[1]['status']);
$this->assertSame(2, $service->createMonth('2026-11'));
$november = $service->rows('2026-11');
$this->assertSame(0.0, $november[0]['cells']['I']);
$this->assertSame(-3000.0, $november[1]['cells']['I']);
$this->assertSame('本月无账单', $november[0]['status']);
$service->updateCell($november[0]['id'], 'Q', '12.5');
$this->assertSame(12.5, $service->rows('2026-11')[0]['cells']['R']);
$path = tempnam(sys_get_temp_dir(), 'summary_export_');
$this->temp[] = $path;
$handle = fopen($path, 'wb');
$service->export('2026-11', $handle);
fclose($handle);
$sheet = IOFactory::createReader('Xlsx')->load($path)->getSheetByName('汇总');
$this->assertSame('示例公司2026年应付11月份快递、物流运费清单', (string) $sheet->getCell('C1')->getValue());
$this->assertSame('承运商', (string) $sheet->getCell('H3')->getValue());
$this->assertSame('旧账快递', (string) $sheet->getCell('H5')->getValue());
$this->assertEquals(-3000, $sheet->getCell('R5')->getValue());
$this->assertSame('合计', (string) $sheet->getCell('H6')->getValue());
}
public function test_ledger_history_import_marks_duplicates(): void
{
$this->seedShipping();
$store = app(CourierBillStore::class);
$store->saveGroup(null, ['name' => '河北中通-江三/小件', 'express_names' => ['河北中通-江三'], 'summary_carrier' => null, 'owner' => null, 'keywords' => null]);
$path = $this->workbook(['台账' => [['分组', '单号', '结算月份', '金额'], ['河北中通-江三/小件', 'ZT001', '2026年9月', 10], ['不存在', 'X1', '2026-09', 1]]]);
$result = $store->importLedger($path, 'xlsx');
$this->assertSame(1, $result['inserted']);
$this->assertSame(['不存在'], $result['unknown_groups']);
$ids = $store->upload([$this->upload('河北中通-江三.xlsx', [['运单号', '运费'], ['ZT001', 10]])], '2026-10', [], 'tester');
$statementId = (int) $store->db()->table('courier_bill_files')->where('id', $ids[0])->value('statement_id');
$this->assertSame(Category::DUPLICATE, $store->db()->table('courier_bill_lines')->where('statement_id', $statementId)->value('category'));
}
public function test_groups_can_be_generated_from_summary_imported_and_completed_from_shipping_names(): void
{
$store = app(CourierBillStore::class);
$result = $store->groupsFromSummary([
['cells' => ['H' => '河北中通-江三', 'E' => '承运', 'D' => '张三', 'K' => 100.0]],
['cells' => ['H' => '常州圆通其他', 'E' => '承运', 'D' => '/']],
['cells' => ['H' => '常州圆通-上楼', 'E' => '承运', 'D' => '李四']],
['cells' => ['H' => '旧账快递', 'E' => '停运', 'D' => '不合作', 'I' => -5.0]],
['cells' => ['H' => '停运但有账单', 'E' => '停运', 'K' => 8.0]],
]);
$this->assertSame(['created' => 4, 'skipped' => 1], $result);
$groups = collect($store->groups())->keyBy('name');
$this->assertSame(['河北中通-江三'], $groups['河北中通-江三']->express_names);
$this->assertSame('河北中通-江三', $groups['河北中通-江三']->summary_carrier);
$this->assertSame('张三', $groups['河北中通-江三']->owner);
$this->assertNull($groups['常州圆通其他']->owner);
// 再生成一次不会重复建
$this->assertSame(0, $store->groupsFromSummary([['cells' => ['H' => '河北中通-江三', 'E' => '承运']]])['created']);
// 文件名识别:取最长命中;「河北中通-江三」的「河北中通」也能认
$all = $store->groups();
$this->assertSame('常州圆通其他', CourierBillStore::identify('常州圆通其他10月账单.xlsx', $all)?->name);
$this->assertSame('常州圆通-上楼', CourierBillStore::identify('常州圆通-上楼 10月.xlsx', $all)?->name);
$this->assertNull(CourierBillStore::identify('常州圆通10月.xlsx', $all));
$this->assertSame('河北中通-江三', CourierBillStore::identify('河北中通10月对账单.xlsx', $all)?->name);
// 未归组的快递名称1 + 推荐
$unassigned = $store->unassignedExpressNames(['河北中通-江三' => 10, '河北中通小件-江三' => 30, '完全不一样' => 1]);
$this->assertSame(['河北中通小件-江三', '完全不一样'], array_column($unassigned, 'name'));
$this->assertSame((int) $groups['河北中通-江三']->id, $unassigned[0]['suggest']);
$this->assertNull($unassigned[1]['suggest']);
$store->addExpressName((int) $groups['河北中通-江三']->id, '河北中通小件-江三');
$this->assertSame(['河北中通-江三', '河北中通小件-江三'], collect($store->groups())->firstWhere('name', '河北中通-江三')->express_names);
// 导入:按分组名称新增或覆盖
$path = $this->workbook(['分组' => [
['分组名称', '快递名称1', '归到承运商', '合并账单', '负责人', '文件名关键字', '单号列', '运费列', '重量列'],
['北京韵达', '北京韵达-乐鑫达、北京韵达-永超', '北京韵达-乐鑫达', '北京韵达合并', '王五', '韵达', '', '运费', ''],
['常州圆通其他', '常州圆通其他', '', '', '初始负责人', '', '', '', ''],
['常州圆通其他', '常州圆通其他', '', '', '赵六', '', '', '', ''],
]]);
$this->assertSame(['created' => 1, 'updated' => 2, 'skipped' => 0], $store->importGroups($path, 'xlsx'));
$groups = collect($store->groups())->keyBy('name');
$this->assertSame(['北京韵达-乐鑫达', '北京韵达-永超'], $groups['北京韵达']->express_names);
$this->assertSame('运费', $groups['北京韵达']->amount_header);
$this->assertSame('北京韵达合并', $groups['北京韵达']->bundle);
$this->assertSame('赵六', $groups['常州圆通其他']->owner);
// 有对账单的分组不能删
$store->deleteGroup((int) $groups['常州圆通-上楼']->id);
$store->db()->table('courier_bill_statements')->insert(['group_id' => $groups['北京韵达']->id, 'bill_month' => '2026-10', 'status' => 'open']);
$this->expectException(\RuntimeException::class);
$store->deleteGroup((int) $groups['北京韵达']->id);
}
public function test_group_with_historical_ledger_cannot_be_deleted(): void
{
$store = app(CourierBillStore::class);
$id = $store->saveGroup(null, ['name' => '已导入历史台账', 'express_names' => ['快递']]);
$store->db()->table('courier_bill_ledger')->insert(['group_id' => $id, 'waybill_no' => 'YT001', 'settle_month' => '2026-10']);
$this->expectExceptionMessage('这个分组关联了结算台账或账单文件,不能删除。');
$store->deleteGroup($id);
}
public function test_combined_bill_is_split_to_groups_of_the_same_bundle(): void
{
$this->seedShipping();
$ship = app(\App\Support\CourierBills\ShippingLookup::class)->connection();
$ship->table('jst_oms_shipping')->insert(['express_no' => 'XX001', 'express_name1' => '别家快递', 'ship_time' => '2026-10-06 10:00:00', 'source_id' => 50]);
$ship->table('jst_oms_shipping_freight')->insert(['source_id' => 50, 'freight' => 4, 'status' => 'OK', 'charge_weight' => 1]);
$store = app(CourierBillStore::class);
$hebei = $store->saveGroup(null, ['name' => '河北中通-江三', 'express_names' => ['河北中通-江三', '河北中通小件-江三'], 'bundle' => '河北中通-江三+霸州百世快运-雅柏']);
$bazhou = $store->saveGroup(null, ['name' => '霸州百世快运-雅柏', 'express_names' => ['霸州百世快运-雅柏'], 'bundle' => '河北中通-江三+霸州百世快运-雅柏']);
$other = $store->saveGroup(null, ['name' => '别家快递', 'express_names' => ['别家快递'], 'bundle' => '别家']);
$ids = $store->upload([$this->upload('河北中通-江三10月账单.xlsx', [['运单号', '运费'], ['ZT001', 10], ['ZT005', 7], ['ZT004', 6], ['XX001', 4], ['ZT010', 10.004]])], '2026-10', [], 'tester');
$file = $store->db()->table('courier_bill_files')->find($ids[0]);
$this->assertSame('合并账单已拆分:河北中通-江三 4 行,霸州百世快运-雅柏 1 行;另有 1 行属于「别家快递」,没拆入(是同一张账单的话,把它加进合并账单后点「重新匹配」)', $file->message);
$statements = $store->db()->table('courier_bill_statements')->pluck('id', 'group_id');
$lines = fn (int $group) => $store->db()->table('courier_bill_lines')->where('statement_id', $statements[$group])->orderBy('id')
->get()->map(fn ($l) => [$l->waybill_no, $l->category])->all();
$this->assertSame([['ZT001', Category::MATCH], ['ZT004', Category::UNMATCHED], ['XX001', Category::MISMATCH], ['ZT010', Category::UNMATCHED]], $lines($hebei));
$this->assertSame([['ZT005', Category::MATCH]], $lines($bazhou));
$this->assertFalse(isset($statements[$other]));
$this->assertEqualsCanonicalizing([(int) $statements[$hebei], (int) $statements[$bazhou]], $store->statementsOfFiles([$ids[0]]));
// 导出:同一张账单的几家一起导出,汇总页每家一个小汇总,明细末列注明对账分组
$this->assertSame([(int) $statements[$bazhou], (int) $statements[$hebei]], app(StatementExporter::class)->related((int) $statements[$bazhou]));
$path = tempnam(sys_get_temp_dir(), 'bill_export_');
$this->temp[] = $path;
$handle = fopen($path, 'wb');
app(StatementExporter::class)->export((int) $statements[$bazhou], $handle);
fclose($handle);
$book = IOFactory::createReader('Xlsx')->load($path);
$summary = array_map(fn ($r) => (string) $r[0], $book->getSheetByName('汇总')->rangeToArray('A1:A12'));
$this->assertSame('霸州百世快运-雅柏 2026-10', $summary[0]);
$this->assertContains('河北中通-江三 2026-10', $summary);
$recon = $book->getSheetByName('对账');
$header = $recon->rangeToArray('A1:CZ1')[0];
$this->assertSame(['运单号', '运费'], array_slice($header, 0, 2));
$groupColumn = array_search('对账分组', $header, true);
$this->assertNotFalse($groupColumn);
$this->assertEqualsCanonicalizing(['霸州百世快运-雅柏', '河北中通-江三'], [(string) $recon->getCell([$groupColumn + 1, 2])->getValue(), (string) $recon->getCell([$groupColumn + 1, 3])->getValue()]);
// 运费表是原始账单原样:表头和 5 行数据都在,不拆、不加列
$freight = $book->getSheetByName('运费');
$this->assertSame(['运单号', '运费', null], $freight->rangeToArray('A1:C1')[0]);
$this->assertSame(6, $freight->getHighestDataRow());
$this->assertSame('XX001', (string) $freight->getCell('A5')->getValue());
$book->disconnectWorksheets();
// 手动多选分组:别的主体也能拆
// 快递运费带 3 位小数时按原值存,合计不逐行四舍五入
$this->assertSame(10.004, (float) $store->db()->table('courier_bill_lines')->where('waybill_no', 'ZT010')->value('bill_amount'));
$ids = $store->upload([$this->upload('合并.xlsx', [['运单号', '运费'], ['ZT002', 12], ['XX001', 4]])], '2026-11', [$hebei, $other], 'tester');
$this->assertStringContainsString('别家快递 1 行', (string) $store->db()->table('courier_bill_files')->where('id', $ids[0])->value('message'));
// 删除文件:两张对账单里的行都删掉
$store->deleteFile((int) $file->id);
$this->assertSame(0, $store->db()->table('courier_bill_lines')->where('file_id', $file->id)->count());
}
public function test_courier_added_to_a_bundle_later_is_flagged_then_split_by_rematch(): void
{
$this->seedShipping();
$ship = app(\App\Support\CourierBills\ShippingLookup::class)->connection();
$ship->table('jst_oms_shipping')->insert(['express_no' => 'NEW001', 'express_name1' => '新快递', 'ship_time' => '2026-10-06 10:00:00', 'source_id' => 60]);
$ship->table('jst_oms_shipping_freight')->insert(['source_id' => 60, 'freight' => 3, 'status' => 'OK', 'charge_weight' => 1]);
$store = app(CourierBillStore::class);
$hebei = $store->saveGroup(null, ['name' => '河北中通-江三', 'express_names' => ['河北中通-江三'], 'bundle' => '河北合并']);
$bazhou = $store->saveGroup(null, ['name' => '霸州百世快运-雅柏', 'express_names' => ['霸州百世快运-雅柏']]);
// 霸州还没加进合并账单;「新快递」连分组都没有
$ids = $store->upload([$this->upload('河北中通-江三11月.xlsx', [['运单号', '运费'], ['ZT001', 10], ['ZT005', 7], ['NEW001', 3]])], '2026-10', [], 'tester');
$file = $store->db()->table('courier_bill_files')->find($ids[0]);
$this->assertSame('另有 1 行属于「霸州百世快运-雅柏」,没拆入(是同一张账单的话,把它加进合并账单后点「重新匹配」);1 行的快递名称1「新快递」还没建分组', $file->message);
$hebeiStatement = (int) $file->statement_id;
$this->assertSame(3, $store->db()->table('courier_bill_lines')->where('statement_id', $hebeiStatement)->count());
// 把霸州加进合并账单、给新快递建分组并加进来,点重新匹配
$store->saveGroup($bazhou, ['name' => '霸州百世快运-雅柏', 'express_names' => ['霸州百世快运-雅柏'], 'bundle' => '河北合并']);
$new = $store->saveGroup(null, ['name' => '新快递', 'express_names' => ['新快递'], 'bundle' => '河北合并']);
$done = $store->rematch($hebeiStatement);
$this->assertCount(3, $done);
$statements = $store->db()->table('courier_bill_statements')->pluck('id', 'group_id');
$waybills = fn (int $group) => $store->db()->table('courier_bill_lines')->where('statement_id', $statements[$group])->pluck('waybill_no')->all();
$this->assertSame(['ZT001'], $waybills($hebei));
$this->assertSame(['ZT005'], $waybills($bazhou));
$this->assertSame(['NEW001'], $waybills($new));
$this->assertSame(Category::MATCH, $store->db()->table('courier_bill_lines')->where('waybill_no', 'ZT005')->value('category'));
$this->assertSame('合并账单已拆分:河北中通-江三 1 行,霸州百世快运-雅柏 1 行,新快递 1 行', $store->db()->table('courier_bill_files')->where('id', $file->id)->value('message'));
// 再把新快递移出合并账单:重新匹配会把它收回主分组,原对账单清空
$store->saveGroup($new, ['name' => '新快递', 'express_names' => ['新快递']]);
$store->rematch($hebeiStatement);
$this->assertSame(['ZT001', 'NEW001'], $waybills($hebei));
$this->assertSame(0, (int) $store->db()->table('courier_bill_statements')->where('id', $statements[$new])->value('line_count'));
$this->assertSame(0, $store->db()->table('courier_bill_unprovided')->where('statement_id', $statements[$new])->count());
// 新目标已确认时,整个重拆回滚,已拆往霸州的行保留原归属。
$store->confirm((int) $statements[$new], 'tester');
$store->saveGroup($new, ['name' => '新快递', 'express_names' => ['新快递'], 'bundle' => '河北合并']);
$store->saveGroup($bazhou, ['name' => '霸州百世快运-雅柏', 'express_names' => ['霸州百世快运-雅柏']]);
try {
$store->rematch($hebeiStatement);
$this->fail('已确认的目标对账单应阻止重拆。');
} catch (\RuntimeException $error) {
$this->assertStringContainsString('本月已确认结算', $error->getMessage());
}
$this->assertSame(['ZT005'], $waybills($bazhou));
$this->assertSame(['ZT001', 'NEW001'], $waybills($hebei));
}
public function test_month_express_names_counts_shipping_rows(): void
{
$this->seedShipping();
$counts = app(\App\Support\CourierBills\ShippingLookup::class)->monthExpressNames('2026-10');
$this->assertSame(['河北中通-江三' => 6, '霸州百世快运-雅柏' => 1], array_intersect_key($counts, ['河北中通-江三' => 1, '霸州百世快运-雅柏' => 1]));
}
public function test_related_export_follows_shared_files_and_bundles_only_in_the_same_month(): void
{
$db = CourierBillMatcher::db();
$store = app(CourierBillStore::class);
$a = $store->saveGroup(null, ['name' => 'A', 'express_names' => ['A']]);
$b = $store->saveGroup(null, ['name' => 'B', 'express_names' => ['B'], 'bundle' => '合并']);
$c = $store->saveGroup(null, ['name' => 'C', 'express_names' => ['C'], 'bundle' => '合并']);
$ids = [];
foreach ([[$a, '2026-10'], [$b, '2026-10'], [$c, '2026-10'], [$c, '2026-11'], [$a, '2026-11']] as [$group, $month]) {
$ids[] = $db->table('courier_bill_statements')->insertGetId(['group_id' => $group, 'bill_month' => $month, 'line_count' => 1]);
}
foreach ([$ids[0], $ids[1]] as $id) {
$db->table('courier_bill_lines')->insert(['statement_id' => $id, 'file_id' => 1, 'sheet' => '明细', 'row_no' => 2, 'waybill_no' => 'WB' . $id, 'raw' => '[]']);
}
$exporter = app(StatementExporter::class);
$this->assertSame([$ids[0], $ids[1], $ids[2]], $exporter->related($ids[0]));
$this->assertEqualsCanonicalizing([$ids[0], $ids[1], $ids[2]], $exporter->related($ids[2]));
$this->assertSame([$ids[3]], $exporter->related($ids[3]));
$this->assertSame([$ids[4]], $exporter->related($ids[4]));
}
public function test_original_export_keeps_blank_rows_text_and_precise_amounts_with_duplicate_long_sheet_names(): void
{
$store = app(CourierBillStore::class);
$group = $store->saveGroup(null, ['name' => '精度测试', 'express_names' => ['测试快递']]);
$sheetName = str_repeat('明细', 15);
$path = $this->workbook([$sheetName => [
[' 原始账单 '], [], ['运单号', '运费', '原始编码'],
['00012345678901234567', 10.004, '1E5'], ['ZT002', 20.408, '=1+1'], ['合计', 30.412],
], '附加费' => [['运单号', '费用金额'], ['ZT002', 99]]]);
$files = $store->upload([new UploadedFile($path, 'first.xlsx', null, null, true), new UploadedFile($path, 'second.xlsx', null, null, true)], '2026-10', [$group], 'tester');
$id = (int) $store->db()->table('courier_bill_files')->where('id', $files[0])->value('statement_id');
$this->assertSame(4, $store->db()->table('courier_bill_lines')->count());
$this->assertEquals(60.824, $store->db()->table('courier_bill_summary_items')->where('statement_id', $id)->sum('bill_amount'));
$output = tempnam(sys_get_temp_dir(), 'bill_precise_');
$this->temp[] = $output;
$handle = fopen($output, 'wb');
app(StatementExporter::class)->export($id, $handle);
fclose($handle);
$book = IOFactory::createReader('Xlsx')->load($output);
$names = array_values(array_filter($book->getSheetNames(), fn ($name) => str_starts_with($name, '运费-')));
$this->assertCount(2, $names);
$this->assertNotSame($names[0], $names[1]);
foreach ($names as $name) {
$this->assertLessThanOrEqual(31, mb_strlen($name));
$sheet = $book->getSheetByName($name);
$this->assertSame(6, $sheet->getHighestDataRow());
$this->assertSame(' 原始账单 ', (string) $sheet->getCell('A1')->getValue());
$this->assertNull($sheet->getCell('A2')->getValue());
$this->assertSame('运单号', (string) $sheet->getCell('A3')->getValue());
$this->assertSame('00012345678901234567', (string) $sheet->getCell('A4')->getValue());
$this->assertSame('1E5', (string) $sheet->getCell('C4')->getValue());
$this->assertSame('=1+1', (string) $sheet->getCell('C5')->getValue());
$this->assertNotSame(DataType::TYPE_FORMULA, $sheet->getCell('C5')->getDataType());
$this->assertEquals(10.004, $sheet->getCell('B4')->getValue());
$this->assertEquals(30.412, $sheet->getCell('B6')->getValue());
}
$summary = $book->getSheetByName('汇总');
$this->assertEquals(60.824, $summary->getCell('B' . $summary->getHighestDataRow())->getValue());
$book->disconnectWorksheets();
Storage::disk('local')->delete($store->db()->table('courier_bill_files')->where('id', $files[0])->value('stored_path'));
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('原始账单文件缺失');
$handle = fopen($output, 'wb');
try {
app(StatementExporter::class)->export($id, $handle);
} finally {
fclose($handle);
}
}
public function test_xls_and_csv_original_values_are_read_without_trimming_or_numeric_coercion(): void
{
$csv = tempnam(sys_get_temp_dir(), 'bill_values_');
$this->temp[] = $csv;
file_put_contents($csv, "运单号,运费,备注\n00123,10.004, 原样 \n");
$reader = app(BillWorkbookReader::class);
foreach ($reader->sheets($csv, 'csv', true) as $rows) {
$values = iterator_to_array($rows);
$this->assertSame(['00123', '10.004', ' 原样 '], $values[2]);
}
$book = new Spreadsheet();
$sheet = $book->getActiveSheet();
$sheet->getCell('A1')->setValueExplicit('00123', DataType::TYPE_STRING);
$sheet->setCellValue('B1', 10.004);
$sheet->setCellValue('C501', ' 原样 ');
$xls = tempnam(sys_get_temp_dir(), 'bill_xls_');
$this->temp[] = $xls;
(new \PhpOffice\PhpSpreadsheet\Writer\Xls($book))->save($xls);
$book->disconnectWorksheets();
foreach ($reader->sheets($xls, 'xls', true) as $rows) {
$values = iterator_to_array($rows);
$this->assertSame('00123', $values[1][0]);
$this->assertEquals(10.004, $values[1][1]);
$this->assertSame(' 原样 ', $values[501][2]);
}
}
private function seedShipping(): void
{
$db = app(\App\Support\CourierBills\ShippingLookup::class)->connection();
$rows = [
// express_no, express_name1, ship_time, source_id
['ZT001', '河北中通-江三', '2026-10-05 10:00:00', 1],
['ZT002', '河北中通-江三', '2026-10-06 10:00:00', 2],
['ZT002', '河北中通-江三', '2026-10-06 10:00:00', 2],
['ZT003', '河北中通-江三', '2026-10-06 10:00:00', 3],
['ZT005', '霸州百世快运-雅柏', '2026-10-06 10:00:00', 5],
['ZT006', '河北中通-江三', '2026-09-28 10:00:00', 6],
['ZT007', '河北中通-江三', '2026-11-01 10:00:00', 7],
['ZT008', '河北中通-江三', '2026-10-07 10:00:00', 8],
['ZT009', '河北中通-江三', '2026-10-08 10:00:00', 9],
];
foreach ($rows as [$no, $name, $time, $source]) {
$db->table('jst_oms_shipping')->insert(['express_no' => $no, 'express_name1' => $name, 'ship_time' => $time,
'source_id' => $source, 'trade_no' => 'T' . $source, 'qty' => 1, 'barcode' => 'B' . $source]);
}
foreach ([[1, 10, 'OK'], [2, 11, 'OK'], [3, 5, 'OK'], [5, 7, 'OK'], [6, 6, 'OK'], [7, 9, 'OK'], [8, null, '无报价'], [9, 3, 'OK']] as [$source, $freight, $status]) {
$db->table('jst_oms_shipping_freight')->insert(['source_id' => $source, 'freight' => $freight, 'status' => $status,
'charge_weight' => 1, 'rate' => '1.5', 'first_price' => 3]);
}
$unshipped = app(\App\Support\UnshippedWaybills::class)->connection();
$unshipped->table('courier_unshipped_waybills')->insert(['source' => 'warehouse', 'waybill_no' => 'ZT003', 'evidence_no' => 'W1',
'evidence_time' => '2026-10-07 00:00:00']);
}
private function upload(string $name, array $rows): UploadedFile
{
$path = $this->workbook(['Sheet1' => $rows]);
return new UploadedFile($path, $name, null, null, true);
}
/** @param array<string,list<list<mixed>>> $sheets */
private function workbook(array $sheets): string
{
$book = new Spreadsheet();
$book->removeSheetByIndex(0);
foreach ($sheets as $name => $rows) {
$sheet = $book->createSheet();
$sheet->setTitle($name);
foreach ($rows as $r => $row) {
foreach ($row as $c => $value) {
if ($value === null) {
continue;
}
$cell = $sheet->getCell([$c + 1, $r + 1]);
is_string($value) ? $cell->setValueExplicit($value, DataType::TYPE_STRING) : $cell->setValue($value);
}
}
}
$path = tempnam(sys_get_temp_dir(), 'bill_xlsx_') . '.xlsx';
$this->temp[] = $path;
(new Xlsx($book))->save($path);
$book->disconnectWorksheets();
return $path;
}
}