CaiWuXiTong/tests/Feature/Business/CourierJointUploadTest.php

264 lines
16 KiB
PHP

<?php
namespace Tests\Feature\Business;
use App\Support\CourierBills\CourierBillMatcher;
use App\Support\CourierBills\CourierBillStore;
use App\Support\CourierBills\CourierJointUploads;
use App\Support\CourierBills\CourierUploadLink;
use App\Support\CourierBills\PortalFreightBillImports;
use App\Support\CourierBills\ShippingLookup;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Tests\Feature\FeatureTestCase;
final class CourierJointUploadTest extends FeatureTestCase
{
private array $ids = [];
private array $paths = [];
protected function setUp(): void
{
parent::setUp();
Storage::fake('local');
$this->company->makeCurrent(true);
foreach (CourierJointUploads::SETS as $set) {
foreach ($set['names'] as $name) {
if (in_array($name, ['睢宁宿迁圆通', '河北中通小件-江三', '山东顺丰大件', '苏北顺丰干配小件'], true)) continue;
$aliases = match ($name) {
'苏北宿迁圆通' => [$name, '睢宁宿迁圆通'],
'河北中通-江三' => [$name, '河北中通小件-江三'],
'山东顺丰干配' => [$name, '山东顺丰大件'],
'苏北顺丰干配大件' => [$name, '苏北顺丰干配小件'],
'睢宁德邦' => ['顺德德邦', $name],
default => [$name],
};
$this->ids[$name] = app(CourierBillStore::class)->saveGroup(null, ['name' => $name === '睢宁德邦' ? '顺德德邦' : $name,
'express_names' => $aliases, 'bundle' => '故意相同的合并配置']);
}
}
$this->ids['仓储费'] = app(CourierBillStore::class)->saveGroup(null, ['name' => '南昌樵舍仓仓储费',
'express_names' => ['南昌樵舍仓仓储费'], 'bundle' => '故意相同的合并配置']);
}
protected function tearDown(): void
{
foreach ($this->paths as $path) @unlink($path);
parent::tearDown();
}
public function test_explicit_sets_and_aliases_are_bound_to_the_signed_page_and_queued_task(): void
{
$this->withExceptionHandling();
$sets = app(CourierJointUploads::class);
$this->assertCount(7, $sets->resolve('qiaoshe')['groups']);
$this->assertCount(4, $sets->resolve('yuantong')['groups']);
$links = app(CourierUploadLink::class);
$url = $links->jointPageUrl((int) $this->company->id, 'yuantong', '2026-11');
$page = $this->get($url . '&group_id=' . $this->ids['仓储费'])->assertOk()
->assertSeeText('圆通联合上传')->assertSeeText('睢宁宿迁圆通')->assertDontSeeText('南昌樵舍仓仓储费');
preg_match('/action="([^"]*\/upload[^"]*)"/', $page->getContent(), $matches);
$upload = html_entity_decode($matches[1]);
$this->post($upload, ['group_id' => $this->ids['仓储费'], 'import' => $this->csv([['YT001', '', '', 10, '睢宁宿迁圆通']])])
->assertRedirect()->assertSessionHas('success');
// 队列接收后分组改变,旧授权失效,不能继续写入。
CourierBillMatcher::db()->table('courier_bill_groups')->where('id', $this->ids['苏北宿迁圆通'])
->update(['express_names' => json_encode(['苏北宿迁圆通', '睢宁宿迁圆通', '仓储费'])]);
$this->assertTrue(app(PortalFreightBillImports::class)->processNext());
$this->assertSame(0, CourierBillMatcher::db()->table('courier_bill_lines')->count());
$this->get($url)->assertStatus(410);
$this->get(preg_replace('/signature=[^&]+/', 'signature=' . str_repeat('0', 64), $url))->assertForbidden();
}
public function test_mixed_bill_uses_shipping_then_declared_name_and_preserves_fees_and_rereads(): void
{
$ship = app(ShippingLookup::class)->connection();
$ship->table('jst_oms_shipping')->insert(['express_no' => 'YT001', 'express_name1' => '常州圆通-上楼',
'ship_time' => '2026-11-05 10:00:00', 'source_id' => 100]);
$scope = app(CourierJointUploads::class)->snapshot('yuantong');
$store = app(CourierBillStore::class);
$id = $store->uploadJoint($this->book([
['YT001', '', '', 10, '苏北宿迁圆通'], // 发货数据优先
['YT002', '', '', 20, '睢宁宿迁圆通'], // 系统没有时按明确别名
['YT003', '', '', 30, '小件宿迁圆通'],
], [['YT002', 5, '上楼费']]), '2026-11', $scope, '测试');
$db = $store->db();
$this->assertSame('parsed', $db->table('courier_bill_files')->find($id)->status);
$this->assertEquals(65, $db->table('courier_bill_files')->find($id)->amount);
$this->assertOwners(['YT001' => '常州圆通-上楼', 'YT002' => '苏北宿迁圆通', 'YT003' => '小件宿迁圆通']);
$groupId = $this->ids['苏北宿迁圆通'];
$statementId = $db->table('courier_bill_statements')->where('group_id', $groupId)->value('id');
$this->assertEquals(5, $db->table('courier_bill_summary_items')->where('statement_id', $statementId)->where('label', '附加费')->sum('bill_amount'));
$store->reread($id);
$store->resplit($id);
$this->assertOwners(['YT001' => '常州圆通-上楼', 'YT002' => '苏北宿迁圆通', 'YT003' => '小件宿迁圆通']);
$this->assertSame(3, $db->table('courier_bill_lines')->count());
$duplicate = $store->uploadJoint($this->csv([['YT001', '', '', 10], ['YT002', '', '', 20]]), '2026-11', $scope, '测试');
$this->assertSame('failed', $db->table('courier_bill_files')->find($duplicate)->status);
$this->assertSame(3, $db->table('courier_bill_lines')->count());
}
public function test_outside_missing_and_inconsistent_rows_are_rejected_atomically(): void
{
$store = app(CourierBillStore::class);
$scope = app(CourierJointUploads::class)->snapshot('qiaoshe');
$cases = [
[['Q001', '', '', 10, '江西中通快运'], ['Q002', '', '', 10, '南昌樵舍仓仓储费']],
[['Q001', '', '', 10, '江西中通快运'], ['Q002', '', '', 10]],
[['Q001', '', '', 10, '江西中通快运'], ['Q001', '', '', 10, '樵舍中通']],
];
foreach ($cases as $rows) {
$id = $store->uploadJoint($this->csv($rows), '2026-11', $scope, '测试');
$this->assertSame('failed', $store->db()->table('courier_bill_files')->find($id)->status);
$this->assertSame(0, $store->db()->table('courier_bill_lines')->count());
}
$id = $store->uploadJoint($this->book([['Q001', '', '', 10, '樵舍中通']], [['Q002', 5, '上楼费']]), '2026-11', $scope, '测试');
$this->assertSame('failed', $store->db()->table('courier_bill_files')->find($id)->status);
$this->assertSame(0, $store->db()->table('courier_bill_surcharges')->count());
app(ShippingLookup::class)->connection()->table('jst_oms_shipping')->insert(['express_no' => 'Q003',
'express_name1' => '南昌樵舍仓仓储费', 'source_id' => 101]);
$id = $store->uploadJoint($this->csv([['Q003', '', '', 10, '樵舍中通']]), '2026-11', $scope, '测试');
$this->assertSame('failed', $store->db()->table('courier_bill_files')->find($id)->status);
}
public function test_confirmation_after_queue_prevents_all_writes(): void
{
$url = app(CourierUploadLink::class)->jointPageUrl((int) $this->company->id, 'qiaoshe', '2026-11');
$page = $this->get($url)->assertOk();
preg_match('/action="([^"]*\/upload[^"]*)"/', $page->getContent(), $matches);
$upload = html_entity_decode($matches[1]);
$this->post($upload, ['import' => $this->csv([['Q001', '', '', 10, '樵舍中通']])])->assertRedirect();
CourierBillMatcher::db()->table('courier_bill_statements')->insert(['group_id' => $this->ids['江西中通快运'],
'bill_month' => '2026-11', 'status' => 'confirmed', 'created_at' => now(), 'updated_at' => now()]);
$this->assertTrue(app(PortalFreightBillImports::class)->processNext());
$this->assertSame(0, CourierBillMatcher::db()->table('courier_bill_files')->count());
$this->get($url)->assertOk()->assertSeeText('财务已确认结算')->assertDontSee('name="import"', false);
}
public function test_new_sets_upload_all_requested_names_into_existing_groups(): void
{
foreach (['hebei' => 2, 'debang-shunfeng' => 4] as $key => $groupCount) {
$set = app(CourierJointUploads::class)->resolve($key);
$this->assertCount($groupCount, $set['groups']);
$url = app(CourierUploadLink::class)->jointPageUrl((int) $this->company->id, $key, '2026-11');
$response = $this->get($url)->assertOk()->assertSeeText($set['label']);
$rows = $expected = [];
foreach ($set['names'] as $i => $name) {
$no = strtoupper($key) . '000' . $i;
$rows[] = [$no, '', '', $i + 1, $name];
$group = collect($set['groups'])->first(fn ($g) => $g->name === $name || in_array($name, $g->express_names, true));
$expected[$no] = $group->name;
$response->assertSeeText($name);
}
preg_match('/action="([^"]*\/upload[^"]*)"/', $response->getContent(), $matches);
Http::fake();
$this->post(html_entity_decode($matches[1]), ['import' => $this->csv($rows)])->assertRedirect();
$this->assertTrue(app(PortalFreightBillImports::class)->processNext());
$file = CourierBillMatcher::db()->table('courier_bill_files')->orderByDesc('id')->first();
$this->assertSame('parsed', $file->status, $file->message ?? '');
$this->assertEquals(array_sum(range(1, count($rows))), $file->amount);
$actual = CourierBillMatcher::db()->table('courier_bill_lines as l')->join('courier_bill_statements as s', 's.id', '=', 'l.statement_id')
->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')->where('l.file_id', $file->id)->pluck('g.name', 'l.waybill_no')->all();
$this->assertEquals($expected, $actual);
}
}
public function test_unlisted_group_name_does_not_gain_access_through_an_allowed_alias(): void
{
$scope = app(CourierJointUploads::class)->snapshot('debang-shunfeng');
$store = app(CourierBillStore::class);
$id = $store->uploadJoint($this->csv([['DB001', '', '', 10, '顺德德邦']]), '2026-11', $scope, '测试');
$this->assertSame('failed', $store->db()->table('courier_bill_files')->find($id)->status);
$this->assertSame(0, $store->db()->table('courier_bill_lines')->count());
app(ShippingLookup::class)->connection()->table('jst_oms_shipping')->insert(['express_no' => 'DB002',
'express_name1' => '顺德德邦', 'source_id' => 102]);
$id = $store->uploadJoint($this->csv([['DB002', '', '', 10, '睢宁德邦']]), '2026-11', $scope, '测试');
$this->assertSame('failed', $store->db()->table('courier_bill_files')->find($id)->status);
$this->assertSame(0, $store->db()->table('courier_bill_lines')->count());
}
public function test_finance_can_open_each_link_and_courier_can_upload_one_mixed_file(): void
{
$this->loginAs()->withExceptionHandling();
$page = route('business.pages.show', ['section' => 'courier-payables-final', 'page' => 'courier-bill-reconciliation', 'cb_view' => 'upload']);
$this->get($page)->assertOk()->assertSeeText('樵舍联合上传')->assertSeeText('圆通联合上传')
->assertSeeText('河北中通与霸州百世联合上传')->assertSeeText('德邦与顺丰干配联合上传');
$entry = route('business.courier-payables-final.courier-bills.joint-upload-link', ['joint' => 'qiaoshe', 'month' => '2026-11']);
$response = $this->get($entry)->assertRedirect();
$url = $response->headers->get('Location');
auth()->logout();
$response = $this->get($url)->assertOk()->assertDontSeeText('南昌樵舍仓仓储费');
preg_match('/action="([^"]*\/upload[^"]*)"/', $response->getContent(), $matches);
Http::fake();
$this->post(html_entity_decode($matches[1]), ['import' => $this->csv([
['Q001', '', '', 10, '江西中通快运'], ['Q002', '', '', 20, '西安圆通'],
])])->assertRedirect();
$this->assertTrue(app(PortalFreightBillImports::class)->processNext());
$this->assertOwners(['Q001' => '江西中通快运', 'Q002' => '西安圆通']);
$this->get($url)->assertOk()->assertSeeText('已读入')->assertSeeText('30.00');
$primary = app(CourierJointUploads::class)->resolve('qiaoshe')['group_ids'][0];
$single = app(CourierUploadLink::class)->pageUrl((int) $this->company->id, $primary, '2026-11');
$this->get($single)->assertOk()->assertDontSeeText('仓储费和圆通混合.csv');
}
public function test_large_csv_keeps_all_rows_and_amounts(): void
{
if (! getenv('JOINT_UPLOAD_BENCHMARK')) $this->markTestSkipped('独立容量验收时运行');
$n = (int) getenv('JOINT_UPLOAD_BENCHMARK');
$path = tempnam(sys_get_temp_dir(), 'joint_') . '.csv';
$this->paths[] = $path;
$f = fopen($path, 'wb');
fputcsv($f, ['单号', '省', '重量', '运费', '快递名称', '面单', '费率']);
for ($i = 0; $i < $n; $i++) fputcsv($f, ['Q' . str_pad((string) $i, 12, '0', STR_PAD_LEFT), '', '', '1.23', $i % 2 ? '樵舍中通' : '江西中通快运', '', '']);
fclose($f);
$start = microtime(true);
$queries = 0;
CourierBillMatcher::db()->listen(function () use (&$queries) { $queries++; });
$validation = app(\App\Support\CourierBills\FreightBillTemplate::class)->validate($path, 'csv');
$this->assertSame($n, $validation['rows']);
$id = app(CourierBillStore::class)->uploadJoint(new UploadedFile($path, '容量.csv', null, null, true), '2026-11',
app(CourierJointUploads::class)->snapshot('qiaoshe'), '容量验收');
$file = CourierBillMatcher::db()->table('courier_bill_files')->find($id);
$this->assertSame('parsed', $file->status, $file->message ?? '');
$this->assertSame($n, CourierBillMatcher::db()->table('courier_bill_lines')->count());
$this->assertEquals(round($n * 1.23, 2), (float) $file->amount);
fwrite(STDERR, json_encode(['rows' => $n, 'bytes' => filesize($path), 'seconds' => round(microtime(true) - $start, 2),
'peak_mb' => round(memory_get_peak_usage(true) / 1048576, 1), 'queries' => $queries]) . PHP_EOL);
}
private function assertOwners(array $expected): void
{
$actual = CourierBillMatcher::db()->table('courier_bill_lines as l')->join('courier_bill_statements as s', 's.id', '=', 'l.statement_id')
->join('courier_bill_groups as g', 'g.id', '=', 's.group_id')->pluck('g.name', 'l.waybill_no')->all();
$this->assertEquals($expected, $actual);
}
private function csv(array $rows): UploadedFile
{
$path = tempnam(sys_get_temp_dir(), 'joint_') . '.csv';
$this->paths[] = $path;
$f = fopen($path, 'wb');
fputcsv($f, ['单号', '省', '重量', '运费', '快递名称', '面单', '费率']);
foreach ($rows as $row) fputcsv($f, array_pad($row, 7, ''));
fclose($f);
return new UploadedFile($path, '仓储费和圆通混合.csv', null, null, true);
}
private function book(array $rows, array $fees): UploadedFile
{
$path = tempnam(sys_get_temp_dir(), 'joint_') . '.xlsx';
$this->paths[] = $path;
$book = new Spreadsheet();
$book->getActiveSheet()->setTitle('账单')->fromArray([['单号', '省', '重量', '运费', '快递名称', '面单', '费率'], ...$rows]);
$book->createSheet()->setTitle('附加费')->fromArray([['快递单号', '附加费金额', '附加费类型'], ...$fees]);
(new Xlsx($book))->save($path);
$book->disconnectWorksheets();
return new UploadedFile($path, '联合账单.xlsx', null, null, true);
}
}