instance('config', new Repository(['app' => ['platform_timezone' => 'Asia/Shanghai']])); $db = new Manager($app); $db->addConnection(['driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '']); $db->setEventDispatcher(new \Illuminate\Events\Dispatcher($app)); $app->instance('db', $db->getDatabaseManager()); $db->getConnection()->statement('CREATE TABLE dropship_factories (id INTEGER PRIMARY KEY, warehouse TEXT, keywords TEXT)'); Facade::clearResolvedInstances(); Facade::setFacadeApplication($app); $app->instance('request', Request::create('/?month=2026-09&state=all')); $app->instance(\Illuminate\Contracts\Routing\ResponseFactory::class, new \Illuminate\Routing\ResponseFactory( Mockery::mock(\Illuminate\Contracts\View\Factory::class), Mockery::mock(\Illuminate\Routing\Redirector::class) )); } protected function tearDown(): void { Mockery::close(); parent::tearDown(); } private function row(array $patch = []): array { return array_replace(['source_id' => 1, 'trade_no' => '123456789012345678', 'express_no' => 'BF001', 'express_name1' => '补发快递', 'ship_time' => '2026-09-15', 'barcode' => 'GBGJ-SJ038024N1410V02-10,GBGJ-SJ038024N1410V02-2', 'freight' => '12.35'], $patch); } public function test_four_province_spellings_deduct_full_freight_once(): void { foreach (['山东', '山东省', '河北', '河北省'] as $province) { $result = (new SupplierAccessoryFreightMatcher)->match($this->row(), [['name' => '成品', 'supplier_name' => '供应商甲'], ['name' => '成品', 'supplier_name' => '供应商甲']], [['linkerprovience' => $province]]); $this->assertSame('GBGJ-SJ038024N1410V02', $result['normalized_barcode']); $this->assertSame('ready', $result['state']); $this->assertSame(1235, $result['deduction_cents']); } } public function test_external_courier_always_excluded_and_keeps_supplier_details(): void { foreach (['express_name1', 'express_name2'] as $field) { foreach (['12.35', null, '0'] as $freight) { $row = (new SupplierAccessoryFreightMatcher)->match($this->row([$field => ' 外采快递 ', 'freight' => $freight]), [['name'=>'成品','supplier_name'=>'甲']], [['linkerprovience'=>'河北省']]); $this->assertSame('excluded', $row['state']); $this->assertSame(0, $row['deduction_cents']); $this->assertSame('甲', $row['supplier_name']); $this->assertSame('外采快递不扣配件运费', $row['reason']); } } $row = (new SupplierAccessoryFreightMatcher)->match($this->row(['express_name1'=>'外采快递']), [], []); $this->assertSame('excluded', $row['state']); $this->assertSame(0, $row['deduction_cents']); $normal = (new SupplierAccessoryFreightMatcher)->match($this->row(), [['name'=>'成品','supplier_name'=>'甲']], [['linkerprovience'=>'河北省']]); $this->assertSame(1235, $normal['deduction_cents']); } public function test_missing_or_ambiguous_product_supplier_province_never_deducts(): void { $product = [['name' => '成品', 'supplier_name' => '甲']]; foreach ([ [[], []], [[['name' => '成品', 'supplier_name' => '']], []], [$product, []], [[...$product, ['name' => '成品', 'supplier_name' => '乙']], [['linkerprovience' => '山东']]], [$product, [['linkerprovience' => '']]], [$product, [['linkerprovience' => '山东'], ['linkerprovience' => '河北']]], [$product, [['linkerprovience' => '山东'], ['linkerprovience' => '']]] ] as [$products, $suppliers]) { $result = (new SupplierAccessoryFreightMatcher)->match($this->row(), $products, $suppliers); $this->assertSame('pending', $result['state']); $this->assertSame(0, $result['deduction_cents']); } } public function test_factory_attribute_exempts_freight_even_when_other_details_are_missing(): void { $matcher = new SupplierAccessoryFreightMatcher; foreach (['12.35', '0', null] as $freight) { foreach ([[], [['name' => '成品', 'supplier_name' => '甲']]] as $products) { $row = $matcher->match($this->row(['freight' => $freight]), $products, [['linkerprovience' => '河北省']], [ ['exp_properties' => ' 工厂 '], ['exp_properties' => '工厂'], ]); $this->assertSame('excluded', $row['state']); $this->assertSame(0, $row['deduction_cents']); $this->assertSame('工厂', $row['courier_attribute']); $this->assertSame('快递属性为工厂,不扣配件运费', $row['reason']); } } } public function test_other_attributes_keep_existing_rules_and_conflicting_attributes_require_review(): void { $matcher = new SupplierAccessoryFreightMatcher; $products = [['name' => '成品', 'supplier_name' => '甲']]; $suppliers = [['linkerprovience' => '山东']]; foreach ([[], [['exp_properties' => '']], [['exp_properties' => '简尚']]] as $couriers) { $row = $matcher->match($this->row(), $products, $suppliers, $couriers); $this->assertSame('ready', $row['state']); $this->assertSame(1235, $row['deduction_cents']); } $row = $matcher->match($this->row(), $products, $suppliers, [['exp_properties' => '工厂'], ['exp_properties' => '简尚']]); $this->assertSame('pending', $row['state']); $this->assertSame(0, $row['deduction_cents']); $this->assertSame('同名快递属性冲突,需核实', $row['reason']); } public function test_dropship_keyword_must_match_courier_and_warehouse_in_the_same_configuration(): void { $matcher = new SupplierAccessoryFreightMatcher; $factories = [ (object) ['warehouse' => '工厂-河北浩浦代发仓', 'keywords' => ' 浩浦, 浩浦 '], (object) ['warehouse' => '工厂-河北森卓代发仓', 'keywords' => '四强'], (object) ['warehouse' => '工厂-普通仓库', 'keywords' => '普通'], (object) ['warehouse' => '工厂-空配置代发仓', 'keywords' => ''], ]; $this->assertSame('工厂-河北浩浦代发仓', $matcher->dropshipWarehouse(' 浩浦极兔 ', $factories)); foreach (['', '极兔', '其他极兔', '四强圆通', '普通快递', '空配置极兔'] as $courier) { $this->assertNull($matcher->dropshipWarehouse($courier, $factories)); } $this->assertNull($matcher->dropshipWarehouse('浩浦极兔', [])); // 不能将另一条配置的仓库和这条配置的关键字拼成一次命中。 $this->assertNull($matcher->dropshipWarehouse('四强圆通', [ (object) ['warehouse' => '工厂-河北森卓代发仓', 'keywords' => '四强'], (object) ['warehouse' => '工厂-河北四强代发仓', 'keywords' => '森卓'], ])); $warehouse = $matcher->dropshipWarehouse('浩浦极兔', $factories); foreach ([[], [['exp_properties' => '简尚']], [['exp_properties' => '工厂'], ['exp_properties' => '简尚']]] as $couriers) { $row = $matcher->match($this->row(['express_name1' => '浩浦极兔']), [['name' => '成品', 'supplier_name' => '甲']], [['linkerprovience' => '河北']], $couriers, $warehouse); $this->assertSame('excluded', $row['state']); $this->assertSame(0, $row['deduction_cents']); $this->assertSame(1235, $row['freight_cents']); $this->assertSame('甲', $row['supplier_name']); $this->assertSame('代发厂家配置匹配「工厂-河北浩浦代发仓」,不扣配件运费', $row['reason']); } } public function test_other_provinces_zero_invalid_and_equivalent_duplicate_provinces(): void { $matcher = new SupplierAccessoryFreightMatcher; $products = [['name' => '成品', 'supplier_name' => '甲']]; foreach (['江苏省', '山东济南', '河北省石家庄市'] as $province) { $result = $matcher->match($this->row(), $products, [['linkerprovience' => $province]]); $this->assertSame('excluded', $result['state']); $this->assertSame(0, $result['deduction_cents']); } foreach ([null, '', '-5', 'abc'] as $amount) { $result = $matcher->match($this->row(['freight' => $amount]), $products, [['linkerprovience' => '河北']]); $this->assertSame('pending', $result['state']); $this->assertSame(0, $result['deduction_cents']); } $result = $matcher->match($this->row(['freight' => '0']), $products, [['linkerprovience' => '河北']]); $this->assertSame('excluded', $result['state']); $result = $matcher->match($this->row(['freight' => '0.10']), $products, [['linkerprovience' => ' 山东 '], ['linkerprovience' => '山东省']]); $this->assertSame('ready', $result['state']); $this->assertSame(10, $result['deduction_cents']); } public function test_repository_uses_product_supplier_not_shipping_supplier_and_ignores_combinations(): void { $connection = app('db')->connection(); $connection->statement('CREATE TABLE products (sku_id TEXT, sku_type TEXT, name TEXT, supplier_name TEXT)'); $connection->statement('CREATE TABLE suppliers (scmname TEXT, linkerprovience TEXT)'); $connection->statement('CREATE TABLE couriers (expname TEXT, exp_properties TEXT)'); $connection->table('couriers')->insert([ ['expname' => '工厂快递', 'exp_properties' => '工厂'], ['expname' => '补发快递', 'exp_properties' => '简尚'], ['expname' => '补发快递-其他', 'exp_properties' => '工厂'], ]); $connection->table('products')->insert([ ['sku_id' => 'GBGJ-SJ038024N1410V02', 'sku_type' => 'normal', 'name' => '成品', 'supplier_name' => '商品供应商'], ['sku_id' => 'GBGJ-SJ038024N1410V02', 'sku_type' => 'combine', 'name' => '组合', 'supplier_name' => '其他供应商'], ]); $connection->table('suppliers')->insert(['scmname' => '商品供应商', 'linkerprovience' => '河北省']); $connection->table('dropship_factories')->insert(['warehouse' => '工厂-河北浩浦代发仓', 'keywords' => '浩浦']); $registry = Mockery::mock(BusinessMirrorDatasetRegistry::class); foreach ([ProductCatalogMirrorRepository::DATASET_KEY => 'products', SupplierManagementMirrorRepository::DATASET => 'suppliers', CourierInformationMirrorRepository::DATASET_KEY => 'couriers'] as $key => $table) { $dataset = Mockery::mock(BusinessMirrorDataset::class); $dataset->shouldReceive('targetTable')->andReturn($table); $registry->shouldReceive('get')->with($key)->andReturn($dataset); } $mirror = Mockery::mock(GenericBusinessMirrorRepository::class); $mirror->shouldReceive('ready')->andReturnTrue(); $mirror->shouldReceive('connection')->andReturn($connection); $shipping = Mockery::mock(ShippingOrderRepository::class); $shipping->shouldReceive('accessoryFreightBatches')->once()->with('2026-09-01', '2026-10-01')->andReturn((function () { yield [$this->row(['supplier_name' => '错误的历史供应商']), $this->row(['express_name1' => '工厂快递']), $this->row(['express_name1' => '', 'express_name2' => '工厂快递']), $this->row(['express_name1' => '补发快递', 'express_name2' => '工厂快递']), $this->row(['express_name1' => '浩浦极兔']), $this->row(['express_name1' => '', 'express_name2' => '浩浦极兔']), $this->row(['express_name1' => '补发快递', 'express_name2' => '浩浦极兔'])]; })()); $repo = new SupplierAccessoryFreightRepository($shipping, $registry, $mirror, new SupplierAccessoryFreightMatcher); $rows = iterator_to_array($repo->rows('2026-09')); $this->assertCount(7, $rows); $this->assertSame('商品供应商', $rows[0]['supplier_name']); $this->assertSame(1235, $rows[0]['deduction_cents']); $this->assertSame('简尚', $rows[0]['courier_attribute']); foreach ([1, 2] as $index) { $this->assertSame('工厂', $rows[$index]['courier_attribute']); $this->assertSame('excluded', $rows[$index]['state']); $this->assertSame(0, $rows[$index]['deduction_cents']); } $this->assertSame('ready', $rows[3]['state']); $this->assertSame('简尚', $rows[3]['courier_attribute']); foreach ([4, 5] as $index) { $this->assertSame('excluded', $rows[$index]['state']); $this->assertSame(0, $rows[$index]['deduction_cents']); $this->assertStringContainsString('工厂-河北浩浦代发仓', $rows[$index]['reason']); } $this->assertSame('ready', $rows[6]['state']); $this->assertSame(1235, $rows[6]['deduction_cents']); } private function data(): SupplierAccessoryFreightPageData { $repository = Mockery::mock(SupplierAccessoryFreightRepository::class); $repository->shouldReceive('rows')->with('2026-09')->andReturnUsing(function () { $matcher = new SupplierAccessoryFreightMatcher; for ($i = 0; $i < 105; $i++) yield $matcher->match($this->row(['source_id' => $i, 'freight' => '0.10']), [['name' => '=危险商品', 'supplier_name' => '山东供应商']], [['linkerprovience' => '山东']]); yield $matcher->match($this->row(['source_id' => 200]), [], []); }); return new SupplierAccessoryFreightPageData($repository); } public function test_factory_rows_are_zero_in_summary_ready_filter_and_csv(): void { $repository = Mockery::mock(SupplierAccessoryFreightRepository::class); $repository->shouldReceive('rows')->with('2026-09')->andReturnUsing(function () { $matcher = new SupplierAccessoryFreightMatcher; foreach (['工厂', '代发', '简尚'] as $attribute) { yield $matcher->match($this->row(['express_no' => ['工厂' => 'FACTORY-1', '代发' => 'DROPSHIP-1', '简尚' => 'NORMAL-1'][$attribute]]), [['name' => '成品', 'supplier_name' => '甲']], [['linkerprovience' => '河北']], [['exp_properties' => $attribute]], $attribute === '代发' ? '工厂-河北浩浦代发仓' : null); } }); $data = new SupplierAccessoryFreightPageData($repository); app()->instance('request', Request::create('/?month=2026-09&state=ready')); $page = $data->page(); $this->assertSame(['all' => 3, 'ready' => 1, 'excluded' => 2, 'pending' => 0, 'amount' => 1235], $page['freightSummary']); $this->assertCount(1, $page['freightRows']); $this->assertSame('NORMAL-1', $page['freightRows']->items()[0]['express_no']); $controller = new \App\Http\Controllers\Business\SupplierAccessoryFreight; $response = $controller->export($data); ob_start(); $response->sendContent(); $csv = ob_get_clean(); $this->assertStringNotContainsString('FACTORY-1', $csv); $this->assertStringNotContainsString('DROPSHIP-1', $csv); app()->instance('request', Request::create('/?month=2026-09&state=excluded&columns=express_no,courier_attribute,deduction,reason')); $response = $controller->export($data); ob_start(); $response->sendContent(); $csv = ob_get_clean(); $lines = explode("\n", trim(substr($csv, 3))); $this->assertCount(3, $lines); $this->assertSame(['FACTORY-1', '工厂', '0.00', '快递属性为工厂,不扣配件运费'], array_slice(str_getcsv($lines[1]), 3)); $this->assertSame(['DROPSHIP-1', '代发', '0.00', '代发厂家配置匹配「工厂-河北浩浦代发仓」,不扣配件运费'], array_slice(str_getcsv($lines[2]), 3)); } public function test_unready_courier_mirror_does_not_produce_deductions(): void { $registry = Mockery::mock(BusinessMirrorDatasetRegistry::class); foreach ([ProductCatalogMirrorRepository::DATASET_KEY, SupplierManagementMirrorRepository::DATASET, CourierInformationMirrorRepository::DATASET_KEY] as $key) { $dataset = Mockery::mock(BusinessMirrorDataset::class); $registry->shouldReceive('get')->with($key)->andReturn($dataset); $datasets[$key] = $dataset; } $mirror = Mockery::mock(GenericBusinessMirrorRepository::class); foreach ($datasets as $key => $dataset) $mirror->shouldReceive('ready')->with($dataset)->andReturn($key !== CourierInformationMirrorRepository::DATASET_KEY); $mirror->shouldNotReceive('connection'); $shipping = Mockery::mock(ShippingOrderRepository::class); $shipping->shouldNotReceive('accessoryFreightBatches'); $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('商品、供应商或快递资料尚未完成首次同步'); iterator_to_array((new SupplierAccessoryFreightRepository($shipping, $registry, $mirror, new SupplierAccessoryFreightMatcher))->rows('2026-09')); } public function test_summary_pagination_and_filters_use_full_month_without_multiplying_amount(): void { app()->instance('request', Request::create('/?month=2026-09&state=all&page=2')); $page = $this->data()->page(); $this->assertNull($page['freightError']); $this->assertCount(50, $page['freightRows']); $this->assertSame(106, $page['freightRows']->total()); $this->assertSame(1050, $page['freightSummary']['amount']); app()->instance('request', Request::create('/?month=2026-09&state=ready&supplier_name=山东&page=3')); $page = $this->data()->page(); $this->assertCount(5, $page['freightRows']); $this->assertSame(105, $page['freightRows']->total()); $this->assertSame(0, $page['freightSummary']['pending']); $this->assertSame(1050, $page['freightSummary']['amount']); } public function test_csv_matches_filters_preserves_long_ids_and_escapes_formulas(): void { app()->instance('request', Request::create('/?month=2026-09&state=pending')); $controller = new \App\Http\Controllers\Business\SupplierAccessoryFreight; $response = $controller->export($this->data()); ob_start(); $response->sendContent(); $csv = ob_get_clean(); $this->assertStringStartsWith("\xEF\xBB\xBF", $csv); $this->assertSame(2, substr_count($csv, "\n")); $this->assertStringContainsString("'123456789012345678", $csv); $this->assertStringContainsString('待核实', $csv); app()->instance('request', Request::create('/?month=2026-09&state=ready')); $response = $controller->export($this->data()); ob_start(); $response->sendContent(); $csv = ob_get_clean(); $this->assertStringContainsString("'=危险商品", $csv); app()->instance('request', Request::create('/?month=2026-09&state=ready&columns=deduction,supplier_name')); $response = $controller->export($this->data()); ob_start(); $response->sendContent(); $csv = ob_get_clean(); $lines = explode("\n", trim(substr($csv, 3))); $this->assertSame(['业务月份', '发货记录ID', '仓库', '扣款金额(元)', '供应商'], str_getcsv($lines[0])); $this->assertCount(5, str_getcsv($lines[1])); } public function test_filters_accept_province_alias_and_reject_invalid_month_state_and_columns(): void { app()->instance('request', Request::create('/?month=2026-09&state=all&province=山东省')); $this->assertSame('山东', $this->data()->filters()['province']); foreach (['month=2026-13', 'month[]=2026-09', 'month=1999-01', 'month=2026-09&state=unknown', 'month=2026-09&supplier_name[]=x', 'month=2026-09&columns=', 'month=2026-09&columns=state,state', 'month=2026-09&columns=password'] as $query) { app()->instance('request', Request::create('/?' . $query)); try { $this->data()->filters(); $this->data()->exportColumns(); $this->fail('应拒绝无效条件'); } catch (\Symfony\Component\HttpKernel\Exception\HttpException $exception) { $this->assertSame(422, $exception->getStatusCode()); } } } public function test_data_error_clears_partial_rows_and_totals(): void { $repository = Mockery::mock(SupplierAccessoryFreightRepository::class); $repository->shouldReceive('rows')->andReturnUsing(function () { yield (new SupplierAccessoryFreightMatcher)->match($this->row(), [['name'=>'商品','supplier_name'=>'甲']], [['linkerprovience'=>'河北']]); throw new \RuntimeException('读取失败'); }); $handler = Mockery::mock(\Illuminate\Contracts\Debug\ExceptionHandler::class); $handler->shouldReceive('report')->once(); app()->instance(\Illuminate\Contracts\Debug\ExceptionHandler::class, $handler); $page = (new SupplierAccessoryFreightPageData($repository))->page(); $this->assertNotNull($page['freightError']); $this->assertSame(0, $page['freightRows']->total()); $this->assertSame(0, $page['freightSummary']['amount']); } public function test_representative_month_caches_factory_matching_and_keeps_export_totals(): void { $connection = app('db')->connection(); $connection->statement('CREATE TABLE products (sku_id TEXT, sku_type TEXT, name TEXT, supplier_name TEXT)'); $connection->statement('CREATE TABLE suppliers (scmname TEXT, linkerprovience TEXT)'); $connection->statement('CREATE TABLE couriers (expname TEXT, exp_properties TEXT)'); $connection->table('products')->insert(['sku_id' => 'GBGJ-SJ038024N1410V02', 'sku_type' => 'normal', 'name' => '成品', 'supplier_name' => '供应商甲']); $connection->table('suppliers')->insert(['scmname' => '供应商甲', 'linkerprovience' => '河北']); for ($i = 0; $i < 79; $i++) { $connection->table('couriers')->insert(['expname' => sprintf('厂家%02d极兔', $i), 'exp_properties' => '简尚']); if ($i < 37) $connection->table('dropship_factories')->insert(['warehouse' => sprintf('工厂-河北厂家%02d代发仓', $i), 'keywords' => sprintf('厂家%02d', $i)]); } $registry = Mockery::mock(BusinessMirrorDatasetRegistry::class); foreach ([ProductCatalogMirrorRepository::DATASET_KEY => 'products', SupplierManagementMirrorRepository::DATASET => 'suppliers', CourierInformationMirrorRepository::DATASET_KEY => 'couriers'] as $key => $table) { $dataset = Mockery::mock(BusinessMirrorDataset::class); $dataset->shouldReceive('targetTable')->andReturn($table); $registry->shouldReceive('get')->with($key)->andReturn($dataset); } $mirror = Mockery::mock(GenericBusinessMirrorRepository::class); $mirror->shouldReceive('ready')->andReturnTrue(); $mirror->shouldReceive('connection')->andReturn($connection); $shipping = Mockery::mock(ShippingOrderRepository::class); $shipping->shouldReceive('accessoryFreightBatches')->times(4)->andReturnUsing(function () { for ($start = 0; $start < 42625; $start += 1000) { $batch = []; for ($i = $start; $i < min($start + 1000, 42625); $i++) { $batch[] = $this->row(['source_id' => $i, 'express_no' => 'PERF' . $i, 'express_name1' => sprintf('厂家%02d极兔', $i % 79), 'freight' => '0.10']); } yield $batch; } }); $matcher = new class extends SupplierAccessoryFreightMatcher { public int $lookups = 0; public function dropshipWarehouse(string $courier, iterable $factories): ?string { $this->lookups++; return parent::dropshipWarehouse($courier, $factories); } }; $data = new SupplierAccessoryFreightPageData(new SupplierAccessoryFreightRepository($shipping, $registry, $mirror, $matcher)); $ready = intdiv(42625, 79) * 42 + max(0, 42625 % 79 - 37); $queries = 0; $factoryQueries = 0; $sqlMs = 0; $connection->listen(function ($query) use (&$queries, &$factoryQueries, &$sqlMs) { $queries++; $sqlMs += $query->time; if (str_contains($query->sql, 'from "dropship_factories"')) $factoryQueries++; }); $start = microtime(true); app()->instance('request', Request::create('/?month=2026-09&state=ready')); $page = $data->page(); $this->assertNull($page['freightError']); $this->assertSame($ready, $page['freightRows']->total()); $this->assertSame($ready * 10, $page['freightSummary']['amount']); $this->assertSame(42625 - $ready, $page['freightSummary']['excluded']); $this->assertCount(50, $page['freightRows']); app()->instance('request', Request::create('/?month=2026-09&state=ready&page=2')); $second = $data->page(); $this->assertCount(50, $second['freightRows']); $this->assertNotSame($page['freightRows']->items()[0]['express_no'], $second['freightRows']->items()[0]['express_no']); app()->instance('request', Request::create('/?month=2026-09&state=excluded&express_no=PERF0')); $filtered = $data->page(); $this->assertSame(1, $filtered['freightRows']->total()); $this->assertSame(0, $filtered['freightSummary']['amount']); app()->instance('request', Request::create('/?month=2026-09&state=ready&columns=deduction')); $response = (new \App\Http\Controllers\Business\SupplierAccessoryFreight)->export($data); ob_start(); $response->sendContent(); $csv = ob_get_clean(); $this->assertSame($ready + 1, substr_count($csv, "\n")); $this->assertSame($ready, substr_count($csv, ',0.10')); $this->assertSame(4, $factoryQueries); // 每次读取都包含命中和未命中项;42,625 行只需判断 79 个名称。 $this->assertSame(79 * 4, $matcher->lookups); fwrite(STDERR, sprintf("\nACCESSORY_MONTH rows=42625 couriers=79 factories=37 first_second_filter_export=%.3fs php_peak_mb=%.1f queries=%d sql_ms=%.1f rss_peak_mb=%.1f\n", microtime(true) - $start, memory_get_peak_usage(true) / 1048576, $queries, $sqlMs, (getrusage()['ru_maxrss'] ?? 0) / 1024)); } }