feat: 发票额度支持按筛选导出 CSV #1349

Merged
yaoyao merged 1 commits from feature/wuyongjie-invoice-quota-export into main 2026-11-21 16:30:14 +08:00
5 changed files with 271 additions and 130 deletions

View File

@ -22,141 +22,166 @@ class InvoiceQuotaPageData
public function page(): array
{
try {
$periodOptions = InvoiceBasic::query()
->select('period')
->whereNotNull('period')
->where('period', '<>', '')
->distinct()
->orderByDesc('period')
->pluck('period')
->map(static fn ($period): string => trim((string) $period))
->filter(fn (string $period): bool => $this->normalizePeriod($period) !== null)
->unique()
->values();
$requestedPeriod = $this->normalizePeriod(
trim((string) request()->query('period', ''))
);
$period = $requestedPeriod ?? $periodOptions->first() ?? '';
$forecastContext = $this->forecastContext($period);
$sellerEntity = mb_substr(
trim((string) request()->query('seller_entity', '')),
0,
100
);
$query = InvoiceBasic::query()->select([
'id',
'store_entity',
'invoice_issuer',
'output_amount',
'period',
]);
if ($period !== '') {
$query->where('period', $period);
} else {
$query->where(function ($query): void {
$query->whereNull('period')->orWhere('period', '');
});
}
if ($sellerEntity !== '') {
$needle = '%' . addcslashes($sellerEntity, '%_\\') . '%';
$query->where('store_entity', 'like', $needle);
}
$snapshots = $this->piaojuQuotas->byNormalizedName();
$rows = $query
->orderBy('store_entity')
->orderByDesc('id')
->get()
->map(fn (InvoiceBasic $row): object => $this->presentRow(
$row,
$snapshots->get(PiaojuSellerQuotaRepository::normalizeName((string) $row->store_entity)),
$forecastContext,
))
->sortBy(static fn (object $row): string => sprintf(
'%02d|%s',
$row->status_rank,
(string) $row->store_entity
))
->values();
$total = $rows->count();
$lastPage = max(1, (int) ceil($total / self::PER_PAGE));
$currentPage = min(max((int) request()->query('page', 1), 1), $lastPage);
$pageRows = $rows
->slice(($currentPage - 1) * self::PER_PAGE, self::PER_PAGE)
->values();
$paginator = new LengthAwarePaginator(
$pageRows,
$total,
self::PER_PAGE,
$currentPage,
[
'path' => request()->url(),
'query' => request()->query(),
]
);
$usedAmount = $rows->sum(static fn (object $row): float => (float) $row->output_amount);
$usedTotal = round($usedAmount, 2);
$forecastTotal = (int) ($forecastContext['elapsed_days'] ?? 0) > 0
? round(
$usedAmount
* (int) ($forecastContext['days_in_month'] ?? 0)
/ (int) $forecastContext['elapsed_days'],
2
)
: 0.0;
$availableRows = $rows->filter(
static fn (object $row): bool => $row->available_amount !== null
);
$availableTotal = round($availableRows->sum(
static fn (object $row): float => (float) $row->available_amount
), 2);
$matchedCount = $rows->where('snapshot_matched', true)->count();
$unmatchedCount = $rows->where('snapshot_matched', false)->count();
$unavailableCount = $rows->where('snapshot_unavailable', true)->count();
$insufficientCount = $rows->where('insufficient', true)->count();
$warningCount = $rows->where('quota_warning', true)->count();
return [
'view' => 'business.pages.invoice_quota',
'title' => '发票额度',
'period' => $period,
'periodOptions' => $periodOptions,
'sellerEntity' => $sellerEntity,
'rows' => $paginator,
'summary' => [
'record_count' => $total,
'used_total' => $usedTotal,
'forecast_total' => $forecastTotal,
'available_total' => $availableTotal,
'matched_count' => $matchedCount,
'unmatched_count' => $unmatchedCount,
'unavailable_count' => $unavailableCount,
'insufficient_count' => $insufficientCount,
'warning_count' => $warningCount,
'forecast_elapsed_days' => $forecastContext['elapsed_days'],
'forecast_days_in_month' => $forecastContext['days_in_month'],
'forecast_is_current' => $forecastContext['is_current'],
'latest_quota_updated_at' => $this->latestDateTime(
$rows->pluck('quota_updated_at')
),
'latest_source_fetched_at' => $this->latestDateTime(
$rows->pluck('source_fetched_at')
),
],
'loadError' => null,
];
$data = $this->buildData();
} catch (Throwable $exception) {
report($exception);
return $this->errorPayload();
}
$rows = $data['allRows'];
$total = $rows->count();
$lastPage = max(1, (int) ceil($total / self::PER_PAGE));
$currentPage = min(max((int) request()->query('page', 1), 1), $lastPage);
$pageRows = $rows
->slice(($currentPage - 1) * self::PER_PAGE, self::PER_PAGE)
->values();
$paginator = new LengthAwarePaginator(
$pageRows,
$total,
self::PER_PAGE,
$currentPage,
[
'path' => request()->url(),
'query' => request()->query(),
]
);
return [
'view' => 'business.pages.invoice_quota',
'title' => '发票额度',
'period' => $data['period'],
'periodOptions' => $data['periodOptions'],
'sellerEntity' => $data['sellerEntity'],
'rows' => $paginator,
'summary' => $data['summary'],
'loadError' => null,
];
}
/**
* 返回当前筛选条件下的全部行,供 CSV 导出使用。
*
* @return array{period:string, sellerEntity:string, allRows:Collection, summary:array}
*/
public function exportData(): array
{
return $this->buildData();
}
private function buildData(): array
{
$periodOptions = InvoiceBasic::query()
->select('period')
->whereNotNull('period')
->where('period', '<>', '')
->distinct()
->orderByDesc('period')
->pluck('period')
->map(static fn ($period): string => trim((string) $period))
->filter(fn (string $period): bool => $this->normalizePeriod($period) !== null)
->unique()
->values();
$requestedPeriod = $this->normalizePeriod(
trim((string) request()->query('period', ''))
);
$period = $requestedPeriod ?? $periodOptions->first() ?? '';
$forecastContext = $this->forecastContext($period);
$sellerEntity = mb_substr(
trim((string) request()->query('seller_entity', '')),
0,
100
);
$query = InvoiceBasic::query()->select([
'id',
'store_entity',
'invoice_issuer',
'output_amount',
'period',
]);
if ($period !== '') {
$query->where('period', $period);
} else {
$query->where(function ($query): void {
$query->whereNull('period')->orWhere('period', '');
});
}
if ($sellerEntity !== '') {
$needle = '%' . addcslashes($sellerEntity, '%_\\') . '%';
$query->where('store_entity', 'like', $needle);
}
$snapshots = $this->piaojuQuotas->byNormalizedName();
$rows = $query
->orderBy('store_entity')
->orderByDesc('id')
->get()
->map(fn (InvoiceBasic $row): object => $this->presentRow(
$row,
$snapshots->get(PiaojuSellerQuotaRepository::normalizeName((string) $row->store_entity)),
$forecastContext,
))
->sortBy(static fn (object $row): string => sprintf(
'%02d|%s',
$row->status_rank,
(string) $row->store_entity
))
->values();
$total = $rows->count();
$usedAmount = $rows->sum(static fn (object $row): float => (float) $row->output_amount);
$usedTotal = round($usedAmount, 2);
$forecastTotal = (int) ($forecastContext['elapsed_days'] ?? 0) > 0
? round(
$usedAmount
* (int) ($forecastContext['days_in_month'] ?? 0)
/ (int) $forecastContext['elapsed_days'],
2
)
: 0.0;
$availableRows = $rows->filter(
static fn (object $row): bool => $row->available_amount !== null
);
$availableTotal = round($availableRows->sum(
static fn (object $row): float => (float) $row->available_amount
), 2);
$matchedCount = $rows->where('snapshot_matched', true)->count();
$unmatchedCount = $rows->where('snapshot_matched', false)->count();
$unavailableCount = $rows->where('snapshot_unavailable', true)->count();
$insufficientCount = $rows->where('insufficient', true)->count();
$warningCount = $rows->where('quota_warning', true)->count();
return [
'period' => $period,
'periodOptions' => $periodOptions,
'sellerEntity' => $sellerEntity,
'allRows' => $rows,
'summary' => [
'record_count' => $total,
'used_total' => $usedTotal,
'forecast_total' => $forecastTotal,
'available_total' => $availableTotal,
'matched_count' => $matchedCount,
'unmatched_count' => $unmatchedCount,
'unavailable_count' => $unavailableCount,
'insufficient_count' => $insufficientCount,
'warning_count' => $warningCount,
'forecast_elapsed_days' => $forecastContext['elapsed_days'],
'forecast_days_in_month' => $forecastContext['days_in_month'],
'forecast_is_current' => $forecastContext['is_current'],
'latest_quota_updated_at' => $this->latestDateTime(
$rows->pluck('quota_updated_at')
),
'latest_source_fetched_at' => $this->latestDateTime(
$rows->pluck('source_fetched_at')
),
],
];
}
private function presentRow(

View File

@ -9455,6 +9455,70 @@ class Pages extends Controller
return $filters;
}
public function exportInvoiceQuota(\App\Business\InvoiceQuotaPageData $pageData): StreamedResponse
{
try {
$data = $pageData->exportData();
} catch (\Throwable $exception) {
report($exception);
abort(503, '发票额度数据暂时无法导出,请稍后重试。');
}
$period = (string) ($data['period'] ?? '');
$filename = 'invoice-quota'
. ($period !== '' ? '-' . $period : '')
. '-' . now()->format('Ymd_His') . '.csv';
$rows = collect($data['allRows'] ?? []);
return response()->streamDownload(function () use ($rows): void {
$out = fopen('php://output', 'w');
if ($out === false) {
throw new RuntimeException('无法创建发票额度导出流。');
}
fwrite($out, chr(0xEF) . chr(0xBB) . chr(0xBF));
fputcsv($out, [
'序号',
'开票主体',
'开票员',
'已开票金额',
'预估整月开票',
'日均开票',
'票聚可用额度',
'额度可支撑(天)',
'额度更新时间',
'状态',
]);
foreach ($rows->values() as $index => $row) {
fputcsv($out, [
$index + 1,
$this->csvText($row->store_entity ?? ''),
$this->csvText($row->invoice_issuer ?? ''),
$this->exportNumber($row->output_amount ?? null),
$this->exportNumber($row->forecast_monthly ?? null),
$this->exportNumber($row->daily_average ?? null),
$this->exportNumber($row->available_amount ?? null),
$this->exportNumber($row->coverage_days ?? null),
$this->csvText($row->quota_updated_at ?? ''),
$this->csvText($row->status ?? ''),
]);
}
fclose($out);
}, $filename, [
'Content-Type' => 'text/csv; charset=UTF-8',
'Cache-Control' => 'private, no-store',
]);
}
private function exportNumber(mixed $value): string
{
return $value === null || $value === ''
? ''
: number_format((float) $value, 2, '.', '');
}
private function csvText(mixed $value): string
{
$text = trim((string) ($value ?? ''));

View File

@ -168,6 +168,19 @@
<span class="material-icons-outlined" aria-hidden="true">search</span>
<span>查询</span>
</button>
@unless ($loadError)
<a
href="{{ route('business.invoice-quota.export', array_filter([
'period' => $period,
'seller_entity' => $sellerEntity,
], static fn ($value): bool => $value !== '' && $value !== null)) }}"
class="upstream-data-button"
title="按当前筛选导出全部记录"
>
<span class="material-icons-outlined" aria-hidden="true">download</span>
<span>导出</span>
</a>
@endunless
<a
href="{{ route('business.pages.show', ['section' => $section['slug'], 'page' => $page['slug']]) }}"
class="upstream-data-button"

