From 5d29bcf9742b504c679bbdb50a974f63c6a3de4e Mon Sep 17 00:00:00 2001 From: WuYongJie Date: Sat, 21 Nov 2026 16:29:43 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=91=E7=A5=A8=E9=A2=9D=E5=BA=A6?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=8C=89=E7=AD=9B=E9=80=89=E5=AF=BC=E5=87=BA?= =?UTF-8?q?=20CSV?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Business/InvoiceQuotaPageData.php | 285 ++++++++++-------- app/Http/Controllers/Business/Pages.php | 64 ++++ .../business/pages/invoice_quota.blade.php | 13 + routes/admin.php | 4 + .../Feature/Business/InvoiceQuotaPageTest.php | 35 +++ 5 files changed, 271 insertions(+), 130 deletions(-) diff --git a/app/Business/InvoiceQuotaPageData.php b/app/Business/InvoiceQuotaPageData.php index b4d1f7f9..ca50239d 100644 --- a/app/Business/InvoiceQuotaPageData.php +++ b/app/Business/InvoiceQuotaPageData.php @@ -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( diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 79bb09b7..e16b298a 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -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 ?? '')); diff --git a/resources/views/business/pages/invoice_quota.blade.php b/resources/views/business/pages/invoice_quota.blade.php index 9d75d3a3..aed751c7 100644 --- a/resources/views/business/pages/invoice_quota.blade.php +++ b/resources/views/business/pages/invoice_quota.blade.php @@ -168,6 +168,19 @@ 查询 + @unless ($loadError) + + + 导出 + + @endunless 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'); diff --git a/tests/Feature/Business/InvoiceQuotaPageTest.php b/tests/Feature/Business/InvoiceQuotaPageTest.php index 7b996b9f..6c922801 100644 --- a/tests/Feature/Business/InvoiceQuotaPageTest.php +++ b/tests/Feature/Business/InvoiceQuotaPageTest.php @@ -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('