账单明细:新增财务备注筛选、筛选联动(行数为0的取值不展示)、行距放宽

This commit is contained in:
yueyang 2026-10-09 10:30:43 +08:00
parent 0cca2aac70
commit f56bd9d3ea
4 changed files with 470 additions and 3 deletions

View File

@ -394,6 +394,19 @@ class Pages extends Controller
]);
}
/** 账单明细筛选联动:按当前其它条件返回各筛选项可选值与行数 */
public function billingDetailsFilterOptions(): \Illuminate\Http\JsonResponse
{
$section = collect(SidebarPermissions::navigationFor(user()))->firstWhere('slug', 'financial-operations');
abort_unless($section && collect($section['pages'] ?? [])->contains('slug', 'billing-details'), 403, '当前账号没有该页面权限。');
$data = app(\Modules\EcommerceFinance\View\BillingDetailsPageData::class);
return response()->json(['facets' => $data->facets(request()->all())], 200, [
'Cache-Control' => 'private, no-store',
]);
}
/** 账单明细导出进度(前端每秒轮询一次) */
public function billingDetailsExportProgress(Request $request): \Illuminate\Http\JsonResponse
{

View File

@ -321,11 +321,354 @@ class BillingDetailsPageData
'summary' => ['rows' => $total, 'income' => round($income, 2), 'expense' => round($expense, 2), 'net' => round($income - $expense, 2)],
'platforms' => array_keys(self::PLATFORM_FILTERS),
'types' => $this->types(),
'remarks' => $this->remarks(),
'error' => $error,
'status' => $status,
];
}
/**
* 筛选联动:按「除该筛选项以外的其它条件」统计各筛选项的可选值与行数,行数为 0 的取值不返回。
* 结果按筛选条件签名缓存 60 秒,避免连续勾选时反复扫同一批数据。
*
* @return array<string,array{values:list<string>,counts:array<string,int>}>
*/
public function facets(?array $input = null): array
{
$input ??= request()->all();
$filters = $this->parseFilters($input);
$signature = md5((string) json_encode($filters, JSON_UNESCAPED_UNICODE));
try {
return cache()->remember(
'billing-details-facets-v1:' . $signature,
now()->addSeconds(60),
fn (): array => $this->computeFacets($filters),
);
} catch (Throwable $exception) {
report($exception);
return $this->emptyFacets();
}
}
/**
* @param array<string,mixed> $filters
* @return array<string,array{values:list<string>,counts:array<string,int>}>
*/
private function computeFacets(array $filters): array
{
$conn = $this->connection();
$rules = $this->rules();
$facets = $this->emptyFacets();
$facets['platform'] = $this->facetPlatform($conn, $this->withoutFilter($filters, 'platform'));
$facets['store'] = $this->shape(
$this->facetCounts($conn, $this->withoutFilter($filters, 'store'), 'store_name'),
$this->options()['stores'] ?? [],
);
// 账单项目按原始 bill_item 分组(命中 bill_item 索引),wx 前缀在 PHP 里归一,避免逐行函数计算拖慢扫描。
$itemByBranch = $this->facetCountsByBranch($conn, $this->withoutFilter($filters, 'item'), 'bill_item');
$itemCounts = [];
foreach ($itemByBranch as $counts) {
foreach ($this->normalizeItemCounts($counts) as $item => $count) {
$itemCounts[$item] = ($itemCounts[$item] ?? 0) + $count;
}
}
$facets['item'] = $this->shape($itemCounts, $this->options()['items'] ?? []);
// 财务类型 / 财务备注:按分支折算(分支内平台集合已知),避免跨平台把同一账单项目的行数重复计入。
$itemIndex = $this->ruleIndexByItem($rules);
$contextPlatforms = $this->rulePlatforms($filters['platform']);
$typeCounts = [];
$remarkCounts = [];
foreach ($itemByBranch as $label => $counts) {
$platforms = self::BRANCH_PLATFORMS[$label] ?? [];
if ($contextPlatforms !== []) {
$platforms = array_values(array_intersect($platforms, $contextPlatforms));
}
$normalized = $this->normalizeItemCounts($counts);
foreach ($this->foldItemCounts($normalized, $itemIndex, 'category', $platforms) as $value => $count) {
$typeCounts[$value] = ($typeCounts[$value] ?? 0) + $count;
}
foreach ($this->foldItemCounts($normalized, $itemIndex, 'memo', $platforms) as $value => $count) {
$remarkCounts[$value] = ($remarkCounts[$value] ?? 0) + $count;
}
}
$facets['type'] = $this->shape($typeCounts, $this->types());
$facets['remark'] = $this->shape($remarkCounts, $this->remarks());
// 未限定平台时,同一账单项目在不同平台可能挂不同备注/类型,行数无法精确拆分:
// 这种情况只给可选值(用于隐藏真的没有数据的取值),不展示可能偏大的行数。
if ($contextPlatforms === []) {
$facets['type']['counts'] = [];
$facets['remark']['counts'] = [];
}
return $facets;
}
/** @return array<string,array{values:list<string>,counts:array<string,int>}> */
private function emptyFacets(): array
{
return [
'platform' => ['values' => [], 'counts' => []],
'store' => ['values' => [], 'counts' => []],
'item' => ['values' => [], 'counts' => []],
'type' => ['values' => [], 'counts' => []],
'remark' => ['values' => [], 'counts' => []],
];
}
/** @param array<string,mixed> $filters */
private function withoutFilter(array $filters, string $key): array
{
if ($key === 'keyword') {
$filters['keyword'] = '';
} else {
$filters[$key] = [];
}
return $filters;
}
/**
* 平台联动:按「账户/数据来源」分支 + 店铺前缀统计行数。
*
* @param array<string,mixed> $filters
* @return array{values:list<string>,counts:array<string,int>}
*/
private function facetPlatform(mixed $conn, array $filters): array
{
$counts = [];
foreach (self::SOURCES as $label => $meta) {
$cases = [];
$labels = [];
foreach (self::PLATFORM_FILTERS as $platformLabel => $mapping) {
if ($mapping['source'] !== $label) {
continue;
}
$cases[] = $mapping['prefix'] === null
? 'COUNT(*)'
: 'SUM(CASE WHEN store_name LIKE ' . $this->likeLiteral((string) $mapping['prefix']) . ' THEN 1 ELSE 0 END)';
$labels[] = $platformLabel;
}
if ($cases === []) {
continue;
}
$select = [];
foreach ($cases as $index => $case) {
$select[] = 'COALESCE(' . $case . ', 0) AS c' . $index;
}
$branch = $this->branch($label, $meta, $filters);
foreach ($branch['scopes'] as $scope) {
$row = $conn->selectOne(
'SELECT ' . implode(', ', $select) . ' FROM ' . $branch['table'] . ' WHERE ' . $scope['where'],
$scope['bind'],
);
foreach ($labels as $index => $platformLabel) {
$counts[$platformLabel] = ($counts[$platformLabel] ?? 0) + (int) ($row->{'c' . $index} ?? 0);
}
}
}
return $this->shape($counts, array_keys(self::PLATFORM_FILTERS));
}
/**
* 单列联动:按该表达式分组统计行数。
*
* @param array<string,mixed> $filters
* @return array<string,int>
*/
/** 分支 → 该分支可能命中的科目映射表平台 */
private const BRANCH_PLATFORMS = [
'淘系支付宝' => ['天猫', '淘宝', '阿里巴巴', '支付宝'],
'淘系微信' => ['天猫', '淘宝'],
'拼多多' => ['拼多多'],
'京东账单' => ['京东', '京喜'],
'京东钱包' => ['京东'],
'抖音' => ['抖音'],
'得物' => ['得物'],
];
private function facetCounts(mixed $conn, array $filters, string $expression): array
{
$counts = [];
foreach ($this->facetCountsByBranch($conn, $filters, $expression) as $branchCounts) {
foreach ($branchCounts as $key => $count) {
$counts[$key] = ($counts[$key] ?? 0) + $count;
}
}
return $counts;
}
/**
* 单列联动(按分支返回):用于只在本分支的平台集合内折算财务类型 / 财务备注。
*
* @param array<string,mixed> $filters
* @return array<string,array<string,int>> 分支标签 → [取值 => 行数]
*/
private function facetCountsByBranch(mixed $conn, array $filters, string $expression): array
{
$result = [];
foreach (self::SOURCES as $label => $meta) {
$branch = $this->branch($label, $meta, $filters);
$parts = [];
$bind = [];
foreach ($branch['scopes'] as $scope) {
$parts[] = 'SELECT ' . $expression . ' AS k, COUNT(*) AS c FROM ' . $branch['table']
. ' WHERE ' . $scope['where'] . ' GROUP BY k';
$bind = array_merge($bind, $scope['bind']);
}
if ($parts === []) {
continue;
}
$counts = [];
foreach ($conn->select(implode(' UNION ALL ', $parts), $bind) as $row) {
$key = trim((string) $row->k);
if ($key !== '') {
$counts[$key] = ($counts[$key] ?? 0) + (int) $row->c;
}
}
$result[$label] = $counts;
}
return $result;
}
/**
* wx 前缀归一:把「wx 前缀」的账单项目并到去前缀后的名称上。
*
* @param array<string,int> $counts
* @return array<string,int>
*/
/**
* 平台筛选值(账户口径)→ 科目映射表里的平台取值。
*
* @param list<string> $labels
* @return list<string>
*/
private function rulePlatforms(array $labels): array
{
$map = [
'淘系支付宝' => ['天猫', '淘宝', '阿里巴巴', '支付宝'],
'淘系微信' => ['天猫', '淘宝'],
'拼多多' => ['拼多多'],
'京东账单' => ['京东'],
'京喜账单' => ['京喜'],
'京东网银钱包' => ['京东'],
'抖音' => ['抖音'],
'得物' => ['得物'],
];
$platforms = [];
foreach ($labels as $label) {
foreach ($map[$label] ?? [$label] as $platform) {
$platforms[$platform] = true;
}
}
return array_keys($platforms);
}
private function normalizeItemCounts(array $counts): array
{
$normalized = [];
foreach ($counts as $item => $count) {
$key = $this->normalizeItem($item);
if ($key === '') {
continue;
}
$normalized[$key] = ($normalized[$key] ?? 0) + $count;
}
return $normalized;
}
/**
* 账单项目 → [平台 => ['memo'=>..,'category'=>..]] 预索引,避免逐项遍历全部规则。
*
* @param array<string,array{memo:string,category:string,catch:bool}> $rules
* @return array<string,array<string,array{memo:string,category:string}>>
*/
private function ruleIndexByItem(array $rules): array
{
$index = [];
foreach ($rules as $key => $rule) {
[$platform, $item] = array_pad(explode('|', $key, 2), 2, '');
if ($platform === '' || $item === '') {
continue;
}
$index[$item][$platform] = ['memo' => $rule['memo'], 'category' => $rule['category']];
}
return $index;
}
/**
* 账单项目行数 → 财务类型 / 财务备注行数。
*
* @param array<string,int> $itemCounts
* @param array<string,array<string,array{memo:string,category:string}>> $itemIndex
* @param list<string> $platforms 平台筛选(为空表示不限平台)
* @return array<string,int>
*/
private function foldItemCounts(array $itemCounts, array $itemIndex, string $field, array $platforms): array
{
$counts = [];
foreach ($itemCounts as $item => $count) {
$values = [];
foreach ($itemIndex[$item] ?? [] as $platform => $rule) {
$value = (string) ($rule[$field] ?? '');
if ($value === '') {
continue;
}
if ($platforms !== [] && ! in_array($platform, $platforms, true)) {
continue;
}
$values[$value] = true;
}
foreach (array_keys($values) as $value) {
$counts[$value] = ($counts[$value] ?? 0) + $count;
}
}
return $counts;
}
/**
* @param array<string,int> $counts
* @param list<string> $order
* @return array{values:list<string>,counts:array<string,int>}
*/
private function shape(array $counts, array $order = []): array
{
$values = [];
foreach ($order as $value) {
if (isset($counts[$value])) {
$values[] = $value;
}
}
$rest = array_values(array_diff(array_keys($counts), $values));
sort($rest, SORT_NATURAL | SORT_FLAG_CASE);
$values = array_merge($values, $rest);
$shaped = [];
foreach ($values as $value) {
$shaped[$value] = (int) $counts[$value];
}
return ['values' => $values, 'counts' => $shaped];
}
private function likeLiteral(string $prefix): string
{
return "'" . str_replace(["\\", "'", '%', '_'], ["\\\\", "''", '\\%', '\\_'], $prefix) . "%'";
}
/**
* 组装单个平台分支:统一的输出列 + 每个账期版本一份「筛选已下推」的 WHERE。
*
@ -404,6 +747,13 @@ class BillingDetailsPageData
$conditions[] = $this->normalizedItemSql() . ' IN (' . $this->literals($allowed) . ')';
}
}
if (($filters['remark'] ?? []) !== []) {
// 财务备注筛选:与财务类型同一口径,先落回「账单项目」集合再下推 SQL。
$allowed = $this->itemsForRemarks($filters['remark']);
$conditions[] = $allowed === []
? '1 = 0'
: $this->normalizedItemSql() . ' IN (' . $this->literals($allowed) . ')';
}
$dateBind = $dateCol === 'bill_date'
? [$filters['start'], $filters['end']]
@ -509,6 +859,7 @@ class BillingDetailsPageData
'store' => $this->values($input['store'] ?? []),
'item' => $this->values($input['item'] ?? []),
'type' => $this->values($input['type'] ?? []),
'remark' => $this->values($input['remark'] ?? []),
'keyword' => trim((string) ($input['keyword'] ?? '')),
'per_page' => $this->perPage($input),
];
@ -644,6 +995,36 @@ class BillingDetailsPageData
return $types;
}
/** @return list<string> 科目映射表里出现过的「财务备注」取值 */
private function remarks(): array
{
$remarks = [];
foreach ($this->rules() as $rule) {
if ($rule['memo'] !== '' && ! in_array($rule['memo'], $remarks, true)) { $remarks[] = $rule['memo']; }
}
sort($remarks);
return $remarks;
}
/**
* 多个财务备注 → 其下所有账单项目的并集。
*
* @param list<string> $remarks
* @return list<string>
*/
private function itemsForRemarks(array $remarks): array
{
$wanted = array_flip($remarks);
$items = [];
foreach ($this->rules() as $key => $rule) {
if (isset($wanted[$rule['memo']])) {
$items[explode('|', $key, 2)[1]] = true;
}
}
return array_keys($items);
}
/** 财务类型 → 该类型下的账单项目集合(用于按类型筛选时保持分页正确) */
private function itemsForType(string $type): array
{

View File

@ -13,7 +13,8 @@
.pd-table-wrap { border:1px solid #d8d2c7; border-radius:.75rem; overflow:auto; background:#fff; }
.pd-table { width:100%; border-collapse:collapse; font-size:.8125rem; }
.pd-table th { background:#1f2937; color:#fff; font-weight:600; text-align:center; padding:.5rem .4rem; white-space:nowrap; }
.pd-table td { border-bottom:1px solid #eee7da; padding:.45rem .5rem; white-space:nowrap; }
.pd-table td { border-bottom:1px solid #eee7da; padding:.6rem .5rem; line-height:1.6; white-space:nowrap; }
.pd-table th { line-height:1.6; }
.pd-table td.num { text-align:right; }
.pd-tag { display:inline-block; padding:.05rem .4rem; border:1px solid #e0d6c2; border-radius:999px; background:#faf6ee; }
.pd-miss { color:#b04a4a; }
@ -101,6 +102,17 @@
<span class="cw-ms__values" data-role="values"></span>
</span>
</div>
<div class="upstream-data-field cw-ms pd-wide" id="pdRemark" data-name="remark"
data-initial="{{ json_encode(array_values($filters['remark'] ?? []), JSON_UNESCAPED_UNICODE) }}">
<span>财务备注</span>
<span class="cw-ms__box">
<button type="button" class="cw-ms__btn" data-role="btn" aria-expanded="false">
<span class="cw-ms__label">全部</span><span class="cw-ms__caret">▾</span>
</button>
<span class="cw-ms__panel" data-role="panel" hidden></span>
<span class="cw-ms__values" data-role="values"></span>
</span>
</div>
<div class="upstream-data-field upstream-data-field--dates">
<span>发生时间</span>
<div class="upstream-data-date-range">
@ -254,19 +266,76 @@
<script>
(function () {
var api = window.CaiWuMultiSelect;
var widgets = [];
if (api) {
[
['pdPlatform', @json(array_values($platforms)), '打字找平台(可多选)'],
['pdStore', @json($options['stores'] ?? []), '打字找店铺(可多选)'],
['pdItem', @json($options['items'] ?? []), '打字找账单项目(可多选)'],
['pdType', @json(array_values($types)), '打字找财务类型(可多选)']
['pdType', @json(array_values($types)), '打字找财务类型(可多选)'],
['pdRemark', @json(array_values($remarks ?? [])), '打字找财务备注(可多选)']
].forEach(function (def) {
var el = document.getElementById(def[0]);
if (el) {
api.create(el, { options: def[1], searchable: true, searchPlaceholder: def[2] });
widgets.push(api.create(el, { options: def[1], searchable: true, searchPlaceholder: def[2] }));
}
});
}
// 筛选联动:按「其它筛选条件」重新统计各筛选项(行数为 0 的不展示),
// 已勾选的值始终保留在列表里,方便取消。与科目映射表 / 业绩明细同一套交互。
var form = document.getElementById('pdFilterForm');
if (api && form && widgets.length) {
var endpoint = @json(route('business.financial-operations.billing-details.filter-options'));
var timer = null;
function currentParams() {
var params = new URLSearchParams();
widgets.forEach(function (widget) {
var name = widget.root.getAttribute('data-name');
(widget.values() || []).forEach(function (value) { params.append(name + '[]', value); });
});
['start', 'end', 'keyword'].forEach(function (name) {
var field = form.querySelector('[name="' + name + '"]');
if (field && field.value.trim()) { params.set(name, field.value.trim()); }
});
return params;
}
function refresh() {
window.fetch(endpoint + '?' + currentParams().toString(), {
headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
credentials: 'same-origin'
}).then(function (response) {
return response.ok ? response.json() : null;
}).then(function (data) {
if (!data || !data.facets) { return; }
widgets.forEach(function (widget) {
var facet = data.facets[widget.root.getAttribute('data-name')];
if (!facet || !facet.values) { return; }
var options = facet.values.slice();
(widget.values() || []).forEach(function (value) {
if (options.indexOf(value) < 0) { options.push(value); }
});
widget.setOptions(options, facet.counts || {});
});
}).catch(function () {
// 联动统计失败时保留原有选项,不影响筛选本身。
});
}
function schedule() {
window.clearTimeout(timer);
timer = window.setTimeout(refresh, 250);
}
widgets.forEach(function (widget) {
widget.root.addEventListener('click', schedule);
widget.root.addEventListener('change', schedule);
});
schedule();
}
if (window.CaiWuDatePicker) {
window.CaiWuDatePicker.setup(document.getElementById('pdFilterForm'));
}

View File

@ -387,6 +387,10 @@ Route::get('workspace/financial-operations/billing-details/export-progress', 'Bu
->middleware('business.page:financial-operations,billing-details')
->name('business.financial-operations.billing-details.export-progress');
Route::get('workspace/financial-operations/billing-details/filter-options', 'Business\Pages@billingDetailsFilterOptions')
->middleware('business.page:financial-operations,billing-details')
->name('business.financial-operations.billing-details.filter-options');
Route::get('workspace/order-data/bill-offset/export', 'Business\Pages@exportBillOffset')
->middleware('business.page:order-data,bill-offset')
->name('business.bill-offset.export');