View File

@ -681,6 +681,10 @@ Route::get('workspace/posting-data/kuka-reconciliation/posting-data/export', 'Bu
->middleware('business.page:posting-data,kuka-reconciliation')
->name('business.kuka-reconciliation.posting-data.export');
Route::get('workspace/invoice-management/invoice-quota/export', 'Business\Pages@exportInvoiceQuota')
->middleware('business.page:invoice-management,invoice-quota')
->name('business.invoice-quota.export');
Route::middleware('business.page.viewer')->group(function (): void {
Route::get('workspace/{section}/{page}/{tab}/export', 'Business\Pages@export')
->name('business.pages.export');

View File

@ -79,6 +79,8 @@ class InvoiceQuotaPageTest extends FeatureTestCase
->assertSeeText('已开票金额')
->assertSeeText('预估整月开票')
->assertSeeText('5天额度预警')
->assertSeeText('导出')
->assertSee(route('business.invoice-quota.export', ['period' => '2026-11']), false)
->assertSeeText('15,000.00')
->assertSeeText('18,000.00')
->assertSeeText('19,495.00')
@ -125,6 +127,39 @@ class InvoiceQuotaPageTest extends FeatureTestCase
->assertSee('<option value="2026-10" selected>', false);
}
public function test_invoice_quota_exports_all_filtered_rows_as_csv(): void
{
for ($index = 1; $index <= 55; $index++) {
$this->createInvoiceBasic(
sprintf('导出公司%02d', $index),
'导出店铺' . $index,
0,
1000 + $index,
'2026-11',
);
}
$this->loginAs();
$response = $this->get(route('business.invoice-quota.export', [
'seller_entity' => '导出公司',
]));
$response->assertOk()
->assertHeader('Content-Type', 'text/csv; charset=UTF-8');
$this->assertStringContainsString(
'attachment',
(string) $response->headers->get('Content-Disposition')
);
$content = $response->streamedContent();
$this->assertStringContainsString('开票主体', $content);
$this->assertStringContainsString('导出公司01', $content);
$this->assertStringContainsString('导出公司55', $content);
$this->assertStringContainsString('1055.00', $content);
$this->assertStringNotContainsString('甲公司', $content);
}
private function createPiaojuSnapshot(
string $sellerKey,
string $sellerName,