From 1e8488b914ffd254e6fdf169cf9cee5fcadc5708 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Thu, 22 Oct 2026 10:54:22 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=94=AE=E5=90=8E=E9=A6=96?= =?UTF-8?q?=E5=B1=8F=E6=9F=A5=E8=AF=A2=E4=B8=8E=E5=88=86=E9=A1=B5=EF=BC=8C?= =?UTF-8?q?=E9=99=90=E5=88=B6=E6=9C=AC=E5=9C=B0=20PHP=20=E6=9E=84=E5=BB=BA?= =?UTF-8?q?=E5=B9=B6=E8=A1=8C=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...0000_index_goods_profit_afs_order_time.php | 42 +++++++ deploy/Dockerfile.local | 2 +- .../Repositories/GoodsProfitAfsRepository.php | 24 +++- .../WorkOrderMirrorRepository.php | 17 ++- .../Services/BusinessMirrorSchemaManager.php | 9 ++ .../Services/GoodsProfitAfsLookupSchema.php | 75 ++++++++++++ .../Integration/GoodsProfitAfsLookupTest.php | 89 ++++++++++++++ .../GoodsProfitAfsRepositoryTest.php | 110 ++++++++++++++++++ .../WorkOrderMirrorRepositoryTest.php | 30 +++++ 9 files changed, 389 insertions(+), 9 deletions(-) create mode 100644 database/migrations/2026_10_22_150000_index_goods_profit_afs_order_time.php create mode 100644 modules/EcommerceFinance/Services/GoodsProfitAfsLookupSchema.php create mode 100644 tests/Integration/GoodsProfitAfsLookupTest.php create mode 100644 tests/Unit/EcommerceFinance/GoodsProfitAfsRepositoryTest.php diff --git a/database/migrations/2026_10_22_150000_index_goods_profit_afs_order_time.php b/database/migrations/2026_10_22_150000_index_goods_profit_afs_order_time.php new file mode 100644 index 00000000..6aa8deed --- /dev/null +++ b/database/migrations/2026_10_22_150000_index_goods_profit_afs_order_time.php @@ -0,0 +1,42 @@ +ensure( + DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')), + ); + } + + public function down(): void + { + if (config('system_database.mode', 'bootstrap') === 'bootstrap') return; + $db = DB::connection((string) config('upstream_mirrors.connection', 'business_mirror')); + if (! in_array($db->getDriverName(), ['mysql', 'mariadb'], true)) return; + $schema = Schema::connection($db->getName()); + if (! $schema->hasTable(GoodsProfitAfsLookupSchema::TABLE)) return; + + $changes = []; + foreach (array_keys(GoodsProfitAfsLookupSchema::INDEXES) as $index) { + if ($schema->hasIndex(GoodsProfitAfsLookupSchema::TABLE, $index)) { + $changes[] = 'DROP INDEX `' . $index . '`'; + } + } + if ($changes !== []) { + $db->statement('ALTER TABLE `' . GoodsProfitAfsLookupSchema::TABLE . '` ' + . implode(', ', $changes) . ', ALGORITHM=INPLACE, LOCK=NONE'); + } + if ($schema->hasColumn(GoodsProfitAfsLookupSchema::TABLE, GoodsProfitAfsLookupSchema::DATE_COLUMN)) { + $db->statement('ALTER TABLE `' . GoodsProfitAfsLookupSchema::TABLE . '` DROP COLUMN `' + . GoodsProfitAfsLookupSchema::DATE_COLUMN . '`, ALGORITHM=INPLACE, LOCK=NONE'); + } + } +}; diff --git a/deploy/Dockerfile.local b/deploy/Dockerfile.local index 714f342e..8d7ef530 100644 --- a/deploy/Dockerfile.local +++ b/deploy/Dockerfile.local @@ -41,7 +41,7 @@ RUN apt-get update \ g++ \ && docker-php-ext-configure gd --with-freetype --with-jpeg \ && docker-php-ext-configure pdo_odbc --with-pdo-odbc=unixODBC,/usr \ - && docker-php-ext-install -j"$(nproc)" \ + && docker-php-ext-install -j2 \ bcmath \ curl \ dom \ diff --git a/modules/EcommerceFinance/Repositories/GoodsProfitAfsRepository.php b/modules/EcommerceFinance/Repositories/GoodsProfitAfsRepository.php index 214a822b..dcdee067 100644 --- a/modules/EcommerceFinance/Repositories/GoodsProfitAfsRepository.php +++ b/modules/EcommerceFinance/Repositories/GoodsProfitAfsRepository.php @@ -4,6 +4,7 @@ namespace Modules\EcommerceFinance\Repositories; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; +use Modules\EcommerceFinance\Services\GoodsProfitAfsLookupSchema; /** * 订单售后费用明细:聚水潭「商品利润 → 导出明细数据 → 订单售后费用数据」原表。 @@ -25,6 +26,8 @@ class GoodsProfitAfsRepository /** @var array|null */ private ?array $fieldColumns = null; + private ?bool $hasDateLookup = null; + public function ready(): bool { try { @@ -101,10 +104,10 @@ class GoodsProfitAfsRepository $query = $this->filtered($filters, $columns)->select($select); if ($orderColumn !== null) { - $query->orderByRaw("STR_TO_DATE(REPLACE(`{$orderColumn}`, '/', '-'), '%Y-%m-%d %H:%i:%s') desc"); + $query->orderByRaw($this->dateExpression($orderColumn) . ' desc'); } - $records = $query->orderByDesc('id')->forPage($page, $limit + 1)->get(); + $records = $query->orderByDesc('id')->offset(($page - 1) * $limit)->limit($limit + 1)->get(); $numberKeys = array_flip((array) config('order_after_sales_cost.number_keys', [])); $rows = []; @@ -145,7 +148,7 @@ class GoodsProfitAfsRepository // 原表的订单时间是字符串(如 2026/8/23 14:58:51,不补零),不能直接和 ISO 日期做字符串比较。 if (($from !== '' || $to !== '') && isset($columns['order_time'])) { - $expression = "STR_TO_DATE(REPLACE(`{$columns['order_time']}`, '/', '-'), '%Y-%m-%d %H:%i:%s')"; + $expression = $this->dateExpression($columns['order_time']); if ($from !== '') { $query->whereRaw($expression . ' >= ?', [$from . ' 00:00:00']); @@ -186,6 +189,21 @@ class GoodsProfitAfsRepository return $query; } + private function dateExpression(string $column): string + { + // Dynamic schemas can move the source field. Keep the original parser + // until the matching additive lookup has been installed. + if ($column === 'undefined7') { + $this->hasDateLookup ??= Schema::connection($this->connectionName()) + ->hasColumn(self::MAIN_TABLE, GoodsProfitAfsLookupSchema::DATE_COLUMN); + if ($this->hasDateLookup) { + return '`' . GoodsProfitAfsLookupSchema::DATE_COLUMN . '`'; + } + } + + return "STR_TO_DATE(REPLACE(`{$column}`, '/', '-'), '%Y-%m-%d %H:%i:%s')"; + } + private function connection(): \Illuminate\Database\ConnectionInterface { return DB::connection($this->connectionName()); diff --git a/modules/EcommerceFinance/Repositories/WorkOrderMirrorRepository.php b/modules/EcommerceFinance/Repositories/WorkOrderMirrorRepository.php index d288d58c..8b3c0a3f 100644 --- a/modules/EcommerceFinance/Repositories/WorkOrderMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/WorkOrderMirrorRepository.php @@ -192,8 +192,7 @@ class WorkOrderMirrorRepository }); $this->applyAfterSalesFilters($query, $filters); - $total = (clone $query)->count(); - $rows = $query + $rows = (clone $query) ->select([ 'm.id', 'm.work_type', 'c.work_type_name', 'c.group_name', 'm.order_no', 'm.title', 'm.status', 'm.create_user', @@ -207,6 +206,10 @@ class WorkOrderMirrorRepository ->map(static fn (object $row): array => (array) $row) ->all(); + // An incomplete first page already gives the exact total. In particular, + // an empty alert panel must not scan the same form values a second time. + $total = $page === 1 && count($rows) < $perPage ? count($rows) : (clone $query)->count(); + $this->hydrateRelatedRows($rows); return [ @@ -282,7 +285,10 @@ class WorkOrderMirrorRepository private function whereFormValueLike(Builder $query, array $fieldCodes, string $value): void { $valueTable = $this->datasets->get(self::VALUE_DATASET)->targetTable(); - $query->whereExists(function (Builder $valueQuery) use ($valueTable, $fieldCodes, $value): void { + // A scalar LIMIT keeps this lookup correlated to the indexed parent. + // MariaDB otherwise materializes and scans the entire values table for + // the leading-wildcard text match, even for an empty alert panel. + $query->where(function (Builder $valueQuery) use ($valueTable, $fieldCodes, $value): void { $valueQuery->selectRaw('1') ->from($valueTable . ' AS filter_values') ->whereColumn('filter_values.main_order_no', 'm.order_no') @@ -290,8 +296,9 @@ class WorkOrderMirrorRepository ->whereRaw("filter_values.field_value LIKE ? ESCAPE '!'", [$this->contains($value)]) ->where(static function (Builder $active): void { $active->whereNull('filter_values.is_deleted')->orWhere('filter_values.is_deleted', 0); - }); - }); + }) + ->limit(1); + }, '=', 1); } /** @param list> $rows */ diff --git a/modules/EcommerceFinance/Services/BusinessMirrorSchemaManager.php b/modules/EcommerceFinance/Services/BusinessMirrorSchemaManager.php index 533f3c3d..b91ffefb 100644 --- a/modules/EcommerceFinance/Services/BusinessMirrorSchemaManager.php +++ b/modules/EcommerceFinance/Services/BusinessMirrorSchemaManager.php @@ -43,6 +43,7 @@ class BusinessMirrorSchemaManager } }); + $this->ensureDerivedLookups($dataset, $connection); return $columns; } @@ -84,9 +85,17 @@ class BusinessMirrorSchemaManager }); } + $this->ensureDerivedLookups($dataset, $connection); return $columns; } + private function ensureDerivedLookups(BusinessMirrorDataset $dataset, string $connection): void + { + if ($dataset->targetTable() === GoodsProfitAfsLookupSchema::TABLE) { + app(GoodsProfitAfsLookupSchema::class)->ensure(DB::connection($connection)); + } + } + /** @return list> */ public function columns(BusinessMirrorDataset $dataset): array { diff --git a/modules/EcommerceFinance/Services/GoodsProfitAfsLookupSchema.php b/modules/EcommerceFinance/Services/GoodsProfitAfsLookupSchema.php new file mode 100644 index 00000000..aa6a8366 --- /dev/null +++ b/modules/EcommerceFinance/Services/GoodsProfitAfsLookupSchema.php @@ -0,0 +1,75 @@ + ['_mirror_afs_order_time', 'id'], + 'idx_afs_shop_order_time_id' => ['undefined8', '_mirror_afs_order_time', 'id'], + ]; + + public function ensure(ConnectionInterface $db): void + { + if (! in_array($db->getDriverName(), ['mysql', 'mariadb'], true)) { + return; + } + + $schema = Schema::connection($db->getName()); + if (! $schema->hasTable(self::TABLE) + || ! $schema->hasColumns(self::TABLE, ['id', 'undefined7', 'undefined8'])) { + return; + } + + $statements = []; + if (! $schema->hasColumn(self::TABLE, self::DATE_COLUMN)) { + $expression = $this->dateExpression(); + // MariaDB requires the virtual column and its indexes in separate + // ALTER statements to allow concurrent writes with LOCK=NONE. + $statements[] = 'ADD COLUMN `' . self::DATE_COLUMN + . '` VARCHAR(19) CHARACTER SET ascii COLLATE ascii_bin GENERATED ALWAYS AS (' . $expression . ') VIRTUAL'; + } + $indexes = []; + foreach (self::INDEXES as $name => $columns) { + if (! $schema->hasIndex(self::TABLE, $name)) { + $indexes[] = 'ADD INDEX `' . $name . '` (`' . implode('`, `', $columns) . '`)'; + } + } + if ($indexes !== []) $statements[] = implode(', ', $indexes); + + if ($statements !== []) { + // Fail rather than silently copying/locking this multi-million-row table. + $wait = (int) $db->selectOne('SELECT @@SESSION.lock_wait_timeout AS seconds')->seconds; + $db->statement('SET SESSION lock_wait_timeout = 5'); + try { + foreach ($statements as $statement) { + $db->statement('ALTER TABLE `' . self::TABLE . '` ' . $statement . ', ALGORITHM=INPLACE, LOCK=NONE'); + } + } finally { + $db->statement('SET SESSION lock_wait_timeout = ' . $wait); + } + } + } + + public function dateExpression(): string + { + $raw = "REPLACE(TRIM(`undefined7`), '/', '-')"; + $pattern = '^[0-9]{1,4}-(0?[1-9]|1[0-2])-(0?[1-9]|[12][0-9]|3[01])' + . '([[:space:]]+([01]?[0-9]|2[0-3])(:[0-5]?[0-9]){0,2}([.][0-9]+)?)?$'; + + // Guard malformed strings so a future bad source value cannot break an + // indexed-column update in strict mode. Fractional seconds were already + // ignored by the original format. CHAR preserves its calendar semantics + // (e.g. 2026-02-31), unlike coercing the result into a DATETIME column. + return "CASE WHEN {$raw} REGEXP '{$pattern}' THEN CAST(STR_TO_DATE(" + . "SUBSTRING_INDEX({$raw}, '.', 1), '%Y-%m-%d %H:%i:%s') AS CHAR(19)) ELSE NULL END"; + } +} diff --git a/tests/Integration/GoodsProfitAfsLookupTest.php b/tests/Integration/GoodsProfitAfsLookupTest.php new file mode 100644 index 00000000..5ae1dc80 --- /dev/null +++ b/tests/Integration/GoodsProfitAfsLookupTest.php @@ -0,0 +1,89 @@ +markTestSkipped('Requires the isolated caiwu_afs_generated_test MariaDB fixture.'); + } + config(['database.connections.afs_lookup_fixture' => [ + 'driver' => 'mysql', 'host' => 'caiwu_afs_generated_test', 'database' => 'qa_integration', + 'username' => 'root', 'password' => '', 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', + 'prefix' => '', 'strict' => true, + ], 'upstream_mirrors.connection' => 'afs_lookup_fixture', 'system_database.mode' => 'shared']); + $db = DB::connection('afs_lookup_fixture'); + $this->assertSame('qa_integration', $db->selectOne('SELECT DATABASE() AS name')->name); + $schema = Schema::connection('afs_lookup_fixture'); + $schema->dropIfExists(GoodsProfitAfsLookupSchema::TABLE); + $schema->create(GoodsProfitAfsLookupSchema::TABLE, function (Blueprint $table): void { + $table->char('_mirror_key', 64)->primary(); + $table->integer('id'); $table->string('undefined7', 50)->nullable(); + $table->string('undefined8', 50)->nullable(); $table->string('amount', 50)->nullable(); + }); + try { + $rawDates = ['2026/8/23 14:58:51', '2026-10-19 23:59:59', '2026/10/20 0:0:0', + '2026-10-19', '2026/10/19 2:3:4', '2026/10/19 00:00:00.123', + '2026-10-19 01', '2026-10-19 01:02', '2026/2/31 00:00:00', + null, '', 'not a date', '2026/99/99 50:00:00']; + foreach ($rawDates as $id => $raw) { + $db->table(GoodsProfitAfsLookupSchema::TABLE)->insert([ + '_mirror_key' => hash('sha256', (string) $id), 'id' => $id, 'undefined7' => $raw, + 'undefined8' => 'fixture shop', 'amount' => '-31.20', + ]); + } + $before = $db->table(GoodsProfitAfsLookupSchema::TABLE)->orderBy('id')->get()->toJson(); + $migration = require base_path('database/migrations/2026_10_22_150000_index_goods_profit_afs_order_time.php'); + $migration->up(); + $migration->up(); + $this->assertTrue($schema->hasIndex(GoodsProfitAfsLookupSchema::TABLE, 'idx_afs_order_time_id')); + $rows = $db->select('SELECT id, `_mirror_afs_order_time` AS indexed_date, ' + . "CAST(STR_TO_DATE(REPLACE(`undefined7`, '/', '-'), '%Y-%m-%d %H:%i:%s') AS CHAR(19)) AS original_date " + . 'FROM `' . GoodsProfitAfsLookupSchema::TABLE . '` ORDER BY id'); + foreach ($rows as $row) { + $this->assertSame($row->original_date, $row->indexed_date, 'date fixture ' . $row->id); + } + $db->table(GoodsProfitAfsLookupSchema::TABLE)->where('id', 0)->update(['undefined7' => '2026/10/19 1:2:3']); + $this->assertSame('2026-10-19 01:02:03', $db->table(GoodsProfitAfsLookupSchema::TABLE)->where('id', 0)->value('_mirror_afs_order_time')); + $db->table(GoodsProfitAfsLookupSchema::TABLE)->where('id', 0)->update(['undefined7' => 'bad timestamp']); + $this->assertNull($db->table(GoodsProfitAfsLookupSchema::TABLE)->where('id', 0)->value('_mirror_afs_order_time')); + $db->table(GoodsProfitAfsLookupSchema::TABLE)->where('id', 0)->update(['undefined7' => $rawDates[0]]); + $migration->down(); + $this->assertSame($before, $db->table(GoodsProfitAfsLookupSchema::TABLE)->orderBy('id')->get()->toJson()); + + // The same indexes must also exist when a new mirror is created + // after this migration has already been recorded. + $schema->drop(GoodsProfitAfsLookupSchema::TABLE); + config(['upstream_mirrors.datasets' => ['fixture.rpt.afs' => [ + 'source_key' => 'fixture', 'schema' => 'rpt', 'object' => 'afs', + 'target' => GoodsProfitAfsLookupSchema::TABLE, 'keys' => ['id'], 'watermark' => null, + ]]]); + foreach (['id' => 'int', 'undefined7' => 'nvarchar', 'undefined8' => 'nvarchar'] as $column => $type) { + DB::table('upstream_schema_columns')->insert([ + 'source_key' => 'fixture', 'schema_name' => 'rpt', 'object_name' => 'afs', 'object_type' => 'table', + 'column_name' => $column, 'ordinal_position' => $column === 'id' ? 1 : (int) substr($column, 9), + 'data_type' => $type, 'max_length' => 50, 'is_nullable' => true, 'synchronized_at' => now(), + 'created_at' => now(), 'updated_at' => now(), + ]); + } + $dataset = (new BusinessMirrorDatasetRegistry())->get('fixture.rpt.afs'); + app(BusinessMirrorSchemaManager::class)->ensure($dataset); + app(BusinessMirrorSchemaManager::class)->ensure($dataset); + $this->assertTrue($schema->hasIndex(GoodsProfitAfsLookupSchema::TABLE, 'idx_afs_shop_order_time_id')); + } finally { + $schema->dropIfExists(GoodsProfitAfsLookupSchema::TABLE); + DB::purge('afs_lookup_fixture'); + } + } +} diff --git a/tests/Unit/EcommerceFinance/GoodsProfitAfsRepositoryTest.php b/tests/Unit/EcommerceFinance/GoodsProfitAfsRepositoryTest.php new file mode 100644 index 00000000..17241123 --- /dev/null +++ b/tests/Unit/EcommerceFinance/GoodsProfitAfsRepositoryTest.php @@ -0,0 +1,110 @@ + [ + 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', + ], 'upstream_mirrors.connection' => 'business_mirror']); + DB::purge('business_mirror'); + $schema = Schema::connection('business_mirror'); + $schema->create(GoodsProfitAfsLookupSchema::TABLE, function (Blueprint $table): void { + $table->integer('id')->primary(); + foreach (['undefined1', 'undefined2', 'undefined7', 'undefined8', 'undefined10', 'undefined25', '_mirror_afs_order_time'] as $column) { + $table->string($column)->nullable(); + } + }); + $schema->create('ops_jst_goods_profit_kpi_items_afs_schemas', function (Blueprint $table): void { + $table->integer('id'); $table->string('column'); $table->string('name'); + }); + $schema->create('business_mirror_table_states', function (Blueprint $table): void { + $table->string('dataset_key'); $table->dateTime('initial_completed_at')->nullable(); + }); + $db = DB::connection('business_mirror'); + $db->table('business_mirror_table_states')->insert([ + 'dataset_key' => GoodsProfitAfsRepository::MAIN_DATASET, 'initial_completed_at' => '2026-10-01 00:00:00', + ]); + foreach (['undefined1' => '内部订单号', 'undefined2' => '线上订单号', 'undefined7' => '订单时间', + 'undefined8' => '店铺名称', 'undefined10' => '商品编码', 'undefined25' => '商品金额'] as $column => $name) { + $db->table('ops_jst_goods_profit_kpi_items_afs_schemas')->insert(['id' => (int) substr($column, 9), 'column' => $column, 'name' => $name]); + } + $db->getPdo()->sqliteCreateFunction('STR_TO_DATE', static function (?string $date): ?string { + return $date === null || trim($date) === '' ? null : date('Y-m-d H:i:s', strtotime($date)); + }); + for ($id = 1; $id <= 60; $id++) { + $db->table(GoodsProfitAfsLookupSchema::TABLE)->insert([ + 'id' => $id, 'undefined1' => 'ORDER-' . $id, 'undefined2' => 'ONLINE-' . $id, + 'undefined7' => sprintf('2026/10/19 1:%d:00', $id - 1), + '_mirror_afs_order_time' => sprintf('2026-10-19 01:%02d:00', $id - 1), + 'undefined8' => $id % 2 ? '店铺甲' : '店铺乙', 'undefined10' => 'SKU_1', 'undefined25' => '123.45', + ]); + } + } + + public function test_next_page_does_not_skip_the_lookahead_row(): void + { + $repo = new GoodsProfitAfsRepository(); + $filters = ['from' => '2026-10-19', 'to' => '2026-10-19']; + $pages = array_map(fn ($page) => $repo->paginate($filters, $page, 25), [1, 2, 3]); + $orders = array_merge(...array_map(fn ($page) => array_column($page['rows'], 'internal_order_no'), $pages)); + + $this->assertSame(array_map(fn ($id) => 'ORDER-' . $id, range(60, 1)), $orders); + $this->assertSame([true, true, false], array_column($pages, 'has_more')); + $this->assertSame(123.45, $pages[0]['rows'][0]['product_amount']); + } + + public function test_date_boundaries_and_multi_shop_filters_preserve_values(): void + { + $db = DB::connection('business_mirror'); + foreach ([61 => ['2026/10/19 23:59:59', '2026-10-19 23:59:59'], + 62 => ['2026/10/20 0:00:00', '2026-10-20 00:00:00'], + 63 => ['2026/8/23 14:58:51', '2026-08-23 14:58:51']] as $id => [$raw, $parsed]) { + $db->table(GoodsProfitAfsLookupSchema::TABLE)->insert([ + 'id' => $id, 'undefined1' => 'ORDER-' . $id, 'undefined7' => $raw, + '_mirror_afs_order_time' => $parsed, 'undefined8' => '店铺甲', 'undefined25' => '-31.20', + ]); + } + $db->enableQueryLog(); + $result = (new GoodsProfitAfsRepository())->paginate([ + 'from' => '2026-10-19', 'to' => '2026-10-19', 'shop_names' => ['店铺甲', '店铺乙'], + ], 1, 100); + $this->assertCount(61, $result['rows']); + $this->assertSame('ORDER-61', $result['rows'][0]['internal_order_no']); + $this->assertSame(-31.2, $result['rows'][0]['product_amount']); + $this->assertStringNotContainsString('STR_TO_DATE', implode(' ', array_column($db->getQueryLog(), 'query'))); + } + + public function test_missing_lookup_keeps_the_original_parser(): void + { + Schema::connection('business_mirror')->table(GoodsProfitAfsLookupSchema::TABLE, function (Blueprint $table): void { + $table->dropColumn('_mirror_afs_order_time'); + }); + $result = (new GoodsProfitAfsRepository())->paginate(['from' => '2026-10-19', 'to' => '2026-10-19'], 1, 25); + $this->assertCount(25, $result['rows']); + $this->assertSame('ORDER-60', $result['rows'][0]['internal_order_no']); + } + + public function test_moved_dynamic_header_does_not_use_the_old_lookup_column(): void + { + Schema::connection('business_mirror')->table(GoodsProfitAfsLookupSchema::TABLE, function (Blueprint $table): void { + $table->string('undefined9')->nullable(); + }); + $db = DB::connection('business_mirror'); + $db->table(GoodsProfitAfsLookupSchema::TABLE)->update(['undefined9' => '2026/8/23 14:58:51']); + $db->table('ops_jst_goods_profit_kpi_items_afs_schemas')->where('name', '订单时间')->update(['column' => 'undefined9']); + $result = (new GoodsProfitAfsRepository())->paginate(['from' => '2026-08-23', 'to' => '2026-08-23'], 1, 25); + $this->assertCount(25, $result['rows']); + $this->assertSame('2026/8/23 14:58:51', $result['rows'][0]['order_time']); + } +} diff --git a/tests/Unit/EcommerceFinance/WorkOrderMirrorRepositoryTest.php b/tests/Unit/EcommerceFinance/WorkOrderMirrorRepositoryTest.php index e613f5c7..d2270d13 100644 --- a/tests/Unit/EcommerceFinance/WorkOrderMirrorRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/WorkOrderMirrorRepositoryTest.php @@ -150,6 +150,36 @@ class WorkOrderMirrorRepositoryTest extends TestCase $this->assertFalse($result['sync_status']['datasets']['sub']['ready']); } + public function test_empty_after_sales_panel_runs_one_filtered_query_without_a_count(): void + { + $db = DB::connection('business_mirror'); + $db->enableQueryLog(); + $result = $this->repository->paginateAfterSales(1, 10, ['shop_name' => '不存在的店铺']); + $queries = array_values(array_filter($db->getQueryLog(), fn ($query) => str_contains($query['query'], 'filter_values'))); + + $this->assertSame(0, $result['total']); + $this->assertSame([], $result['data']); + $this->assertCount(1, $queries); + $this->assertStringNotContainsString('count(*)', $queries[0]['query']); + $this->assertStringContainsString('limit 1) = ?', $queries[0]['query']); + } + + public function test_after_sales_full_pages_still_return_the_exact_total(): void + { + DB::connection('business_mirror')->table('fixture_work_order_config')->where('id', 1) + ->update(['work_type_name' => '售后预警']); + $first = $this->repository->paginateAfterSales(1, 1); + $second = $this->repository->paginateAfterSales(2, 1); + $empty = $this->repository->paginateAfterSales(3, 1); + + $this->assertSame(2, $first['total']); + $this->assertSame(2, $second['total']); + $this->assertSame(2, $empty['total']); + $this->assertSame('WO-002', $first['data'][0]['order_no']); + $this->assertSame('WO-001', $second['data'][0]['order_no']); + $this->assertSame([], $empty['data']); + } + private function definition(string $object, string $target, array $keys, ?string $watermark): array { return [ -- 2.47.2