CaiWuXiTong/tests/Feature/Business/CourierBillReconciliationTest.php

369 lines
21 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_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', null, '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', null, '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', null, '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', null, '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'));
}
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;
}
}