Merge inventory export improvements

This commit is contained in:
chenxi 2026-09-25 22:44:59 +08:00
commit 39885bccea
5 changed files with 165 additions and 23 deletions

View File

@ -1319,9 +1319,28 @@ class Pages extends Controller
$filters = $this->inventoryReportFilters($request);
$productInventory = collect(config('business_navigation'))->firstWhere('slug', 'product-inventory');
$inventoryPage = collect($productInventory['pages'] ?? [])->firstWhere('slug', 'inventory-report');
$columns = $inventoryPage['directory']['fields'] ?? [];
$availableColumns = collect($inventoryPage['directory']['fields'] ?? [])
->reject(static fn (array $column): bool => in_array($column['kind'] ?? '', ['secret', 'password'], true))
->keyBy('name');
$requestedColumnsParam = $request->query('columns', '');
abort_unless(is_string($requestedColumnsParam), 422);
$requestedColumns = trim($requestedColumnsParam);
$columns = $availableColumns->values()->all();
if ($requestedColumns !== '') {
$names = explode(',', $requestedColumns);
abort_if(count($names) > $availableColumns->count() || count($names) !== count(array_unique($names)), 422);
$columns = [];
foreach ($names as $name) {
abort_unless($availableColumns->has($name), 422);
$columns[] = $availableColumns->get($name);
}
}
$scope = $request->query('scope', 'all');
abort_unless(in_array($scope, ['all', 'page'], true), 422);
$page = max(1, $request->integer('page', 1));
$perPage = min(max((int) setting('default.list_limit', 25), 1), 100);
return response()->streamDownload(function () use ($filters, $columns): void {
return response()->streamDownload(function () use ($filters, $columns, $scope, $page, $perPage): void {
set_time_limit(0);
$csv = fopen('php://output', 'w');
if ($csv === false) {
@ -1331,7 +1350,10 @@ class Pages extends Controller
fputs($csv, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($csv, array_column($columns, 'label'));
$written = 0;
foreach ($this->thirdPartyWarehouseStorage->exportMonthlyInventoryReportRows($filters) as $row) {
$rows = $scope === 'page'
? $this->thirdPartyWarehouseStorage->paginateMonthlyInventoryReport($filters, $page, $perPage, false)['data']
: $this->thirdPartyWarehouseStorage->exportMonthlyInventoryReportRows($filters);
foreach ($rows as $row) {
fputcsv($csv, array_map(function (array $column) use ($row): mixed {
$value = data_get($row, $column['name']);

View File

@ -305,6 +305,7 @@ class ThirdPartyWarehouseStorageMirrorRepository
int $perPage,
bool $includeTotal = true,
?array $state = null,
?array $sourceCounts = null,
): array
{
$state ??= $this->requireReadyState();
@ -339,6 +340,7 @@ class ThirdPartyWarehouseStorageMirrorRepository
$includeTotal,
$state,
$authorityIsCurrentMonth,
$sourceCounts,
);
$rolledForward = $includeTotal && $perPage <= 100 && $authority !== null
? $this->rememberMonthlyInventoryReport(
@ -553,6 +555,7 @@ class ThirdPartyWarehouseStorageMirrorRepository
$batchSize = min(max($batchSize, 1), 5000);
$page = 1;
$state = $this->requireReadyState();
$sourceCounts = null;
while (true) {
$result = $this->paginateMonthlyInventoryReport(
@ -561,8 +564,13 @@ class ThirdPartyWarehouseStorageMirrorRepository
$batchSize,
false,
$state,
$sourceCounts,
);
if (isset($result['source_counts']) && is_array($result['source_counts'])) {
$sourceCounts = $result['source_counts'];
}
$rows = $result['data'] ?? [];
if ($rows === []) {
return;
@ -651,6 +659,7 @@ class ThirdPartyWarehouseStorageMirrorRepository
bool $includeTotal,
array $state,
bool $authorityIsCurrentMonth = false,
?array $sourceCounts = null,
): ?array {
try {
$latestProducts = $this->connection->table(self::PRODUCT_TABLE)
@ -825,7 +834,7 @@ class ThirdPartyWarehouseStorageMirrorRepository
[$inventoryDimensions, $inventoryDimensions, 'w.name', 'inventory.sku_code'],
[$movementDimensions, $movementCount, 'movement_warehouse.name', 'movement_pair.sku_code'],
];
$counts = [];
$counts = is_array($sourceCounts) ? array_values($sourceCounts) : [];
$total = 0;
if ($includeTotal) {
$countCacheKey = $this->monthlyInventoryReportCacheKey(
@ -842,6 +851,13 @@ class ThirdPartyWarehouseStorageMirrorRepository
Cache::put($countCacheKey, $counts, self::REPORT_CACHE_SECONDS);
}
$total = array_sum($counts);
} elseif ($counts === []) {
// The exporter walks the same ordered source pages repeatedly. Count
// each source once and pass the result into later batches instead of
// re-running the candidate counts for every page.
foreach ($sources as $index => [, $countQuery]) {
$counts[$index] = $this->boundedCount(clone $countQuery);
}
}
$offset = ($page - 1) * $perPage;
$remaining = $perPage;
@ -850,8 +866,7 @@ class ThirdPartyWarehouseStorageMirrorRepository
if ($remaining === 0) {
break;
}
$sourceTotal = $counts[$index] ?? ($index < count($sources) - 1
? $this->boundedCount(clone $countQuery) : null);
$sourceTotal = $counts[$index] ?? null;
if ($sourceTotal !== null && $offset >= $sourceTotal) {
$offset -= $sourceTotal;
continue;
@ -871,6 +886,7 @@ class ThirdPartyWarehouseStorageMirrorRepository
return [
'data' => [],
'total' => $total,
'source_counts' => $counts,
'state' => $state,
'sync' => $this->syncStatus($state),
];
@ -885,6 +901,7 @@ class ThirdPartyWarehouseStorageMirrorRepository
return [
'data' => [],
'total' => $total,
'source_counts' => $counts,
'state' => $state,
'sync' => $this->syncStatus($state),
];
@ -979,6 +996,7 @@ class ThirdPartyWarehouseStorageMirrorRepository
return [
'data' => $rows,
'total' => $total,
'source_counts' => $counts,
'state' => $state,
'sync' => $this->syncStatus($state),
];

View File

@ -256,6 +256,15 @@
opacity: 0.65;
}
.directory-table-tools select {
height: 2.25rem;
padding: 0 0.5rem;
border: 1px solid var(--vip-border, #d8d2c7);
border-radius: 0.25rem;
background: #fff;
color: var(--vip-content-ink, #171717);
}
.directory-field-picker {
position: relative;
display: inline-block;
@ -849,14 +858,11 @@
<div class="installation-filter-actions">
<button type="submit" class="biz-btn biz-btn-primary">查询</button>
<a href="{{ request()->url() }}" class="biz-btn biz-btn-ghost">清除</a>
<a href="{{ route('business.product-inventory.inventory-report.export', request()->except('page')) }}" class="biz-btn biz-btn-ghost" aria-label="导出当前筛选结果" title="导出当前筛选结果">
<span class="material-icons-outlined" aria-hidden="true">download</span>导出
</a>
</div>
</form>
@endif
@if (! $directoryUsesFieldQuery)
<div class="directory-table-tools" data-directory-tools>
<div class="directory-table-tools" data-directory-tools @if (($page['slug'] ?? '') === 'inventory-report') data-directory-server-export @endif>
<label class="sr-only" for="directory-search-{{ $page['slug'] ?? 'page' }}">搜索当前表格</label>
<input id="directory-search-{{ $page['slug'] ?? 'page' }}" type="search" placeholder="搜索当前页数据..." data-directory-search>
<div class="directory-field-picker" data-directory-field-picker>
@ -871,14 +877,26 @@
@endforeach
</div>
</div>
<div class="directory-export-group" aria-label="导出范围">
<button type="button" data-directory-export="visible">当前页·显示列</button>
<button type="button" data-directory-export="all-fields">当前页·全部字段</button>
<button type="button" data-directory-export-all="visible">全部结果·显示列</button>
<button type="button" data-directory-export-all="all-fields">全部结果·全部字段</button>
</div>
<button type="button" data-directory-reset>恢复默认</button>
<button type="button" data-directory-template>下载表头模板</button>
@if (($page['slug'] ?? '') === 'inventory-report')
<select data-inventory-export-scope aria-label="导出范围">
<option value="all">全部筛选结果</option>
<option value="page">当前页(第 {{ $directoryCurrentPage }} 页)</option>
</select>
<select data-inventory-export-fields aria-label="导出字段范围">
<option value="visible">当前显示列及顺序</option>
<option value="all">全部可导出字段</option>
</select>
<button type="button" data-inventory-export data-export-url="{{ route('business.product-inventory.inventory-report.export') }}">导出</button>
@else
<div class="directory-export-group" aria-label="导出范围">
<button type="button" data-directory-export="visible">当前页·显示列</button>
<button type="button" data-directory-export="all-fields">当前页·全部字段</button>
<button type="button" data-directory-export-all="visible">全部结果·显示列</button>
<button type="button" data-directory-export-all="all-fields">全部结果·全部字段</button>
</div>
<button type="button" data-directory-reset>恢复默认</button>
<button type="button" data-directory-template>下载表头模板</button>
@endif
</div>
@endif
<div class="directory-table-scroll">
@ -1216,6 +1234,31 @@
};
const resetButton = tools.querySelector('[data-directory-reset]');
if (resetButton) resetButton.onclick = resetColumns;
tools.querySelector('[data-inventory-export]')?.addEventListener('click', (event) => {
const url = new URL(event.currentTarget.dataset.exportUrl, window.location.origin);
const current = new URL(window.location.href);
['month', 'product_code', 'warehouse_provider', 'category'].forEach((key) => {
if (current.searchParams.has(key)) url.searchParams.set(key, current.searchParams.get(key));
});
const scope = tools.querySelector('[data-inventory-export-scope]').value;
url.searchParams.set('scope', scope);
if (scope === 'page') url.searchParams.set('page', current.searchParams.get('page') || '1');
if (tools.querySelector('[data-inventory-export-fields]').value === 'visible') {
const columns = [...table.tHead.querySelectorAll('th[data-column-key]')]
.filter((cell) => !cell.classList.contains('is-column-hidden'))
.map((cell) => cell.dataset.columnKey);
if (!columns.length) {
window.alert('请至少选择一个显示列。');
return;
}
url.searchParams.set('columns', columns.join(','));
}
const link = document.createElement('a');
link.href = url.toString();
document.body.appendChild(link);
link.click();
link.remove();
});
search.addEventListener('input', () => {
const query = search.value.trim().toLocaleLowerCase();
table.querySelectorAll('tbody tr').forEach((row) => {

View File

@ -612,7 +612,7 @@
pageScope.querySelectorAll('[data-finance-fallback-export]').forEach((fallback) => {
fallback.hidden = true;
});
if (existingDirectoryTools) {
if (existingDirectoryTools && !existingDirectoryTools.hasAttribute('data-directory-server-export')) {
controls.dataset.financeExportEnhanced = 'true';
const currentPage = controls.querySelector('[data-directory-export]');
const allRows = controls.querySelector('[data-directory-export-all]');

View File

@ -45,10 +45,11 @@ class PagesTest extends FeatureTestCase
$response->assertOk()
->assertSeeText('导出')
->assertSee(e(route('business.product-inventory.inventory-report.export', [
'month' => '2026-08',
'product_code' => '121630-49',
])), false);
->assertSee('data-inventory-export-scope', false)
->assertSee('data-inventory-export-fields', false)
->assertSee('data-inventory-export', false)
->assertDontSee('<button type="button" data-directory-export-all', false)
->assertDontSee('<button type="button" data-directory-template', false);
}
public function testInventoryReportKeepsJulyMonthFilter(): void
@ -120,6 +121,64 @@ class PagesTest extends FeatureTestCase
$this->assertStringContainsString("'121630-49", $content);
}
public function testInventoryReportExportUsesSelectedVisibleColumnsInOrder(): void
{
$repository = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class);
$repository->shouldReceive('available')->once()->andReturnTrue();
$repository->shouldReceive('allWarehousesReady')->once()->andReturnTrue();
$repository->shouldReceive('exportMonthlyInventoryReportRows')->once()->with([
'month' => '2026-08', 'product_code' => '121630-49',
'warehouse_provider' => '', 'category' => '',
])->andReturn((static function (): \Generator {
yield (object) ['product_code' => '121630-49', 'warehouse' => '主仓', 'opening_quantity' => 10];
})());
$this->app->instance(ThirdPartyWarehouseStorageMirrorRepository::class, $repository);
$response = $this->loginAs()->get(route('business.product-inventory.inventory-report.export', [
'month' => '2026-08', 'product_code' => '121630-49',
'columns' => 'product_code,warehouse,opening_quantity',
]));
$response->assertOk()->assertDownload();
$this->assertSame("\xEF\xBB\xBF商品编码,仓库,期初数量\n'121630-49,主仓,10\n", $response->streamedContent());
}
public function testInventoryReportCurrentPageExportDoesNotReadAllFilteredRows(): void
{
$repository = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class);
$repository->shouldReceive('available')->once()->andReturnTrue();
$repository->shouldReceive('allWarehousesReady')->once()->andReturnTrue();
$repository->shouldNotReceive('exportMonthlyInventoryReportRows');
$repository->shouldReceive('paginateMonthlyInventoryReport')->once()->with(
['month' => '2026-08', 'product_code' => '', 'warehouse_provider' => '', 'category' => ''],
2,
Mockery::type('int'),
false,
)->andReturn(['data' => [(object) ['product_code' => 'PAGE-2']], 'total' => 0]);
$this->app->instance(ThirdPartyWarehouseStorageMirrorRepository::class, $repository);
$response = $this->loginAs()->get(route('business.product-inventory.inventory-report.export', [
'month' => '2026-08', 'page' => 2, 'scope' => 'page', 'columns' => 'product_code',
]));
$response->assertOk()->assertDownload();
$this->assertStringContainsString("商品编码\n'PAGE-2\n", $response->streamedContent());
}
public function testInventoryReportExportRejectsFieldsOutsideThePageSchema(): void
{
$repository = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class);
$repository->shouldReceive('available')->once()->andReturnTrue();
$repository->shouldReceive('allWarehousesReady')->once()->andReturnTrue();
$repository->shouldNotReceive('exportMonthlyInventoryReportRows');
$this->app->instance(ThirdPartyWarehouseStorageMirrorRepository::class, $repository);
$this->withExceptionHandling();
$this->loginAs()->get(route('business.product-inventory.inventory-report.export', [
'columns' => 'product_code,password',
]))->assertStatus(422);
}
public function testInventoryReportDoesNotFallBackToLegacyRowsBeforeAllWarehouseMirrorIsReady(): void
{
$repository = Mockery::mock(ThirdPartyWarehouseStorageMirrorRepository::class);