CaiWuXiTong/tests/Feature/Business/DropshipFreightTest.php

670 lines
49 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\Models\Auth\Permission;
use App\Support\CourierBills\BillWorkbookReader;
use App\Support\CourierBills\Category;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\ShippingLookup;
use App\Support\DropshipFreight\DropshipFreightStore;
use App\Support\DropshipFreight\DropshipExporter;
use App\Support\DropshipFreight\DropshipReconciler;
use App\Support\DropshipFreight\FactoryBillParser;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Tests\Feature\FeatureTestCase;
final class DropshipFreightTest extends FeatureTestCase
{
private const WAREHOUSE = '工厂-山东卿德客代发仓';
public function test_factory_bill_parser_reads_freight_sheets_only(): void
{
$path = $this->xlsx([
'运费+货款' => [
['卿德客10月对账'],
['快递单号', '内部订单号', '快递公司', '金额', '快递', '偏远'],
['773444000001', '1', '卿德客申通', 15.1, 4, null],
['773444000001', '1', '卿德客申通', 11.0, 4, null], // 一单多件:运费相加
['773444000002', '2', '卿德客申通', 20.0, 5.5, 3], // 偏远列加进运费
['JDVB0001', '3', '京喜京东快递', 30.0, null, null], // 没运费:不算厂家开了运费
['合计', null, null, 76.1, 13.5, 3],
],
'对账' => [['快递单号', '运费', '结算运费'], ['773444000001', 8, 8]],
'记账' => [['物流单号', '记账金额'], ['773444000009', 30]],
'送货' => [['快递单号', '金额'], ['773444000003', 11]],
]);
$result = (new FactoryBillParser(new BillWorkbookReader()))->parse($path, 'xlsx');
$this->assertSame(['773444000001', '773444000002'], array_map('strval', array_keys($result['lines'])));
$this->assertEquals(8.0, $result['lines']['773444000001']['amount']);
$this->assertEquals(8.5, $result['lines']['773444000002']['amount']);
$read = array_values(array_filter($result['sheets'], static fn (array $s): bool => $s['read']));
$this->assertCount(1, $read);
$this->assertStringContainsString('运费列「快递」(加上「偏远」)', $read[0]['note']);
$skipped = collect($result['sheets'])->where('read', false)->pluck('note', 'sheet');
$this->assertStringContainsString('对账', $skipped['对账']);
$this->assertStringContainsString('记账', $skipped['记账']);
$this->assertStringContainsString('没有同时找到', $skipped['送货']);
}
public function test_generate_upload_reconcile_and_pages(): void
{
Storage::fake('local');
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->withExceptionHandling();
$db = CourierBillMatcher::db();
// 自有快递:快递账单对账分组里的快递名称1
$db->table('courier_bill_groups')->insert(['name' => '曹县韵达', 'express_names' => json_encode(['曹县韵达'], JSON_UNESCAPED_UNICODE),
'created_at' => now(), 'updated_at' => now()]);
$this->ship('773444000001', '卿德客申通', self::WAREHOUSE, '2026-10-03 09:00:00', 1, 8); // 一致
$this->ship('773444000002', '卿德客申通', self::WAREHOUSE, '2026-10-04 09:00:00', 2, 5); // 厂家多开
$this->ship('773444000003', '卿德客极兔', self::WAREHOUSE, '2026-10-05 09:00:00', 3, 6); // 厂家少开
$this->ship('773444000004', '卿德客申通', self::WAREHOUSE, '2026-10-06 09:00:00', 4, 7); // 厂家没开:不付
$this->ship('YD0001', '曹县韵达', self::WAREHOUSE, '2026-10-06 09:00:00', 5, 9); // 自有快递
$this->ship('773444000006', '卿德客申通', '简尚-新外贸仓主仓', '2026-10-06 09:00:00', 6, 9); // 别的仓
$this->ship('773444000007', '卿德客申通', self::WAREHOUSE, '2026-10-07 09:00:00', 7, null); // 未核算
$this->ship('773444000008', '卿德客申通', self::WAREHOUSE, '2026-09-30 09:00:00', 8, 4); // 前月补提供
$this->ship('773444000010', '卿德客申通', self::WAREHOUSE, '2026-11-02 09:00:00', 12, 4); // 跨月订单
$this->ship('JDVB0001', '京喜京东快递', self::WAREHOUSE, '2026-10-08 09:00:00', 9, 3);
$this->ship('JDVB0002', '京喜京东快递', '工厂-河北丽彪代发仓', '2026-10-08 09:00:00', 10, 3);
$this->ship('JDVB0003', '京喜京东快递', '简尚-新外贸仓主仓', '2026-10-08 09:00:00', 11, 3);
$this->ship('773444000020', '卿德客申通', self::WAREHOUSE, '2026-10-09 09:00:00', 13, 6); // 换单后的新单号:代发单
$this->ship('YD0020', '曹县韵达', self::WAREHOUSE, '2026-10-09 09:00:00', 14, 9); // 换单后的新单号:自有快递
$this->shipping()->table('jst_oms_shipping')->where('express_no', '773444000020')->update(['front_no' => 'OLD0000001']);
$this->shipping()->table('jst_oms_shipping')->where('express_no', 'YD0020')->update(['front_no' => 'OLD0000002']);
$this->shipping()->table('jst_oms_shipping')->where('source_id', '<=', 8)->update(['supplier_name' => '临沂卿德客']);
$section = 'courier-payables-final';
$page = fn (array $q = []) => route('business.pages.show', ['section' => $section, 'page' => 'dropship-freight-reconciliation', ...$q]);
$this->get(route('business.pages.show', ['section' => $section]))->assertOk()->assertSeeText('代发运费对账');
foreach (['overview', 'upload', 'factories'] as $view) {
$this->get($page(['df_view' => $view, 'month' => '2026-10']))->assertOk()->assertSee('data-cbr-root', false);
}
$this->post(route("business.$section.dropship-freight.generate"), ['month' => '2026-10'])->assertRedirect()->assertSessionHas('dropship_message');
$factory = $db->table('dropship_factories')->sole();
$this->assertSame('临沂卿德客', $factory->name);
$this->assertSame(self::WAREHOUSE, $factory->warehouse);
$this->assertSame('卿德客', $factory->keywords);
$bill = new UploadedFile($this->xlsx(['运费+货款' => [
['快递单号', '快递公司', '运费'],
['773444000001', '卿德客申通', 8], ['773444000002', '卿德客申通', 6], ['773444000003', '卿德客极兔', 5],
['YD0001', '曹县韵达', 9], ['773444000006', '卿德客申通', 9], ['773444000007', '卿德客申通', 4],
['773444000008', '卿德客申通', 4], ['999999999999', '卿德客申通', 3], ['773444000010', '卿德客申通', 4],
['OLD0000001', '卿德客申通', 6], ['OLD0000002', '卿德客申通', 5],
]]), '临沂卿德客10月.xlsx', null, null, true);
$this->post(route("business.$section.dropship-freight.upload"), ['month' => '2026-10', 'files' => [$bill]])
->assertRedirect()->assertSessionHas('dropship_message');
$file = $db->table('dropship_bill_files')->sole();
$this->assertSame('parsed', $file->status);
$this->assertSame((int) $factory->id, (int) $file->factory_id);
$this->assertSame(11, (int) $file->waybill_count);
$f = collect(app(DropshipFreightStore::class)->factories())->sole();
$result = app(DropshipReconciler::class)->factoryMonth($f, '2026-10');
$status = collect($result['rows'])->pluck('status', 'waybill')->all();
$expected = [
'773444000001' => Category::MATCH, '773444000002' => Category::DIFF, '773444000003' => Category::DIFF,
'773444000004' => Category::UNPROVIDED, 'YD0001' => Category::MISMATCH, '773444000006' => Category::MISMATCH,
'773444000007' => Category::UNCALCULATED, '773444000008' => Category::PRIOR, '773444000010' => Category::LATER,
'999999999999' => Category::UNMATCHED, 'OLD0000001' => Category::MATCH, 'OLD0000002' => Category::MISMATCH,
];
ksort($status);
ksort($expected);
$this->assertSame($expected, $status);
$s = $result['summary'];
$this->assertSame(11, $s['billed']);
$this->assertEquals(63, $s['bill']);
// 按我方核算:一致、运费有差、前月补提供、换单实际发出的代发单;跨月订单留到发货月
$this->assertEquals(8 + 5 + 6 + 4 + 6, $s['calc_settle']);
// 最终结算:厂家开得比核算少的(773444000003 厂家 5、核算 6)按厂家运费结
$this->assertEquals(8 + 5 + 5 + 4 + 6, $s['settle']);
$this->assertSame(1, $s['capped']);
$this->assertEquals(63 - 28, $s['diff']);
$under = collect($result['rows'])->firstWhere('waybill', '773444000003');
$this->assertEquals([5, 6, 5], [$under['bill'], $under['settle'], $under['final']]);
$over = collect($result['rows'])->firstWhere('waybill', '773444000002');
$this->assertEquals([6, 5, 5], [$over['bill'], $over['settle'], $over['final']]);
$swap = collect($result['rows'])->firstWhere('waybill', 'OLD0000001');
$this->assertStringContainsString('换单:实际发出 773444000020(卿德客申通)', $swap['note']);
$this->assertStringContainsString('自有快递「曹县韵达」', collect($result['rows'])->firstWhere('waybill', 'OLD0000002')['note']);
$this->assertArrayNotHasKey('773444000020', $status); // 新单号不再算「厂家未提供」
$this->assertSame([1, 1], [$s['over'], $s['under']]);
$prior = collect($result['rows'])->firstWhere('waybill', '773444000008');
$this->assertSame('前月补提供-9月', $prior['label']);
$own = collect($result['rows'])->firstWhere('waybill', 'YD0001');
$this->assertStringContainsString('自有快递', (string) $own['note']);
$this->assertNull($own['settle']);
$this->get($page(['df_view' => 'overview', 'month' => '2026-10']))->assertOk()->assertSeeText('临沂卿德客')->assertSeeText('28.00');
$this->get($page(['df_view' => 'factory', 'factory' => $factory->id, 'month' => '2026-10']))->assertOk()
->assertSeeText('一致但运费有差')->assertSeeText('773444000004')->assertSeeText('厂家未提供(不付)')->assertSeeText('匹配不到')
->assertSeeText('自有快递「曹县韵达」');
$this->get($page(['df_view' => 'factory', 'factory' => $factory->id, 'month' => '2026-10', 'status' => 'attention']))->assertOk()
->assertDontSeeText('773444000004');
$this->get(route("business.$section.dropship-freight.export", ['month' => '2026-10']))->assertOk();
// 导入这家 10 月手工做好的账单:只读汇总的样子(标题、表头、类目),导出汇总照它排
$manual = new UploadedFile($this->xlsx(['运费+货款' => [['快递单号', '运费'], ['1', 2]], '汇总' => [
['10月', '厂家金额', '简尚金额', '差异'], ['运费', 37923.5, 37612.5, 311], ['货款', 151323.6, 151323.6, 0], ['记账', null, -3645.9, 3645.9], ['未发出', 15, 0, 15],
['汇总', 189262.1, 185290.2, 3971.9],
]]), '卿德客10月手工.xlsx', null, null, true);
$this->post(route("business.$section.dropship-freight.import-summary-templates"), ['month' => '2026-10', 'files' => [$manual]])
->assertRedirect()->assertSessionHas('dropship_message');
$this->assertSame(['10月', '["运费","货款","记账","未发出"]', '汇总'], array_values((array) $db->table('dropship_summary_templates')
->where('factory_id', $factory->id)->where('bill_month', '2026-10')->first(['title', 'labels', 'total_label'])));
$november = app(DropshipFreightStore::class)->summaryTemplate($f, '2026-11');
$this->assertSame(['11月', ['运费', '货款', '记账', '未发出'], '2026-10'], [$november['title'], $november['labels'], $november['from']]);
// 小汇总不要「代发」「退货」:默认样子没有,手工汇总里带了也去掉
$this->assertSame(['运费', '记账'], \App\Support\DropshipFreight\DropshipSummaryTemplate::DEFAULT['labels']);
$this->assertSame(['运费', '货款', '记账'], \App\Support\DropshipFreight\DropshipSummaryTemplate::withoutDropped(
['labels' => ['运费', '货款', '代发', '记账', '10月退货']])['labels']);
$before = $db->table('dropship_bill_lines')->orderBy('id')->get()->toJson();
$filesBefore = $db->table('dropship_bill_files')->orderBy('id')->get()->toJson();
$export = $this->get(route("business.$section.dropship-freight.export", ['month' => '2026-10', 'factory' => $factory->id]))->assertOk();
$out = $export->baseResponse->getFile()->getPathname();
$book = \PhpOffice\PhpSpreadsheet\IOFactory::load($out);
$names = $book->getSheetNames();
$this->assertSame(['汇总', '厂家账单'], array_slice($names, 0, 2)); // 和手工版一样:汇总第一张,原账单叫「厂家账单」
$this->assertSame('卿德客申通', $book->getSheetByName('厂家账单')->getCell('B2')->getValue());
foreach (['汇总', '对账', '前月补提供-9月', '跨月订单-11月', '快递不符', '匹配不到', '厂家未提供', '说明'] as $sheet) {
$this->assertContains($sheet, $names);
}
$recon = $book->getSheetByName('对账')->toArray(null, false, false);
$this->assertSame(['快递单号', '快递公司', '运费', '称重重量', '首重', '面单', '快递单号'], array_slice($recon[0], 0, 7));
$row = collect($recon)->first(fn ($r) => $r[0] === '773444000002');
$this->assertSame('卿德客申通', $row[1]);
$this->assertEquals(6, $row[2]);
$this->assertSame('一致但运费有差', $row[count($row) - 2]);
// 核算运费后面是最终结算运费;运费差 = 厂家运费 − 最终结算运费
$head = $recon[0];
$at = array_search('核算运费', $head, true);
$this->assertSame('最终结算运费', $head[$at + 1]);
$under = collect($recon)->first(fn ($r) => $r[0] === '773444000003'); // 厂家 5、核算 6 → 按 5 结,运费差 0
$this->assertEquals([6, 5], [$under[$at], $under[$at + 1]]);
$this->assertEquals(0, $under[array_search('运费差', $head, true)]);
$this->assertEquals([5, 5, 1], [$row[$at], $row[$at + 1], $row[array_search('运费差', $head, true)]]); // 厂家 6、核算 5:多开 1
$swapRow = collect($recon)->first(fn ($r) => $r[0] === 'OLD0000001');
$this->assertSame('773444000020', $swapRow[6]);
$sheet = $book->getSheetByName('汇总');
$summary = $sheet->toArray(null, false, false);
$this->assertSame(['10月', '厂家金额', '简尚金额', '差异'], array_slice($summary[0], 0, 4));
// 厂家开了运费、这个月不付的按分类各加一行:原始 = 厂家开的,简尚 = 0,原始合计 = 厂家账单运费合计;上月手工汇总的「未发出」这个月没有,不留空行
$this->assertSame(['运费', '货款', '记账', '快递不符', '匹配不到', '跨月订单-11月', '汇总'], array_column(array_slice($summary, 1, 7), 0));
$this->assertEquals([33, 28], [$summary[1][1], $summary[1][2]]); // 运费:按我方结算的单厂家开 33,最终结算 28
$this->assertNull($summary[2][1]); // 货款先空着手工填
$this->assertEquals([[23, 0], [3, 0], [4, 0]], [array_slice($summary[4], 1, 2), array_slice($summary[5], 1, 2), array_slice($summary[6], 1, 2)]);
$this->assertSame('=SUM(B2:B7)', $sheet->getCell('B8')->getValue()); // 合计是公式,手工填了跟着算
$this->assertEquals(63, $sheet->getCell('B8')->getCalculatedValue());
// 页面小汇总和导出逐项一致,放在逐单明细上方,筛选/翻页不影响整月金额。
$detailUrl = $page(['df_view' => 'factory', 'factory' => $factory->id, 'month' => '2026-10']);
$summaryRows = array_map(static fn (array $r): array => [
(string) $r[0], $r[1] === null ? '' : number_format((float) $r[1], 2),
$r[2] === null ? '' : number_format((float) $r[2], 2),
$r[1] === null && $r[2] === null ? '' : number_format((float) $r[1] - (float) $r[2], 2),
], array_slice($summary, 1, 6));
$summaryRows[] = ['汇总', '63.00', '28.00', '35.00'];
foreach ([[], ['status' => 'attention'], ['q' => '773444000002'], ['page' => 2]] as $filter) {
$response = $this->get($detailUrl . '&' . http_build_query($filter))->assertOk();
$html = (string) $response->getContent();
$this->assertLessThan(strpos($html, '逐单核算明细'), strpos($html, 'data-df-bill-summary'));
$dom = new \DOMDocument();
@$dom->loadHTML('<?xml encoding="utf-8" ?>' . $html);
$xpath = new \DOMXPath($dom);
$actual = [];
foreach ($xpath->query('//*[@data-df-bill-summary]//tbody/tr | //*[@data-df-bill-summary]//tfoot/tr') as $tr) {
$actual[] = array_map(static fn ($cell): string => trim($cell->textContent), iterator_to_array($tr->getElementsByTagName('td')));
}
$this->assertSame($summaryRows, $actual);
}
$sheet->setCellValue('C4', -100);
$this->assertEquals(100, $sheet->getCell('D4')->getCalculatedValue());
$this->assertEquals(-72, $sheet->getCell('C8')->getCalculatedValue());
$this->assertSame(8, $sheet->getHighestDataRow()); // 汇总块下面不再附别的
$this->assertSame([3, 1], [count($book->getSheetByName('快递不符')->toArray()) - 1, count($book->getSheetByName('匹配不到')->toArray()) - 1]);
$book->disconnectWorksheets();
@unlink($out);
// 早期账单没有 raw 列也能直接导出;只读原文件,不重读入库,不改金额和文件状态。
$this->assertSame($before, $db->table('dropship_bill_lines')->orderBy('id')->get()->toJson());
$this->assertSame($filesBefore, $db->table('dropship_bill_files')->orderBy('id')->get()->toJson());
// 同一份账单再传:重复导入,不读入
$again = new UploadedFile($this->xlsx(['账单' => [['快递单号', '运费'], ['773444000001', 8], ['773444000002', 6]]]), '卿德客10月补.xlsx', null, null, true);
$this->post(route("business.$section.dropship-freight.upload"), ['month' => '2026-10', 'files' => [$again]])->assertRedirect();
$this->assertSame('failed', $db->table('dropship_bill_files')->orderByDesc('id')->value('status'));
// 下个月的账单又开了 10 月已开过的单
$next = new UploadedFile($this->xlsx(['账单' => [['快递单号', '运费'], ['773444000001', 8]]]), '卿德客11月.xlsx', null, null, true);
$this->post(route("business.$section.dropship-freight.upload"), ['month' => '2026-11', 'files' => [$next]])->assertRedirect();
$nov = app(DropshipReconciler::class)->factoryMonth($f, '2026-11');
$this->assertSame(Category::DUPLICATE, collect($nov['rows'])->firstWhere('waybill', '773444000001')['status']);
// 换单跨月:10 月账单开的是旧单号 OLD0000001(已换成 773444000020),11 月账单又开新单号 → 同一包裹,算重复
$swapNov = new UploadedFile($this->xlsx(['账单' => [['快递单号', '运费'], ['773444000020', 6]]]), '卿德客11月补.xlsx', null, null, true);
$this->post(route("business.$section.dropship-freight.upload"), ['month' => '2026-11', 'files' => [$swapNov]])->assertRedirect();
$nov = app(DropshipReconciler::class)->factoryMonth($f, '2026-11');
$row = collect($nov['rows'])->firstWhere('waybill', '773444000020');
$this->assertSame(Category::DUPLICATE, $row['status']);
$this->assertStringContainsString('OLD0000001', (string) $row['note']);
$this->assertNull($row['settle']);
// 认不出厂家的文件:待选厂家,选后读入
$unknown = new UploadedFile($this->xlsx(['账单' => [['快递单号', '运费'], ['773444000004', 7]]]), '某厂家12月.xlsx', null, null, true);
$this->post(route("business.$section.dropship-freight.upload"), ['month' => '2026-12', 'files' => [$unknown]])->assertRedirect();
$pending = $db->table('dropship_bill_files')->where('bill_month', '2026-12')->sole();
$this->assertSame('pending_factory', $pending->status);
$this->post(route("business.$section.dropship-freight.assign", ['file' => $pending->id]), ['factory_id' => $factory->id])->assertRedirect();
$this->assertSame('parsed', $db->table('dropship_bill_files')->where('id', $pending->id)->value('status'));
// 厂家设置:有账单不能删;删完账单再删
$this->post(route("business.$section.dropship-freight.save-factory"), ['id' => $factory->id, 'name' => '临沂卿德客', 'warehouse' => self::WAREHOUSE,
'keywords' => '卿德客,卿德客申通'])->assertRedirect();
$this->assertSame('卿德客,卿德客申通', $db->table('dropship_factories')->value('keywords'));
$this->post(route("business.$section.dropship-freight.delete-factory", ['factory' => $factory->id]))->assertSessionHasErrors('dropship');
foreach ($db->table('dropship_bill_files')->pluck('id') as $id) {
$this->post(route("business.$section.dropship-freight.delete-file", ['file' => $id]))->assertRedirect();
}
$this->assertSame(0, $db->table('dropship_bill_lines')->count());
$this->post(route("business.$section.dropship-freight.delete-factory", ['factory' => $factory->id]))->assertRedirect();
$this->assertSame(0, $db->table('dropship_factories')->count());
}
public function test_partial_duplicate_check_covers_every_waybill_of_a_large_bill(): void
{
Storage::fake('local');
$store = app(DropshipFreightStore::class);
$store->saveFactory(null, ['name' => '临沂卿德客', 'warehouse' => self::WAREHOUSE, 'keywords' => '卿德客']);
$first = new UploadedFile($this->xlsx(['账单' => [['快递单号', '运费'], ['773449999999', 5]]]), '卿德客10月.xlsx', null, null, true);
$store->upload([$first], '2026-10', 't');
$rows = [['快递单号', '运费']];
for ($i = 0; $i < 5001; $i++) {
$rows[] = [(string) (773440000000 + $i), 4];
}
$rows[] = ['773449999999', 5]; // 第 5,002 个单号和上一份重复
$id = $store->upload([new UploadedFile($this->xlsx(['账单' => $rows]), '卿德客10月补.xlsx', null, null, true)], '2026-10', 't')[0];
$file = $store->db()->table('dropship_bill_files')->find($id);
$this->assertSame('parsed', $file->status);
$this->assertSame(5001, (int) $file->waybill_count);
$this->assertStringContainsString('1 个单号本月别的账单文件里也有', (string) $file->message);
$this->assertSame(1, $store->db()->table('dropship_bill_lines')->where('waybill_no', '773449999999')->count());
}
public function test_single_export_preserves_original_workbook_and_first_source_row_without_changing_bills(): void
{
Storage::fake('local');
$store = app(DropshipFreightStore::class);
$id = $store->saveFactory(null, ['name' => '导出测试', 'warehouse' => self::WAREHOUSE, 'keywords' => '卿德客']);
$path = $this->xlsx([
'运费' => [['原始账单'], [], ['快递单号', '运费', '备注', '备注'],
['00012345678901234567', 4, ' 保留空格 ', '=1+1'], ['00012345678901234567', 6, '第二件', '00001']],
'汇总' => [['厂家自己的汇总']],
'对账' => [['厂家自己的对账']],
]);
$original = \PhpOffice\PhpSpreadsheet\IOFactory::load($path);
$sheet = $original->getSheetByName('运费');
$sheet->mergeCells('A1:D1');
$sheet->getStyle('A1')->getFont()->setBold(true)->setSize(18);
$sheet->setCellValue('E4', '=B4*2');
(new Xlsx($original))->save($path);
$original->disconnectWorksheets();
$file = $store->upload([new UploadedFile($path, '导出测试.xlsx', null, null, true)], '2026-10', 'tester')[0];
$db = $store->db();
// 模拟已核对的金额:导出取当前账单结果,不再次解析入库覆盖。
$db->table('dropship_bill_lines')->where('file_id', $file)->update(['amount' => 11]);
$before = $db->table('dropship_bill_lines')->get()->toJson();
$this->ship('00012345678901234567', '卿德客申通', self::WAREHOUSE, '2026-10-03 09:00:00', 1, 10);
$out = tempnam(sys_get_temp_dir(), 'dropship_export_');
$handle = fopen($out, 'wb');
try {
app(DropshipExporter::class)->export(collect($store->factories())->firstWhere('id', $id), '2026-10', $handle);
} finally {
fclose($handle);
}
$book = \PhpOffice\PhpSpreadsheet\IOFactory::load($out);
// 汇总第一张;原文件几张表都叫「厂家账单-原表名」,所以和系统的汇总、对账不再撞名
$this->assertSame(['汇总', '厂家账单-运费', '厂家账单-汇总', '厂家账单-对账', '对账'], array_slice($book->getSheetNames(), 0, 5));
$this->assertTrue($book->getSheetByName('厂家账单-运费')->getStyle('A1')->getFont()->getBold());
$this->assertSame(['A1:D1' => 'A1:D1'], $book->getSheetByName('厂家账单-运费')->getMergeCells());
$this->assertSame('=B4*2', $book->getSheetByName('厂家账单-运费')->getCell('E4')->getValue());
$this->assertSame('厂家自己的汇总', $book->getSheetByName('厂家账单-汇总')->getCell('A1')->getValue());
$this->assertSame(['10月导出测试', '原始', '简尚核对', '差异'], array_slice($book->getSheetByName('汇总')->toArray(null, false, false)[0], 0, 4));
$data = $book->getSheetByName('对账')->toArray(null, false, false);
$this->assertSame(['快递单号', '运费', '备注', '备注(2)'], array_slice($data[0], 0, 4));
$this->assertSame(['00012345678901234567', 4, ' 保留空格 ', '=1+1'], array_slice($data[1], 0, 4));
$this->assertEquals(11, $data[1][count($data[0]) - 4]);
$this->assertSame(['厂家运费(这一单合计)', '结算运费', '分类', '说明'], array_slice($data[0], -4));
$this->assertContains($book->getSheetByName('对账')->getCell('D2')->getDataType(), [
\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING, \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_INLINE,
]);
$book->disconnectWorksheets();
$sourceZip = new \ZipArchive();
$resultZip = new \ZipArchive();
$sourceZip->open($path);
$resultZip->open($out);
// 原表一个字节都不改,只去掉「选中」标记(打开时停在汇总)
$this->assertSame(str_replace(' tabSelected="1"', '', $sourceZip->getFromName('xl/worksheets/sheet1.xml')), $resultZip->getFromName('xl/worksheets/sheet1.xml'));
$sourceZip->close();
$resultZip->close();
$this->assertSame($before, $db->table('dropship_bill_lines')->get()->toJson());
@unlink($path);
@unlink($out);
}
public function test_single_export_supports_csv_and_multiple_original_files(): void
{
Storage::fake('local');
$store = app(DropshipFreightStore::class);
$id = $store->saveFactory(null, ['name' => '导出测试', 'warehouse' => self::WAREHOUSE, 'keywords' => '卿德客']);
$store->upload([
UploadedFile::fake()->createWithContent('导出测试.csv', "快递单号,运费,备注\nCSV001,4,00001\n"),
new UploadedFile($this->xlsx(['明细' => [['快递单号', '运费', '额外'], ['XLSX001', 7, ' 原样 ']]]), '导出测试.xlsx', null, null, true),
], '2026-10', 'tester');
$out = tempnam(sys_get_temp_dir(), 'dropship_export_');
$handle = fopen($out, 'wb');
try {
app(DropshipExporter::class)->export(collect($store->factories())->firstWhere('id', $id), '2026-10', $handle);
} finally {
fclose($handle);
}
$book = \PhpOffice\PhpSpreadsheet\IOFactory::load($out);
$this->assertSame(['汇总', '厂家账单', '厂家账单2'], array_slice($book->getSheetNames(), 0, 3)); // xlsx 原样做底叫「厂家账单」,csv 按值复制
$this->assertSame(' 原样 ', (string) $book->getSheetByName('厂家账单')->getCell('C2')->getValue());
$this->assertSame('CSV001', (string) $book->getSheetByName('厂家账单2')->getCell('A2')->getValue());
$data = $book->getSheetByName('匹配不到')->toArray(null, false, false);
$this->assertSame(['快递单号', '运费', '备注', '额外'], array_slice($data[0], 0, 4));
$csv = collect(array_slice($data, 1))->first(fn ($r) => $r[0] === 'CSV001');
$xlsx = collect(array_slice($data, 1))->first(fn ($r) => $r[0] === 'XLSX001');
$this->assertSame('00001', $csv[2]);
$this->assertSame(' 原样 ', $xlsx[3]);
$book->disconnectWorksheets();
@unlink($out);
}
public function test_missing_original_file_returns_an_error_instead_of_a_partial_download(): void
{
Storage::fake('local');
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->withExceptionHandling();
$store = app(DropshipFreightStore::class);
$id = $store->saveFactory(null, ['name' => '导出测试', 'warehouse' => self::WAREHOUSE, 'keywords' => '卿德客']);
$file = $store->upload([UploadedFile::fake()->createWithContent('导出测试.csv', "快递单号,运费\nCSV001,4\n")], '2026-10', 'tester')[0];
Storage::disk('local')->delete($store->db()->table('dropship_bill_files')->where('id', $file)->value('stored_path'));
$page = route('business.pages.show', ['section' => 'courier-payables-final', 'page' => 'dropship-freight-reconciliation']);
$this->from($page)->get(route('business.courier-payables-final.dropship-freight.export', ['month' => '2026-10', 'factory' => $id]))
->assertRedirect($page)->assertSessionHasErrors('dropship');
$this->assertSame(1, $store->db()->table('dropship_bill_lines')->count());
$this->assertSame('parsed', $store->db()->table('dropship_bill_files')->value('status'));
}
public function test_overview_fee_columns_fill_from_the_surcharge_sheet_and_can_be_edited(): void
{
Storage::fake('local');
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->withExceptionHandling();
$db = CourierBillMatcher::db();
$id = $db->table('dropship_factories')->insertGetId(['name' => '临沂卿德客', 'warehouse' => self::WAREHOUSE, 'keywords' => '卿德客',
'created_at' => now(), 'updated_at' => now()]);
$this->ship('773444000001', '卿德客申通', self::WAREHOUSE, '2026-11-03 09:00:00', 1, 8);
$this->ship('773444000002', '卿德客申通', self::WAREHOUSE, '2026-11-04 09:00:00', 2, 6); // 厂家开 5,比核算少,按 5 结
$h = ['单号', '省', '重量', '运费', '快递名称', '面单', '费率'];
$path = $this->xlsx(['账单' => [$h, ['773444000001', '', 2, 8], ['773444000002', '', 1, 5]],
'附加费' => [['快递单号', '附加费金额', '附加费类型'], ['773444000001', 3, '退回费'], ['773444000002', 2, '拦截费'], ['773444000002', 1.5, '上楼费']]]);
app(DropshipFreightStore::class)->uploadFor('卿德客11月.xlsx', $path, '2026-11', $id, '测试');
// 自算来自结算表;厂家提供金额不能当作系统已核对金额。
BillSurchargeMatchingTest::createSettlementTable();
foreach([['773444000001','退回费',3],['773444000002','拦截费',2],['773444000002','上楼费',1.5]] as [$wb,$type,$amount]){
$db->table('courier_surcharge_settlement_rows')->insert(['waybill'=>$wb,'surcharge_type'=>$type,
'courier_name'=>'卿德客申通','settlement_amount'=>$amount,'settlement_status'=>'已计算','shipped_at'=>'2026-11-01 00:00:00']);
}
app(\App\Support\CourierBills\SurchargeSettlementMatcher::class)->dropship($id,'2026-11');
$fees = app(\App\Support\DropshipFreight\DropshipFees::class);
$row = $fees->rows('2026-11', [$id => 13.0], (int) $this->company->id)[$id];
$this->assertEquals(['freight' => 13, 'returned' => 3, 'intercept' => 2], array_filter($row['values']));
$this->assertSame(['上楼费' => 1.5], $row['other']);
$this->assertEquals(18, $row['total']);
$this->assertSame('booking', \App\Support\DropshipFreight\DropshipFees::classify('快递记账'));
$this->assertSame('extra_booking', \App\Support\DropshipFreight\DropshipFees::classify('补记账'));
$this->assertSame('readdress', \App\Support\DropshipFreight\DropshipFees::classify('改址费'));
$section = 'courier-payables-final';
$page = route('business.pages.show', ['section' => $section, 'page' => 'dropship-freight-reconciliation', 'df_view' => 'overview', 'month' => '2026-11']);
$this->get($page)->assertOk()->assertSeeTextInOrder(['厂家', '快递运费', '快递记账', '补运费', '补记账', '退回费', '拦截费', '改地址费', '翻箱费', '超长费', '合计运费', '备注', '代发仓'])
->assertSeeText('18.00')->assertSeeText('上楼费');
// 财务改:快递记账 4(扣款)、补记账 1、退回费改成 2.5,备注
$save = route("business.$section.dropship-freight.save-fees", ['factory' => $id]);
$this->post($save, ['month' => '2026-11', 'fees' => ['booking' => '-4', 'extra_booking' => '1', 'returned' => '2.5'], 'note' => '已和厂家核对'])
->assertSessionHas('dropship_message');
$row = $fees->rows('2026-11', [$id => 13.0], (int) $this->company->id)[$id];
$this->assertEquals(13 + 2.5 + 2 - 4 + 1, $row['total']);
$this->assertTrue($row['manual']['booking']);
$this->assertEquals(3, $row['auto']['returned']);
$this->get($page)->assertOk()->assertSeeText('-4.00')->assertSeeText('14.50')->assertSeeText('已和厂家核对');
// 汇总导出使用页面费用口径:手工调整、扣款负数、未归类费用说明和合计均一致。
$overview = $this->get($page)->assertOk()->assertSee('data-df-export-summary', false)->assertSeeText('导出厂家汇总');
$download = $this->get(route("business.$section.dropship-freight.export", ['month' => '2026-11', 'summary' => 1]))->assertOk();
$summaryPath = tempnam(sys_get_temp_dir(), 'dropship_summary_');
file_put_contents($summaryPath, $download->streamedContent());
try {
$summaryBook = \PhpOffice\PhpSpreadsheet\IOFactory::load($summaryPath);
$this->assertSame(['各厂家汇总'], $summaryBook->getSheetNames());
$grid = $summaryBook->getActiveSheet()->toArray(null, false, false);
$dom = new \DOMDocument();
@$dom->loadHTML('<?xml encoding="UTF-8">' . $overview->getContent());
$xpath = new \DOMXPath($dom);
$headers = [];
foreach ($xpath->query('//section[@aria-label="各厂家汇总"]//thead//th') as $cell) $headers[] = trim($cell->textContent);
array_pop($headers); // 页面操作按钮不作为数据列导出。
$this->assertSame($headers, $grid[0]);
$this->assertEquals(['临沂卿德客', 13, -4, null, 1, 2.5, 2, null, null, null, 14.5,
"已和厂家核对\n未归类附加费(不计入合计):上楼费 1.50", self::WAREHOUSE, '卿德客',
2, 13, 13, 0, 0, 1, 0, 0, '未核完'], $grid[1]);
$this->assertEquals(['合计', 13, -4, null, 1, 2.5, 2, null, null, null, 14.5], array_slice($grid[2], 0, 11));
$this->assertCount(3, $grid);
$summaryBook->disconnectWorksheets();
// 月份沿用页面选择;无账单月份只导出表头,不混入本月数据。
$empty = $this->get(route("business.$section.dropship-freight.export", ['month' => '2026-12', 'summary' => 1]))->assertOk();
file_put_contents($summaryPath, $empty->streamedContent());
$emptyBook = \PhpOffice\PhpSpreadsheet\IOFactory::load($summaryPath);
$this->assertSame(1, $emptyBook->getActiveSheet()->getHighestDataRow());
$emptyBook->disconnectWorksheets();
} finally { @unlink($summaryPath); }
// 清空回到自动值
$this->post($save, ['month' => '2026-11', 'fees' => ['booking' => '', 'returned' => ''], 'note' => ''])->assertSessionHas('dropship_message');
$this->assertEquals(18, $fees->rows('2026-11', [$id => 13.0], (int) $this->company->id)[$id]['total']);
$this->post($save, ['month' => '2026-11', 'fees' => ['booking' => 'abc']])->assertSessionHasErrors('fees.booking');
// 页面上的快递运费 = 最终结算运费
$this->assertEquals(13, app(DropshipReconciler::class)->factoryMonth(collect(app(DropshipFreightStore::class)->factories())->sole(), '2026-11')['summary']['settle']);
// 「拦截退回」算拦截费
$this->assertSame('intercept', \App\Support\DropshipFreight\DropshipFees::classify('拦截退回'));
// 补丁前入库的老文件 sheets 里没记附加费:导出时现读原文件补记
$sheets = collect(json_decode((string) $db->table('dropship_bill_files')->value('sheets'), true))->map(fn (array $x) => \Illuminate\Support\Arr::except($x, 'fees'))->all();
$db->table('dropship_bill_files')->update(['sheets' => json_encode($sheets, JSON_UNESCAPED_UNICODE)]);
// 导出的小汇总:附加费表金额合计放「厂家账单-附加费」一行,简尚核对空着
$out = tempnam(sys_get_temp_dir(), 'dropship_export_');
$handle = fopen($out, 'wb');
try {
app(DropshipExporter::class)->export(collect(app(DropshipFreightStore::class)->factories())->sole(), '2026-11', $handle);
} finally {
fclose($handle);
}
$book = \PhpOffice\PhpSpreadsheet\IOFactory::load($out);
$sheet = $book->getSheetByName('汇总');
$summary = $sheet->toArray(null, false, false);
$this->assertSame(['运费', '记账', '厂家账单-附加费', '合计'], array_column(array_slice($summary, 1, 4), 0));
$this->assertEquals([13, 13], array_slice($summary[1], 1, 2));
$this->assertEquals(6.5, $summary[3][1]);
$this->assertEquals(6.5,$summary[3][2]);
$this->assertEquals(19.5, $sheet->getCell('B5')->getCalculatedValue());
$this->assertEquals(0, $sheet->getCell('D5')->getCalculatedValue());
$book->disconnectWorksheets();
@unlink($out);
$file = $db->table('dropship_bill_files')->first();
$this->assertStringContainsString('"fees"', (string) $file->sheets);
$this->assertSame(['退回费' => 3.0, '拦截费' => 2.0, '上楼费' => 1.5], app(DropshipFreightStore::class)->feesFor($file));
}
public function test_export_keeps_uncalculated_settlement_blank(): void
{
Storage::fake('local');
$db = CourierBillMatcher::db();
$factoryId = $db->table('dropship_factories')->insertGetId(['name' => '未核算测试厂家', 'warehouse' => self::WAREHOUSE,
'keywords' => '测试快递', 'created_at' => now(), 'updated_at' => now()]);
$this->ship('UNCALCULATED0001', '测试快递', self::WAREHOUSE, '2026-11-03 09:00:00', 1, null);
$input = $this->xlsx(['账单' => [['快递单号', '运费'], ['UNCALCULATED0001', 6]]]);
$output = tempnam(sys_get_temp_dir(), 'uncalculated_export_');
$book = null;
try {
$store = app(DropshipFreightStore::class);
$store->uploadFor('未核算.xlsx', $input, '2026-11', $factoryId, '测试');
$handle = fopen($output, 'wb');
try {
app(DropshipExporter::class)->export(collect($store->factories())->sole(), '2026-11', $handle);
} finally {
fclose($handle);
}
$book = \PhpOffice\PhpSpreadsheet\IOFactory::load($output);
$this->assertSame('运费', (string) $book->getSheetByName('汇总')->getCell('A2')->getValue());
$this->assertEquals(6, $book->getSheetByName('汇总')->getCell('B2')->getValue());
$this->assertNull($book->getSheetByName('汇总')->getCell('C2')->getValue());
$summary = app(\App\Support\DropshipFreight\DropshipBillSummary::class)->build(
collect($store->factories())->sole(), '2026-11', app(DropshipReconciler::class)->factoryMonth(collect($store->factories())->sole(), '2026-11')['rows']);
$this->assertNull($summary['rows'][0]['settle']);
$this->assertSame(6.0, $summary['rows'][0]['diff']);
} finally {
$book?->disconnectWorksheets();
@unlink($input);
@unlink($output);
}
}
public function test_rematch_refreshes_current_factory_month_without_changing_source_or_manual_fees(): void
{
Storage::fake('local');
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()->withExceptionHandling();
$db = CourierBillMatcher::db();
$store = app(DropshipFreightStore::class);
$id = $db->table('dropship_factories')->insertGetId(['name' => '临沂卿德客', 'warehouse' => self::WAREHOUSE,
'keywords' => '卿德客', 'created_at' => now(), 'updated_at' => now()]);
// 当前生产单家最多 71 条附加费,按这一规模覆盖重新匹配及页面返回。
$feeRows = [['快递单号', '附加费金额', '附加费类型']];
for ($i = 1; $i <= 71; $i++) $feeRows[] = [sprintf('773444%06d', $i), 4, '退回费'];
$file = $store->uploadFor('卿德客11月.xlsx', $this->xlsx([
'账单' => [['单号', '运费'], ['773444000001', 8]],
'附加费' => $feeRows,
]), '2026-11', $id, '测试');
$source = $db->table('dropship_bill_lines')->where('file_id', $file)->get()->toJson();
$factory = collect($store->factories())->sole();
$this->assertSame(Category::UNMATCHED, app(DropshipReconciler::class)->factoryMonth($factory, '2026-11')['rows'][0]['status']);
$fees = app(\App\Support\DropshipFreight\DropshipFees::class);
$fees->save('2026-11', $id, ['booking' => 2], '保留手工备注', (int) $this->company->id, $this->user->id);
BillSurchargeMatchingTest::createSettlementTable();
for ($i = 1; $i <= 71; $i++) {
$waybill = sprintf('773444%06d', $i);
$this->ship($waybill, '卿德客申通', self::WAREHOUSE, '2026-11-03 09:00:00', $i, 6);
$db->table('courier_surcharge_settlement_rows')->insert(['waybill' => $waybill, 'surcharge_type' => '退回费',
'courier_name' => '卿德客申通', 'settlement_amount' => 3, 'settlement_status' => '已计算', 'shipped_at' => '2026-11-03 00:00:00']);
}
$matcher = app(\App\Support\CourierBills\SurchargeSettlementMatcher::class);
// 其他月份的旧匹配记录不能被这次操作清除。
$other = (array) $matcher->query('dropship', $id, '2026-11')->first();
unset($other['id']);
$other['bill_month'] = '2026-10';
$other['row_no'] = 999;
$other['waybill_no'] = 'OTHER-MONTH';
$otherId = $db->table($matcher::TABLE)->insertGetId($other);
$otherBefore = (array) $db->table($matcher::TABLE)->find($otherId);
foreach (['courier-payables', 'courier-payables-final'] as $section) {
$page = route('business.pages.show', ['section' => $section, 'page' => 'dropship-freight-reconciliation',
'df_view' => 'overview', 'month' => '2026-11']);
$url = route("business.$section.dropship-freight.rematch", ['factory' => $id]);
$this->get($page)->assertOk()->assertSee('data-df-rematch', false)->assertSeeText('重新匹配');
$this->post($url, ['month' => '2026-11', 'df_view' => 'overview'])->assertRedirect($page)->assertSessionHas('dropship_message');
$this->get($page)->assertOk()->assertSeeText('217.00')->assertSeeText('保留手工备注');
$detail = route('business.pages.show', ['section' => $section, 'page' => 'dropship-freight-reconciliation',
'df_view' => 'factory', 'month' => '2026-11', 'factory' => $id]);
$this->post($url, ['month' => '2026-11'])->assertRedirect($detail);
$this->get($detail)->assertOk()->assertSee('data-df-rematch', false)->assertSeeText('一致但运费有差');
$this->post($url, ['month' => '2026-13'])->assertSessionHasErrors('month');
$this->post($url, ['month' => '2026-11', 'df_view' => 'upload'])->assertSessionHasErrors('df_view');
}
$this->assertSame(71, $matcher->query('dropship', $id, '2026-11')->count());
$matched = $matcher->query('dropship', $id, '2026-11')->where('waybill_no', '773444000001')->sole();
$this->assertSame('已匹配', $matched->match_status);
$this->assertEquals(3, $matched->self_amount);
$this->assertSame($source, $db->table('dropship_bill_lines')->where('file_id', $file)->get()->toJson());
$this->assertEquals($otherBefore, (array) $db->table($matcher::TABLE)->find($otherId));
$row = $fees->rows('2026-11', [$id => 6], (int) $this->company->id)[$id];
$this->assertEquals(2, $row['values']['booking']);
$this->assertEquals(213, $row['values']['returned']);
$this->assertSame('保留手工备注', $row['note']);
$this->post(route('business.courier-payables.dropship-freight.rematch', ['factory' => $id + 999]),
['month' => '2026-11'], ['X-Requested-With' => 'XMLHttpRequest'])->assertNotFound();
$confirmed = ['month' => '2026-11', 'factory_id' => $id, 'status' => 'confirmed', 'version' => 1];
app(\Modules\EcommerceFinance\Services\SupplierPayableOverrideStore::class)->save(
\App\Support\DropshipFreight\DropshipConfirmation::DATASET, '2026-11|' . $id, $confirmed,
(int) $this->company->id, $this->user->id, 'test');
$before = $matcher->query('dropship', $id, '2026-11')->get()->toJson();
$this->post(route('business.courier-payables.dropship-freight.rematch', ['factory' => $id]), ['month' => '2026-11'])
->assertSessionHasErrors('dropship');
$this->assertSame($before, $matcher->query('dropship', $id, '2026-11')->get()->toJson());
$this->assertSame('confirmed', app(\App\Support\DropshipFreight\DropshipConfirmation::class)
->state('2026-11', $id, (int) $this->company->id)['status']);
}
public function test_keyword_helpers(): void
{
$this->assertSame('卿德客', DropshipFreightStore::warehouseCore('工厂-山东卿德客代发仓'));
$this->assertSame('派雅世佳', DropshipFreightStore::warehouseCore('工厂-河北霸州派雅世佳代发仓'));
$this->assertSame('四强', DropshipFreightStore::commonPart(['四强申通', '四强圆通']));
$this->assertSame('派雅', DropshipFreightStore::commonPart(['派雅韵达', '派雅世佳']));
$this->assertSame('', DropshipFreightStore::commonPart(['四强申通', '森卓']));
$this->assertSame(['卿德客', '极兔'], DropshipFreightStore::splitKeywords('卿德客, 极兔、卿德客'));
}
private function shipping()
{
return app(ShippingLookup::class)->connection();
}
private function ship(string $waybill, string $express, string $warehouse, string $time, int $source, ?float $freight): void
{
$this->shipping()->table('jst_oms_shipping')->insert(['express_no' => $waybill, 'express_name1' => $express, 'warehouse_name' => $warehouse,
'ship_time' => $time, 'source_id' => $source]);
$this->shipping()->table('jst_oms_shipping_freight')->insert(['source_id' => $source, 'freight' => $freight,
'status' => $freight === null ? '报价管理里没有「' . $express . '」的报价' : 'OK', 'charge_weight' => 1]);
}
/** @param array<string,list<list<mixed>>> $sheets */
private function xlsx(array $sheets): string
{
$book = new Spreadsheet();
$book->removeSheetByIndex(0);
foreach ($sheets as $title => $rows) {
$sheet = $book->createSheet();
$sheet->setTitle($title);
foreach ($rows as $r => $row) {
foreach ($row as $c => $value) {
if ($value !== null) {
$sheet->setCellValueExplicit([$c + 1, $r + 1], $value, is_string($value)
? \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING : \PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_NUMERIC);
}
}
}
}
$path = tempnam(sys_get_temp_dir(), 'df_') . '.xlsx';
(new Xlsx($book))->save($path);
return $path;
}
}