From 806593787b8a3966ee8e6c57be7b1845bf06adbd Mon Sep 17 00:00:00 2001 From: chenxi Date: Mon, 28 Sep 2026 13:22:08 +0800 Subject: [PATCH] Add warehouse short names to inventory report --- app/Business/InventoryWarehouseShortNames.php | 35 ++++++ app/Http/Controllers/Business/Pages.php | 13 ++- app/Jobs/Common/InventoryReportExport.php | 9 +- config/business_navigation.php | 1 + .../pages/partials/directory-table.blade.php | 34 +++++- .../finance-table-interactions.blade.php | 13 ++- tests/Feature/Business/PagesTest.php | 107 +++++++++++++++++- 7 files changed, 204 insertions(+), 8 deletions(-) create mode 100644 app/Business/InventoryWarehouseShortNames.php diff --git a/app/Business/InventoryWarehouseShortNames.php b/app/Business/InventoryWarehouseShortNames.php new file mode 100644 index 00000000..12a8025a --- /dev/null +++ b/app/Business/InventoryWarehouseShortNames.php @@ -0,0 +1,35 @@ + */ + public function forCompany(int $companyId): array + { + return InventoryWarehouseNameMapping::allCompanies() + ->companyId($companyId) + ->get(['warehouse_provider', 'warehouse', 'warehouse_short_name']) + ->mapWithKeys(static fn (InventoryWarehouseNameMapping $mapping): array => [ + self::key($mapping->warehouse_provider, $mapping->warehouse) => $mapping->warehouse_short_name, + ])->all(); + } + + /** @param array $names */ + public function fill(object $row, array $names): object + { + $row->warehouse_short_name = $names[self::key( + (string) ($row->warehouse_provider ?? ''), + (string) ($row->warehouse ?? ''), + )] ?? ''; + + return $row; + } + + private static function key(string $provider, string $warehouse): string + { + return $provider . "\0" . $warehouse; + } +} diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 8e6ed37a..283d62a8 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -4,6 +4,7 @@ namespace App\Http\Controllers\Business; use App\Business\BusinessTableImporter; use App\Business\InventoryWarehouseNameMappingWorkbookImporter; +use App\Business\InventoryWarehouseShortNames; use App\Business\CourierPayableSummaryFilter; use App\Business\CourierPayableSummaryStore; use App\Business\FundForecastTemplate; @@ -531,8 +532,11 @@ class Pages extends Controller $perPage, ); + $shortNames = app(InventoryWarehouseShortNames::class); + $names = $shortNames->forCompany((int) (company_id() ?: 1)); + return [new LengthAwarePaginator( - $result['data'], + array_map(static fn (object $row): object => $shortNames->fill($row, $names), $result['data']), $result['total'], $perPage, $page, @@ -1520,7 +1524,7 @@ class Pages extends Controller if ($scope === 'all' && should_queue()) { $fileName = Str::filename('进销存报表') . '-' . now()->format('Ymd_His') . '-' . Str::random(8) . '.csv'; - dispatch(new InventoryReportExport(user(), $filters, $columns, $fileName))->onQueue('exports'); + dispatch(new InventoryReportExport(user(), $filters, $columns, $fileName, (int) (company_id() ?: 1)))->onQueue('exports'); flash('进销存报表已提交后台生成,完成后可从通知中心下载。')->success(); return back(); @@ -1533,7 +1537,7 @@ class Pages extends Controller // download connection. The job stores the completed file and // raises the existing notification when it is ready. $fileName = Str::filename('进销存报表') . '-' . now()->format('Ymd_His') . '-' . Str::random(8) . '.csv'; - dispatch(new InventoryReportExport(user(), $filters, $columns, $fileName))->afterResponse(); + dispatch(new InventoryReportExport(user(), $filters, $columns, $fileName, (int) (company_id() ?: 1)))->afterResponse(); flash('进销存报表已提交后台生成,完成后可从通知中心下载。')->success(); return back(); @@ -1561,8 +1565,11 @@ class Pages extends Controller $rows = $scope === 'page' ? $this->thirdPartyWarehouseStorage->paginateMonthlyInventoryReport($filters, $page, $perPage, false)['data'] : $this->thirdPartyWarehouseStorage->exportMonthlyInventoryReportRows($filters); + $shortNames = app(InventoryWarehouseShortNames::class); + $names = $shortNames->forCompany((int) (company_id() ?: 1)); $written = 0; foreach ($rows as $row) { + $row = $shortNames->fill($row, $names); fputcsv($csv, array_map(function (array $column) use ($row): mixed { $value = data_get($row, $column['name']); diff --git a/app/Jobs/Common/InventoryReportExport.php b/app/Jobs/Common/InventoryReportExport.php index a23fab2c..f566f45a 100644 --- a/app/Jobs/Common/InventoryReportExport.php +++ b/app/Jobs/Common/InventoryReportExport.php @@ -3,6 +3,7 @@ namespace App\Jobs\Common; use App\Abstracts\JobShouldQueue; +use App\Business\InventoryWarehouseShortNames; use App\Notifications\Common\ExportFailed; use Illuminate\Support\Facades\File; use Modules\EcommerceFinance\Repositories\ThirdPartyWarehouseStorageMirrorRepository; @@ -15,16 +16,20 @@ class InventoryReportExport extends JobShouldQueue public int $tries = 1; + protected int $company_id = 1; + public function __construct( protected $user, protected array $filters, protected array $columns, protected string $file_name, + ?int $companyId = null, ) { + $this->company_id = $companyId ?? 1; $this->onQueue('exports'); } - public function handle(ThirdPartyWarehouseStorageMirrorRepository $repository): void + public function handle(ThirdPartyWarehouseStorageMirrorRepository $repository, InventoryWarehouseShortNames $shortNames): void { $path = storage_path('app/temp/' . $this->file_name); File::ensureDirectoryExists(dirname($path)); @@ -37,7 +42,9 @@ class InventoryReportExport extends JobShouldQueue fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF)); fputcsv($csv, array_column($this->columns, 'label')); + $names = $shortNames->forCompany($this->company_id); foreach ($repository->exportMonthlyInventoryReportRows($this->filters) as $row) { + $row = $shortNames->fill($row, $names); fputcsv($csv, array_map(function (array $column) use ($row): mixed { $value = data_get($row, $column['name']); diff --git a/config/business_navigation.php b/config/business_navigation.php index 355fca4d..dadff23d 100644 --- a/config/business_navigation.php +++ b/config/business_navigation.php @@ -366,6 +366,7 @@ $navigation = [ ['name' => 'month', 'label' => '月份', 'kind' => 'date'], ['name' => 'warehouse_provider', 'label' => '仓储方'], ['name' => 'warehouse', 'label' => '仓库'], + ['name' => 'warehouse_short_name', 'label' => '仓库简称'], ['name' => 'product_code', 'label' => '商品编码'], ['name' => 'category', 'label' => '分类'], ['name' => 'opening_quantity', 'label' => '期初数量', 'kind' => 'integer'], diff --git a/resources/views/business/pages/partials/directory-table.blade.php b/resources/views/business/pages/partials/directory-table.blade.php index 658ed8eb..cbac72c8 100644 --- a/resources/views/business/pages/partials/directory-table.blade.php +++ b/resources/views/business/pages/partials/directory-table.blade.php @@ -490,6 +490,8 @@ .directory-sort-link:hover { color: var(--vip-content-accent-dark, #856632); } .directory-sort-icon { width: 1rem; height: 1rem; color: var(--vip-content-muted, #595959); font-size: 1rem; line-height: 1; } .directory-sort-link[aria-current="true"] .directory-sort-icon { color: var(--vip-content-accent-dark, #856632); } + .directory-inventory-sort { display: inline-flex; align-items: center; gap: 0.25rem; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; cursor: pointer; } + .directory-inventory-sort:hover, .directory-inventory-sort:focus-visible { color: var(--vip-content-accent-dark, #856632); } .directory-header-menu { position: relative; display: inline-flex; align-items: center; gap: 0.15rem; } .directory-header-menu summary { display: inline-flex; align-items: center; cursor: pointer; list-style: none; } .directory-header-menu summary::-webkit-details-marker { display: none; } @@ -1295,7 +1297,7 @@ # @foreach ($directoryFields as $field) - + @if ($directoryUsesFieldQuery) @php $isSorted = request('sort') === $field['name']; @@ -1313,6 +1315,8 @@ + @elseif ($isInventoryReportPage && $field['name'] === 'warehouse_short_name') + @else {{ $field['label'] }} @endif @@ -1362,7 +1366,7 @@ @endif @else - {{ filled($display) ? $display : '—' }} + {{ filled($display) ? $display : ($isInventoryReportPage && $field['name'] === 'warehouse_short_name' ? '' : '—') }} @endif @endforeach @@ -1789,6 +1793,22 @@ const table = tableScope?.querySelector('.directory-table') || section?.querySelector('.directory-table'); const search = tools.querySelector('[data-directory-search]'); if (!table || !search) return; + const shortNameSort = table.querySelector('[data-inventory-short-name-sort]'); + shortNameSort?.addEventListener('click', () => { + const header = shortNameSort.closest('th'); + const ascending = header.getAttribute('aria-sort') !== 'ascending'; + const rows = [...table.tBodies[0].querySelectorAll('tr:not(.is-empty)')]; + rows.sort((left, right) => { + const a = left.querySelector('[data-column-key="warehouse_short_name"]')?.textContent.trim() || ''; + const b = right.querySelector('[data-column-key="warehouse_short_name"]')?.textContent.trim() || ''; + if (!a) return b ? 1 : 0; + if (!b) return -1; + return a.localeCompare(b, 'zh-Hans-CN') * (ascending ? 1 : -1); + }).forEach((row) => table.tBodies[0].appendChild(row)); + header.setAttribute('aria-sort', ascending ? 'ascending' : 'descending'); + shortNameSort.setAttribute('aria-label', `仓库简称按当前页${ascending ? '降序' : '升序'}排序`); + shortNameSort.querySelector('.directory-sort-icon').textContent = ascending ? 'arrow_upward' : 'arrow_downward'; + }); const picker = tools.querySelector('[data-directory-field-picker]'); const toggle = picker?.querySelector('[data-directory-field-toggle]'); const panel = picker?.querySelector('.directory-field-picker__panel'); @@ -1848,6 +1868,16 @@ const saved = JSON.parse(localStorage.getItem(storageKey) || 'null'); const savedOrder = Array.isArray(saved) ? saved : saved?.order; const savedSelected = Array.isArray(saved) ? saved : saved?.selected; + if (table.id === 'inventory-report-total-table' && !localStorage.getItem(`${storageKey}:warehouse-short-name-v1`)) { + if (Array.isArray(savedOrder) && !savedOrder.includes('warehouse_short_name')) { + savedOrder.splice(savedOrder.indexOf('warehouse') + 1, 0, 'warehouse_short_name'); + } + if (Array.isArray(savedSelected) && !savedSelected.includes('warehouse_short_name')) { + savedSelected.push('warehouse_short_name'); + } + if (saved) localStorage.setItem(storageKey, JSON.stringify({ order: savedOrder, selected: savedSelected })); + localStorage.setItem(`${storageKey}:warehouse-short-name-v1`, '1'); + } if (Array.isArray(savedSelected)) checks.forEach((check) => { check.checked = savedSelected.includes(check.value); }); if (Array.isArray(savedOrder)) savedOrder.forEach((key) => { const option = picker.querySelector(`[data-directory-field-option] input[value="${CSS.escape(key)}"]`)?.closest('[data-directory-field-option]'); diff --git a/resources/views/business/pages/partials/finance-table-interactions.blade.php b/resources/views/business/pages/partials/finance-table-interactions.blade.php index 3c60c91f..fe1ffd50 100644 --- a/resources/views/business/pages/partials/finance-table-interactions.blade.php +++ b/resources/views/business/pages/partials/finance-table-interactions.blade.php @@ -558,8 +558,19 @@ }; try { const savedVisibility = JSON.parse(localStorage.getItem(storageKey(table, 'visibility')) || 'null'); - if (Array.isArray(savedVisibility)) checks.forEach((check) => { if (!check.disabled) check.checked = savedVisibility.includes(check.value); }); const savedOrder = JSON.parse(localStorage.getItem(storageKey(table, 'order')) || 'null'); + if (table.id === 'inventory-report-total-table' && !localStorage.getItem(storageKey(table, 'warehouse-short-name-v1'))) { + if (Array.isArray(savedOrder) && !savedOrder.includes('warehouse_short_name')) { + savedOrder.splice(savedOrder.indexOf('warehouse') + 1, 0, 'warehouse_short_name'); + localStorage.setItem(storageKey(table, 'order'), JSON.stringify(savedOrder)); + } + if (Array.isArray(savedVisibility) && !savedVisibility.includes('warehouse_short_name')) { + savedVisibility.push('warehouse_short_name'); + localStorage.setItem(storageKey(table, 'visibility'), JSON.stringify(savedVisibility)); + } + localStorage.setItem(storageKey(table, 'warehouse-short-name-v1'), '1'); + } + if (Array.isArray(savedVisibility)) checks.forEach((check) => { if (!check.disabled) check.checked = savedVisibility.includes(check.value); }); applyOrder(Array.isArray(savedOrder) ? savedOrder : defaults, false); } catch (_) {} setVisibility(table, checks, false); diff --git a/tests/Feature/Business/PagesTest.php b/tests/Feature/Business/PagesTest.php index 6f48ae95..d665a7a0 100644 --- a/tests/Feature/Business/PagesTest.php +++ b/tests/Feature/Business/PagesTest.php @@ -4,6 +4,7 @@ namespace Tests\Feature\Business; use App\Models\Auth\Permission; use App\Models\Business\InventoryWarehouseNameMapping; +use App\Business\InventoryWarehouseShortNames; use App\Jobs\Common\InventoryReportExport; use Illuminate\Support\Facades\Queue; use Mockery; @@ -95,6 +96,46 @@ class PagesTest extends FeatureTestCase $this->assertLessThan($mappingPanelStart, $filterPosition); } + public function testInventoryReportShowsWarehouseShortNameOnlyForExactProviderAndWarehouse(): void + { + InventoryWarehouseNameMapping::query()->create([ + 'company_id' => 1, + 'warehouse_provider' => '测试仓储方', + 'warehouse' => '测试主仓', + 'warehouse_short_name' => '崔桥主仓', + ]); + $repository = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class); + $repository->shouldReceive('available')->once()->andReturnTrue(); + $repository->shouldReceive('allWarehousesReady')->once()->andReturnTrue(); + $repository->shouldReceive('paginateMonthlyInventoryReport')->once()->andReturn([ + 'data' => [ + (object) ['warehouse_provider' => '测试仓储方', 'warehouse' => '测试主仓', 'product_code' => 'MATCHED'], + (object) ['warehouse_provider' => '其他仓储方', 'warehouse' => '测试主仓', 'product_code' => 'UNMATCHED'], + ], + 'total' => 2, + 'state' => ['status' => 'succeeded'], + 'sync' => ['code' => 'healthy'], + ]); + $this->app->instance(ThirdPartyWarehouseStorageMirrorRepository::class, $repository); + + $response = $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'product-inventory', 'page' => 'inventory-report', 'month' => '2026-08', + ])); + + $response->assertOk() + ->assertSee('data-column-key="warehouse_short_name"', false) + ->assertSee('data-inventory-short-name-sort', false) + ->assertSee('value="warehouse_short_name"', false) + ->assertSee('崔桥主仓'); + $html = $response->getContent(); + $this->assertLessThan( + strpos($html, 'data-column-key="warehouse_short_name"'), + strpos($html, 'data-column-key="warehouse"'), + ); + $this->assertMatchesRegularExpression('/data-column-key="warehouse_short_name"[^>]*>\s*崔桥主仓\s*<\/td>/', $html); + $this->assertMatchesRegularExpression('/data-column-key="warehouse_short_name"[^>]*>\s*<\/td>/', $html); + } + public function testInventoryReportKeepsJulyMonthFilter(): void { $repository = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class); @@ -168,7 +209,7 @@ class PagesTest extends FeatureTestCase $content = $response->streamedContent(); $this->assertSame((string) strlen($content), $response->headers->get('Content-Length')); $this->assertStringStartsWith(chr(0xEF) . chr(0xBB) . chr(0xBF), $content); - $this->assertStringContainsString('货主,月份,仓储方,仓库,商品编码,分类,期初数量,期末数量', $content); + $this->assertStringContainsString('货主,月份,仓储方,仓库,仓库简称,商品编码,分类,期初数量,期末数量', $content); $this->assertStringContainsString("'121630-49", $content); } @@ -199,6 +240,37 @@ class PagesTest extends FeatureTestCase $this->assertSame("\xEF\xBB\xBF商品编码,仓库,期初数量\n'121630-49,主仓,10\n", $response->streamedContent()); } + public function testInventoryReportExportIncludesMappedShortNameAndLeavesUnmatchedBlank(): void + { + InventoryWarehouseNameMapping::query()->create([ + 'company_id' => 1, + 'warehouse_provider' => '测试仓储方', + 'warehouse' => '主仓', + 'warehouse_short_name' => '测试简称', + ]); + $repository = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class); + $repository->shouldReceive('available')->once()->andReturnTrue(); + $repository->shouldReceive('allWarehousesReady')->once()->andReturnTrue(); + $repository->shouldReceive('paginateMonthlyInventoryReport')->once()->andReturn([ + 'data' => [ + (object) ['warehouse_provider' => '测试仓储方', 'warehouse' => '主仓'], + (object) ['warehouse_provider' => '其他仓储方', 'warehouse' => '主仓'], + ], + ]); + $this->app->instance(ThirdPartyWarehouseStorageMirrorRepository::class, $repository); + + $response = $this->loginAs()->get(route('business.product-inventory.inventory-report.export', [ + 'month' => '2026-08', 'scope' => 'page', + 'columns' => 'warehouse,warehouse_short_name,warehouse_provider', + ])); + + $response->assertOk()->assertDownload(); + $this->assertSame( + "\xEF\xBB\xBF仓库,仓库简称,仓储方\n主仓,测试简称,测试仓储方\n主仓,,其他仓储方\n", + $response->streamedContent(), + ); + } + public function testInventoryReportCurrentPageExportDoesNotReadAllFilteredRows(): void { $repository = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class); @@ -259,6 +331,39 @@ class PagesTest extends FeatureTestCase Queue::assertPushed(InventoryReportExport::class); } + public function testInventoryReportBackgroundExportWritesWarehouseShortName(): void + { + Queue::fake(); + InventoryWarehouseNameMapping::query()->create([ + 'company_id' => 1, + 'warehouse_provider' => '后台仓储方', + 'warehouse' => '后台仓库', + 'warehouse_short_name' => '后台简称', + ]); + $repository = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class); + $repository->shouldReceive('exportMonthlyInventoryReportRows')->once()->andReturn( + (static function (): \Generator { + yield (object) ['warehouse_provider' => '后台仓储方', 'warehouse' => '后台仓库']; + })(), + ); + $fileName = 'inventory-short-name-test-' . uniqid() . '.csv'; + $path = storage_path('app/temp/' . $fileName); + + try { + (new InventoryReportExport( + $this->user, + ['month' => '2026-08'], + [['name' => 'warehouse_short_name', 'label' => '仓库简称']], + $fileName, + 1, + ))->handle($repository, app(InventoryWarehouseShortNames::class)); + + $this->assertSame("\xEF\xBB\xBF仓库简称\n后台简称\n", file_get_contents($path)); + } finally { + @unlink($path); + } + } + public function testInventoryReportExportRejectsFieldsOutsideThePageSchema(): void { $repository = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class); -- 2.47.2