feat: 新增发票额度页面 #1225

Merged
huilan merged 1 commits from feature/huilan-invoice-quota into main 2026-11-17 17:51:13 +08:00
5 changed files with 640 additions and 0 deletions

View File

@ -0,0 +1,211 @@
<?php
namespace App\Business;
use App\Models\Business\InvoiceBasic;
use Illuminate\Pagination\LengthAwarePaginator;
use Throwable;
class InvoiceQuotaPageData
{
private const PER_PAGE = 50;
private const WARNING_RATE = 0.8;
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() ?? '';
$sellerEntity = mb_substr(
trim((string) request()->query('seller_entity', '')),
0,
100
);
$filtered = InvoiceBasic::query();
if ($period !== '') {
$filtered->where('period', $period);
} else {
$filtered->where(function ($query): void {
$query->whereNull('period')->orWhere('period', '');
});
}
if ($sellerEntity !== '') {
$needle = '%' . addcslashes($sellerEntity, '%_\\') . '%';
$filtered->where('store_entity', 'like', $needle);
}
$aggregate = (clone $filtered)
->reorder()
->selectRaw(
'COUNT(*) AS record_count,
COALESCE(SUM(invoice_limit), 0) AS quota_total,
COALESCE(SUM(output_amount), 0) AS used_total,
SUM(CASE WHEN output_amount > invoice_limit THEN 1 ELSE 0 END) AS exceeded_count,
SUM(CASE WHEN invoice_limit > 0
AND output_amount > 0
AND output_amount <= invoice_limit
AND output_amount >= invoice_limit * ? THEN 1 ELSE 0 END) AS warning_count',
[self::WARNING_RATE]
)
->first();
$rows = (clone $filtered)
->select([
'id',
'store_name',
'store_entity',
'invoice_issuer',
'invoice_limit',
'output_amount',
'period',
])
->orderByRaw(
'CASE
WHEN output_amount > invoice_limit THEN 0
WHEN invoice_limit > 0 AND output_amount >= invoice_limit * ? THEN 1
WHEN invoice_limit > 0 THEN 2
ELSE 3
END',
[self::WARNING_RATE]
)
->orderBy('store_entity')
->orderByDesc('id')
->paginate(self::PER_PAGE)
->withQueryString();
$rows->setCollection(
$rows->getCollection()->map(
fn (InvoiceBasic $row): object => $this->presentRow($row)
)
);
$quotaTotal = round((float) ($aggregate->quota_total ?? 0), 2);
$usedTotal = round((float) ($aggregate->used_total ?? 0), 2);
$exceededCount = (int) ($aggregate->exceeded_count ?? 0);
$warningCount = (int) ($aggregate->warning_count ?? 0);
return [
'view' => 'business.pages.invoice_quota',
'title' => '发票额度',
'period' => $period,
'periodOptions' => $periodOptions,
'sellerEntity' => $sellerEntity,
'rows' => $rows,
'summary' => [
'record_count' => (int) ($aggregate->record_count ?? 0),
'quota_total' => $quotaTotal,
'used_total' => $usedTotal,
'remaining_total' => round($quotaTotal - $usedTotal, 2),
'usage_rate' => $quotaTotal > 0
? round($usedTotal / $quotaTotal * 100, 1)
: null,
'exceeded_count' => $exceededCount,
'warning_count' => $warningCount,
'attention_count' => $exceededCount + $warningCount,
],
'warningRate' => self::WARNING_RATE * 100,
'loadError' => null,
];
} catch (Throwable $exception) {
report($exception);
return $this->errorPayload();
}
}
private function presentRow(InvoiceBasic $row): object
{
$quota = round((float) $row->invoice_limit, 2);
$used = round((float) $row->output_amount, 2);
$remaining = round($quota - $used, 2);
$usageRate = $quota > 0 ? round($used / $quota * 100, 1) : null;
if ($used > $quota) {
$status = '超额';
$statusTone = 'danger';
$statusIcon = 'error';
} elseif ($quota <= 0) {
$status = '未设置额度';
$statusTone = 'muted';
$statusIcon = 'remove_circle_outline';
} elseif ($usageRate !== null && $usageRate >= self::WARNING_RATE * 100) {
$status = '需关注';
$statusTone = 'warning';
$statusIcon = 'warning_amber';
} else {
$status = '正常';
$statusTone = 'success';
$statusIcon = 'check_circle_outline';
}
return (object) [
'id' => $row->id,
'store_name' => $row->store_name,
'store_entity' => $row->store_entity,
'invoice_issuer' => $row->invoice_issuer,
'invoice_limit' => $quota,
'output_amount' => $used,
'remaining' => $remaining,
'usage_rate' => $usageRate,
'usage_bar_width' => $usageRate === null
? 0
: min(100, max(0, (int) round($usageRate))),
'status' => $status,
'status_tone' => $statusTone,
'status_icon' => $statusIcon,
'period' => $row->period,
];
}
private function normalizePeriod(string $period): ?string
{
return preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) === 1
? $period
: null;
}
private function errorPayload(): array
{
return [
'view' => 'business.pages.invoice_quota',
'title' => '发票额度',
'period' => '',
'periodOptions' => collect(),
'sellerEntity' => '',
'rows' => new LengthAwarePaginator([], 0, self::PER_PAGE, 1, [
'path' => request()->url(),
'query' => request()->query(),
]),
'summary' => [
'record_count' => 0,
'quota_total' => 0.0,
'used_total' => 0.0,
'remaining_total' => 0.0,
'usage_rate' => null,
'exceeded_count' => 0,
'warning_count' => 0,
'attention_count' => 0,
],
'warningRate' => self::WARNING_RATE * 100,
'loadError' => '发票额度数据暂时无法读取,请稍后重试。',
];
}
}

View File

@ -5231,6 +5231,7 @@ class Pages extends Controller
'preview-statistics' => $this->contentForPreviewStatistics(),
'planting-details' => $this->contentForPlantingDetails(),
'jst-order-labels' => $this->contentForJstOrderLabels(),
'invoice-quota' => app(\App\Business\InvoiceQuotaPageData::class)->page(),
'invoice-reports' => app(\App\Business\InvoiceReportsPageData::class)->page($tab),
'planting-reimbursements' => app(\Modules\EcommerceFinance\View\PlantingReimbursementPageData::class)->page(),
'planting-reimbursement-workbench' => app(\Modules\EcommerceFinance\View\PlantingReimbursementWorkbenchPageData::class)->page(),

View File

@ -658,6 +658,7 @@ $navigation = [
'pages' => [
['slug' => 'automatic-invoicing', 'title' => '自动开票'],
['slug' => 'basic-information', 'title' => '发票基础信息'],
['slug' => 'invoice-quota', 'title' => '发票额度'],
[
'slug' => 'invoice-reports',
'title' => '发票数据报表',

View File

@ -0,0 +1,319 @@
@php
$period = $period ?? '';
$periodOptions = $periodOptions ?? collect();
$sellerEntity = $sellerEntity ?? '';
$rows = $rows ?? collect();
$summary = $summary ?? [];
$warningRate = $warningRate ?? 80;
$loadError = $loadError ?? null;
@endphp
<div class="business-page-header">
<span class="business-page-title">{{ $title ?? '发票额度' }}</span>
</div>
<div class="upstream-data-page invoice-quota-page">
@include('business.pages.partials.upstream-data-styles')
<style>
.invoice-quota-summary {
--upstream-summary-columns: 4;
--upstream-summary-min-width: 9rem;
}
.invoice-quota-summary small {
display: block;
overflow: hidden;
margin-top: 0.25rem;
color: var(--vip-content-muted, #595959);
font-size: 0.71875rem;
font-weight: 400;
text-overflow: ellipsis;
white-space: nowrap;
}
.invoice-quota-table {
min-width: 68rem;
}
.invoice-quota-table .invoice-quota-entity {
min-width: 12rem;
max-width: 20rem;
overflow: hidden;
text-overflow: ellipsis;
}
.invoice-quota-table .is-negative {
color: var(--vip-danger, #b80000);
font-weight: 600;
}
.invoice-quota-summary .is-negative {
color: var(--vip-danger, #b80000);
}
.invoice-quota-usage {
display: flex;
min-width: 8.5rem;
align-items: center;
gap: 0.5rem;
}
.invoice-quota-usage__track {
display: block;
width: 5rem;
height: 0.375rem;
overflow: hidden;
border-radius: 999px;
background: #ebe7df;
}
.invoice-quota-usage__bar {
display: block;
height: 100%;
border-radius: inherit;
background: var(--vip-content-accent-dark, #856632);
}
.invoice-quota-usage__value {
min-width: 3rem;
color: var(--vip-content-muted, #595959);
font-variant-numeric: tabular-nums;
text-align: right;
}
.invoice-quota-status {
display: inline-flex;
height: 1.5rem;
align-items: center;
gap: 0.25rem;
padding: 0 0.5rem;
border: 1px solid var(--vip-border, #d8d2c7);
border-radius: 999px;
font-size: 0.71875rem;
font-weight: 600;
white-space: nowrap;
}
.invoice-quota-status .material-icons-outlined {
font-size: 0.9375rem;
}
.invoice-quota-status.is-danger {
border-color: #e7b4b4;
background: #fff5f5;
color: var(--vip-danger, #b80000);
}
.invoice-quota-status.is-warning {
border-color: #e6cf9f;
background: #fdf3e3;
color: var(--vip-warning, #935f07);
}
.invoice-quota-status.is-success {
border-color: #bfd0b5;
background: #f3f8f0;
color: var(--vip-success, #53793e);
}
.invoice-quota-status.is-muted {
background: #f5f4f1;
color: var(--vip-content-muted, #595959);
}
.invoice-quota-note {
margin: 0;
padding: 0.75rem 1rem;
border-top: 1px solid var(--vip-border, #d8d2c7);
color: var(--vip-content-muted, #595959);
font-size: 0.75rem;
line-height: 1.55;
}
@media (max-width: 900px) and (min-width: 721px) {
.invoice-quota-summary {
--upstream-summary-columns: 2;
}
.invoice-quota-summary div:nth-child(2n) {
border-right: 0;
}
.invoice-quota-summary div:nth-child(-n + 2) {
border-bottom: 1px solid var(--vip-border, #d8d2c7);
}
}
</style>
@if ($loadError)
<div class="upstream-data-alert" role="alert">
<span class="material-icons-outlined" aria-hidden="true">error_outline</span>
<span>{{ $loadError }}</span>
</div>
@endif
<form method="GET" action="{{ request()->url() }}" class="upstream-data-toolbar" aria-label="发票额度筛选">
<div class="upstream-data-field">
<label for="invoice-quota-period">期间</label>
<select id="invoice-quota-period" name="period">
@forelse ($periodOptions as $periodOption)
<option value="{{ $periodOption }}" @selected($period === $periodOption)>{{ $periodOption }}</option>
@empty
<option value="">{{ $period !== '' ? $period : '暂无期间' }}</option>
@endforelse
</select>
</div>
<div class="upstream-data-field">
<label for="invoice-quota-seller">开票主体</label>
<input
id="invoice-quota-seller"
type="search"
name="seller_entity"
value="{{ $sellerEntity }}"
maxlength="100"
placeholder="输入主体名称"
autocomplete="off"
>
</div>
<div class="upstream-data-actions">
<button type="submit" class="upstream-data-button upstream-data-button--primary">
<span class="material-icons-outlined" aria-hidden="true">search</span>
<span>查询</span>
</button>
<a
href="{{ route('business.pages.show', ['section' => $section['slug'], 'page' => $page['slug']]) }}"
class="upstream-data-button"
>
<span class="material-icons-outlined" aria-hidden="true">refresh</span>
<span>重置</span>
</a>
</div>
</form>
@unless ($loadError)
<dl class="upstream-data-summary invoice-quota-summary" aria-label="发票额度汇总">
<div>
<dt>当前开票额度</dt>
<dd>{{ number_format((float) ($summary['quota_total'] ?? 0), 2) }}</dd>
<small>{{ $period !== '' ? $period . ' 期间' : '期间未设置' }} · {{ (int) ($summary['record_count'] ?? 0) }} 个主体</small>
</div>
<div>
<dt>已开票金额</dt>
<dd>{{ number_format((float) ($summary['used_total'] ?? 0), 2) }}</dd>
<small>按当前筛选范围内的销项金额汇总</small>
</div>
<div>
<dt>可用额度</dt>
<dd @class(['is-negative' => (float) ($summary['remaining_total'] ?? 0) < 0])>
{{ number_format((float) ($summary['remaining_total'] ?? 0), 2) }}
</dd>
<small>
@if (($summary['usage_rate'] ?? null) !== null)
整体使用率 {{ number_format((float) $summary['usage_rate'], 1) }}%
@else
当前范围未设置开票额度
@endif
</small>
</div>
<div>
<dt>风险主体</dt>
<dd>{{ (int) ($summary['attention_count'] ?? 0) }}</dd>
<small>超额 {{ (int) ($summary['exceeded_count'] ?? 0) }} · 需关注 {{ (int) ($summary['warning_count'] ?? 0) }}</small>
</div>
</dl>
@endunless
<div class="upstream-data-table-panel">
<div class="upstream-data-table-scroll">
<table class="upstream-data-table invoice-quota-table" aria-label="发票额度明细">
<thead>
<tr>
<th>序号</th>
<th>开票主体</th>
<th>店铺范围</th>
<th>开票员</th>
<th class="is-number">开票额度</th>
<th class="is-number">已开票金额</th>
<th class="is-number">可用额度</th>
<th>使用率</th>
<th>状态</th>
</tr>
</thead>
<tbody>
@forelse ($rows as $row)
<tr>
<td>{{ $rows->firstItem() + $loop->index }}</td>
<td class="invoice-quota-entity" title="{{ $row->store_entity }}">{{ $row->store_entity }}</td>
<td title="{{ $row->store_name }}">{{ $row->store_name ?: '—' }}</td>
<td>{{ $row->invoice_issuer ?: '—' }}</td>
<td class="is-number">{{ number_format((float) $row->invoice_limit, 2) }}</td>
<td class="is-number">{{ number_format((float) $row->output_amount, 2) }}</td>
<td @class(['is-number', 'is-negative' => $row->remaining < 0])>
{{ number_format((float) $row->remaining, 2) }}
</td>
<td>
@if ($row->usage_rate !== null)
<div class="invoice-quota-usage" title="已开票金额 ÷ 开票额度">
<span class="invoice-quota-usage__track" aria-hidden="true">
<span class="invoice-quota-usage__bar" style="width: {{ $row->usage_bar_width }}%"></span>
</span>
<span class="invoice-quota-usage__value">{{ number_format((float) $row->usage_rate, 1) }}%</span>
</div>
@else
<span class="invoice-quota-usage__value">—</span>
@endif
</td>
<td>
<span class="invoice-quota-status is-{{ $row->status_tone }}">
<span class="material-icons-outlined" aria-hidden="true">{{ $row->status_icon }}</span>
<span>{{ $row->status }}</span>
</span>
</td>
</tr>
@empty
<tr class="is-empty">
<td colspan="9">
@if ($loadError)
数据加载失败,请稍后重试。
@else
当前期间暂无可展示的发票额度数据,请先在发票基础信息中补充记录或切换期间。
@endif
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
<p class="invoice-quota-note">
可用额度 = 开票额度 - 已开票金额;使用率达到 {{ number_format((float) $warningRate, 0) }}% 标记“需关注”,超过开票额度标记“超额”。开票额度为 0 且有已开票金额时同样按超额处理。
</p>
@if ($rows->total() > 0)
<div class="upstream-data-pagination">
<span>
共 {{ $rows->total() }} 条 · 第 {{ $rows->currentPage() }} / {{ $rows->lastPage() }} 页
</span>
<span class="upstream-data-pagination__controls">
@if ($rows->onFirstPage())
<span class="upstream-data-button is-disabled" aria-disabled="true">
<span class="material-icons-outlined" aria-hidden="true">chevron_left</span>
</span>
@else
<a href="{{ $rows->previousPageUrl() }}" class="upstream-data-button" aria-label="上一页">
<span class="material-icons-outlined" aria-hidden="true">chevron_left</span>
</a>
@endif
@if ($rows->hasMorePages())
<a href="{{ $rows->nextPageUrl() }}" class="upstream-data-button" aria-label="下一页">
<span class="material-icons-outlined" aria-hidden="true">chevron_right</span>
</a>
@else
<span class="upstream-data-button is-disabled" aria-disabled="true">
<span class="material-icons-outlined" aria-hidden="true">chevron_right</span>
</span>
@endif
</span>
</div>
@endif
</div>
</div>

View File

@ -0,0 +1,108 @@
<?php
namespace Tests\Feature\Business;
use App\Models\Auth\Permission;
use App\Models\Business\InvoiceBasic;
use Tests\Feature\FeatureTestCase;
class InvoiceQuotaPageTest extends FeatureTestCase
{
protected function setUp(): void
{
parent::setUp();
$this->user->attachPermission(
Permission::where('name', 'read-admin-panel')->firstOrFail()
);
$this->createInvoiceBasic('甲公司', '甲店铺组', 10000, 8500, '2026-11');
$this->createInvoiceBasic('乙公司', '乙店铺', 2000, 2500, '2026-11');
$this->createInvoiceBasic('丙公司', '丙店铺', 5000, 1000, '2026-11');
$this->createInvoiceBasic('零额度公司', '零额度店铺', 0, 0, '2026-11');
$this->createInvoiceBasic('历史公司', '历史店铺', 100, 100, '2026-10');
}
public function test_invoice_quota_is_listed_after_invoice_basic_information(): void
{
$pages = collect(config('business_navigation'))
->firstWhere('slug', 'invoice-management')['pages'];
$this->assertSame(
['automatic-invoicing', 'basic-information', 'invoice-quota', 'invoice-reports', 'store-backend-invoicing'],
array_column($pages, 'slug')
);
}
public function test_invoice_quota_defaults_to_latest_period_and_shows_usage_summary(): void
{
$this->loginAs()
->get($this->pageUrl())
->assertOk()
->assertSeeText('发票额度')
->assertSeeText('当前开票额度')
->assertSeeText('17,000.00')
->assertSeeText('12,000.00')
->assertSeeText('5,000.00')
->assertSeeText('甲公司')
->assertSeeText('8,500.00')
->assertSeeText('1,500.00')
->assertSeeText('85.0%')
->assertSeeText('乙公司')
->assertSeeText('-500.00')
->assertSeeText('超额')
->assertSeeText('需关注')
->assertSeeText('未设置额度')
->assertSeeText('超额 1 · 需关注 1')
->assertDontSeeText('历史公司')
->assertSee('<option value="2026-11" selected>', false);
}
public function test_invoice_quota_filters_by_period_and_seller_entity(): void
{
$this->loginAs()
->get($this->pageUrl(['seller_entity' => '甲公司']))
->assertOk()
->assertSeeText('甲公司')
->assertSeeText('10,000.00')
->assertSeeText('8,500.00')
->assertDontSeeText('乙公司')
->assertDontSeeText('丙公司');
$this->loginAs()
->get($this->pageUrl(['period' => '2026-10']))
->assertOk()
->assertSeeText('历史公司')
->assertDontSeeText('甲公司')
->assertSee('<option value="2026-10" selected>', false);
}
private function createInvoiceBasic(
string $entity,
string $storeName,
float $invoiceLimit,
float $outputAmount,
string $period
): void {
InvoiceBasic::create([
'company_id' => $this->company->id,
'store_name' => $storeName,
'store_entity' => $entity,
'invoice_issuer' => $entity . '开票员',
'invoice_limit' => $invoiceLimit,
'output_amount' => $outputAmount,
'input_amount' => 0,
'period' => $period,
]);
}
private function pageUrl(array $query = []): string
{
$url = route('business.pages.show', [
'section' => 'invoice-management',
'page' => 'invoice-quota',
]);
return $query === [] ? $url : $url . '?' . http_build_query($query);
}
}