feat: 新增安装明细客服审核金额汇总 #506

Merged
qiuxiang merged 1 commits from feature/qiuxiang-installation-summary into main 2026-10-24 17:39:21 +08:00
7 changed files with 436 additions and 1 deletions

View File

@ -1057,6 +1057,30 @@ class Pages extends Controller
return response()->json(['data' => $payload['data'], 'has_more' => $payload['has_more'] ?? false]);
}
/** 安装明细页:按客服审核时间汇总安装公司的结算、收款明细金额。 */
public function installationDetailsSummary(): \Illuminate\Http\JsonResponse
{
$section = collect(SidebarPermissions::navigationFor(user()))->firstWhere('slug', 'financial-operations');
abort_unless($section && collect($section['pages'] ?? [])->contains('slug', 'installation-details'), 403, '当前账号没有该页面权限。');
$filters = InstallationDetailMirrorRepository::requestFilters();
if (empty($filters['customer_review_from']) || empty($filters['customer_review_to'])) {
return response()->json(['message' => '请选择完整的客服审核起止日期'], 422);
}
$payload = $this->installationDetails->companySummary($filters);
if (! $payload['ready']) {
return response()->json(['message' => '安装明细镜像尚未完成首次同步'], 503);
}
return response()->json([
'data' => $payload['data'],
'totals' => [
'settled_amount' => $payload['total_settled'],
'received_amount' => $payload['total_received'],
],
], 200, ['Cache-Control' => 'private, no-store']);
}
/**
* 账单明细导出:按页面同一套筛选条件流式导出 CSV(全部筛选结果)。
*/

View File

@ -100,6 +100,91 @@ class InstallationDetailMirrorRepository
return ['rows' => (int) $row->row_count, 'requested' => (float) $row->requested, 'settled' => (float) $row->settled, 'paid' => (float) $row->paid];
}
/**
* 按客服审核时间直接从安装明细子表汇总,并用 SourceGuid 取得最新主表的安装公司。
* 不能先按主表 kfshTime 过滤,否则主表日期更新滞后时会漏掉已同步的明细。
*
* @return array{ready:bool,data:list<array{installation_company:string,settled_amount:float,received_amount:float}>,total_settled:float,total_received:float}
*/
public function companySummary(array $filters = []): array
{
$dataset = $this->datasets->get(self::DATASET);
$items = $this->datasets->get(self::ITEM_DATASET);
$connection = $this->mirror->connection();
if (! $this->ready($dataset, $items, $connection->getName())) {
return ['ready' => false, 'data' => [], 'total_settled' => 0.0, 'total_received' => 0.0];
}
$from = trim((string) ($filters['customer_review_from'] ?? ''));
$to = trim((string) ($filters['customer_review_to'] ?? ''));
if ($from === '' && $to === '') {
return ['ready' => true, 'data' => [], 'total_settled' => 0.0, 'total_received' => 0.0];
}
$query = $connection->table($items->targetTable() . ' AS i')
->whereNotNull('i.kfshTime');
if ($from !== '') {
$query->where('i.kfshTime', '>=', $from);
}
if ($to !== '') {
$query->where('i.kfshTime', '<', \Illuminate\Support\Carbon::parse($to)->addDay()->toDateString());
}
$itemTotals = $query
->selectRaw('i.guid AS guid')
->selectRaw('COALESCE(SUM(CAST(i.settleItemAmount AS DECIMAL(18,2))), 0) AS settled_amount')
->selectRaw('COALESCE(SUM(CAST(i.acceptItemAmount AS DECIMAL(18,2))), 0) AS received_amount')
->groupBy('i.guid')
->get();
$companyByGuid = [];
$guids = $itemTotals->pluck('guid')
->filter(static fn (mixed $guid): bool => trim((string) $guid) !== '')
->unique()
->values()
->all();
foreach (array_chunk($guids, 1000) as $guidChunk) {
$connection->table($dataset->targetTable())
->whereIn('SourceGuid', $guidChunk)
->select(['Id', 'SourceGuid', 'installCompanyName'])
->orderBy('Id')
->get()
->each(static function (object $row) use (&$companyByGuid): void {
$companyByGuid[(string) $row->SourceGuid] = trim((string) ($row->installCompanyName ?? ''));
});
}
$companyTotals = [];
foreach ($itemTotals as $item) {
$company = $companyByGuid[(string) $item->guid] ?? '';
$company = $company !== '' ? $company : '未填写安装公司';
$companyTotals[$company] ??= ['settled_amount' => 0.0, 'received_amount' => 0.0];
$companyTotals[$company]['settled_amount'] += (float) $item->settled_amount;
$companyTotals[$company]['received_amount'] += (float) $item->received_amount;
}
$rows = [];
foreach ($companyTotals as $company => $amounts) {
$rows[] = [
'installation_company' => $company,
'settled_amount' => round($amounts['settled_amount'], 2),
'received_amount' => round($amounts['received_amount'], 2),
];
}
usort($rows, static fn (array $left, array $right): int =>
[$right['settled_amount'], $left['installation_company']]
<=> [$left['settled_amount'], $right['installation_company']]
);
return [
'ready' => true,
'data' => $rows,
'total_settled' => round(array_sum(array_column($rows, 'settled_amount')), 2),
'total_received' => round(array_sum(array_column($rows, 'received_amount')), 2),
];
}
public static function requestFilters(): array
{
$rules = [];

View File

@ -280,6 +280,7 @@
input.value = day.getAttribute('data-calendar-day');
selected = parseIsoDate(input.value);
syncClear();
input.dispatchEvent(new Event('change', { bubbles: true }));
close();
}
});
@ -302,6 +303,7 @@
input.value = '';
selected = null;
syncClear();
input.dispatchEvent(new Event('change', { bubbles: true }));
close();
});
}

View File

@ -274,6 +274,74 @@
display: none;
}
.installation-summary {
grid-column: span 3;
min-width: 0;
align-self: stretch;
overflow: hidden;
border: 1px solid #d8d2c7;
border-radius: 0.5rem;
background: #ffffff;
}
.installation-summary__table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
font-size: 0.6875rem;
font-variant-numeric: tabular-nums;
}
.installation-summary__table th,
.installation-summary__table td {
padding: 0.32rem 0.55rem;
border-bottom: 1px solid #eee8dd;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.installation-summary__table thead th {
background: #f7f0de;
color: #595959;
font-weight: 600;
text-align: left;
}
.installation-summary__table th:not(:first-child),
.installation-summary__table td:not(:first-child) {
text-align: right;
}
.installation-summary__table tbody td {
color: #171717;
}
.installation-summary__table tfoot th,
.installation-summary__table tfoot td {
background: #fcfbf8;
color: #171717;
font-weight: 700;
}
.installation-summary__table tfoot td {
text-align: right;
}
.installation-summary__table tbody tr:last-child td,
.installation-summary__table tfoot tr:last-child th {
border-bottom: 0;
}
.installation-summary__empty {
color: #7a746b;
text-align: center !important;
}
.installation-summary__table[aria-busy="true"] tbody {
opacity: 0.56;
}
.installation-filter-actions {
display: flex;
align-items: center;
@ -283,6 +351,7 @@
@media (max-width: 1100px) {
.installation-filter-bar { grid-template-columns: repeat(2, minmax(14rem, 1fr)); }
.installation-date-filter { grid-column: 1 / -1; }
.installation-summary { grid-column: 1 / -1; }
}
@media (max-width: 650px) {
.installation-filter-bar { grid-template-columns: minmax(0, 1fr); padding: 1rem; }
@ -291,6 +360,7 @@
align-items: stretch;
gap: 0.25rem;
}
.installation-summary { grid-column: 1 / -1; }
}
.biz-card-head {
@ -834,6 +904,33 @@
<a href="{{ request()->url() }}" class="biz-btn biz-btn-ghost">清除</a>
<a href="{{ route('business.installation-details.export', request()->query()) }}" class="biz-btn biz-btn-ghost">导出</a>
</div>
<div
class="installation-summary"
data-installation-summary
data-url="{{ route('business.installation-details.summary') }}"
aria-label="客服审核时间金额汇总"
>
<table class="installation-summary__table" aria-busy="false">
<colgroup>
<col style="width: 38%">
<col style="width: 31%">
<col style="width: 31%">
</colgroup>
<thead>
<tr>
<th scope="col">安装公司</th>
<th scope="col">结算明细金额</th>
<th scope="col">收款明细金额</th>
</tr>
</thead>
<tbody data-installation-summary-body aria-live="polite">
<tr><td colspan="3" class="installation-summary__empty">选择客服审核时间后自动汇总</td></tr>
</tbody>
<tfoot data-installation-summary-total hidden>
<tr><th scope="row">合计</th><td data-summary-settled>¥0.00</td><td data-summary-received>¥0.00</td></tr>
</tfoot>
</table>
</div>
</form>
<script>
(function () {
@ -850,6 +947,139 @@
['customer_review_from', 'customer_review_to'],
['finance_review_from', 'finance_review_to']
];
var summary = form.querySelector('[data-installation-summary]');
var summaryTable = summary && summary.querySelector('.installation-summary__table');
var summaryBody = summary && summary.querySelector('[data-installation-summary-body]');
var summaryTotal = summary && summary.querySelector('[data-installation-summary-total]');
var summarySettled = summary && summary.querySelector('[data-summary-settled]');
var summaryReceived = summary && summary.querySelector('[data-summary-received]');
var customerReviewFrom = form.elements.namedItem('customer_review_from');
var customerReviewTo = form.elements.namedItem('customer_review_to');
var summaryTimer = null;
var summaryController = null;
var summaryRequestId = 0;
var amountFormatter = new Intl.NumberFormat('zh-CN', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
function setSummaryMessage(message) {
if (!summaryBody || !summaryTotal) { return; }
summaryBody.replaceChildren();
var row = document.createElement('tr');
var cell = document.createElement('td');
cell.colSpan = 3;
cell.className = 'installation-summary__empty';
cell.textContent = message;
row.appendChild(cell);
summaryBody.appendChild(row);
summaryTotal.hidden = true;
}
function formatSummaryAmount(value) {
return '¥' + amountFormatter.format(Number(value || 0));
}
function renderSummary(payload) {
if (!summaryBody || !summaryTotal || !summarySettled || !summaryReceived) { return; }
var rows = Array.isArray(payload.data) ? payload.data : [];
summaryBody.replaceChildren();
if (!rows.length) {
setSummaryMessage('当前客服审核时间内没有可汇总明细');
return;
}
rows.forEach(function (item) {
var row = document.createElement('tr');
var company = document.createElement('td');
var settled = document.createElement('td');
var received = document.createElement('td');
company.textContent = item.installation_company || '未填写安装公司';
settled.textContent = formatSummaryAmount(item.settled_amount);
received.textContent = formatSummaryAmount(item.received_amount);
row.append(company, settled, received);
summaryBody.appendChild(row);
});
summarySettled.textContent = formatSummaryAmount(payload.totals && payload.totals.settled_amount);
summaryReceived.textContent = formatSummaryAmount(payload.totals && payload.totals.received_amount);
summaryTotal.hidden = false;
}
function refreshSummary() {
if (!summary || !summaryTable || !customerReviewFrom || !customerReviewTo) { return; }
var from = customerReviewFrom.value;
var to = customerReviewTo.value;
if (!from && !to) {
summaryRequestId++;
if (summaryController) { summaryController.abort(); }
summaryTable.setAttribute('aria-busy', 'false');
setSummaryMessage('选择客服审核时间后自动汇总');
return;
}
if (!from || !to) {
summaryRequestId++;
if (summaryController) { summaryController.abort(); }
summaryTable.setAttribute('aria-busy', 'false');
setSummaryMessage('请选择完整的客服审核起止日期');
return;
}
if (from && to && from > to) {
summaryRequestId++;
if (summaryController) { summaryController.abort(); }
summaryTable.setAttribute('aria-busy', 'false');
setSummaryMessage('结束日期不能早于开始日期');
return;
}
if (summaryController) { summaryController.abort(); }
summaryController = new AbortController();
var requestId = ++summaryRequestId;
var url = new URL(summary.dataset.url, window.location.origin);
url.searchParams.set('customer_review_from', from);
url.searchParams.set('customer_review_to', to);
summaryTable.setAttribute('aria-busy', 'true');
setSummaryMessage('正在汇总…');
fetch(url.toString(), {
credentials: 'same-origin',
headers: { Accept: 'application/json' },
signal: summaryController.signal
})
.then(function (response) {
return response.json().catch(function () { return {}; }).then(function (body) {
if (!response.ok) {
throw new Error(body.message || '金额汇总加载失败');
}
return body;
});
})
.then(function (payload) {
if (requestId !== summaryRequestId) { return; }
renderSummary(payload);
})
.catch(function (error) {
if (error && error.name === 'AbortError') { return; }
if (requestId !== summaryRequestId) { return; }
setSummaryMessage(error.message || '金额汇总加载失败,请稍后重试');
})
.finally(function () {
if (requestId === summaryRequestId) {
summaryTable.setAttribute('aria-busy', 'false');
}
});
}
function scheduleSummary() {
window.clearTimeout(summaryTimer);
summaryTimer = window.setTimeout(refreshSummary, 250);
}
[customerReviewFrom, customerReviewTo].forEach(function (input) {
if (input) { input.addEventListener('change', scheduleSummary); }
});
if (customerReviewFrom && customerReviewTo && (customerReviewFrom.value || customerReviewTo.value)) {
refreshSummary();
}
form.addEventListener('submit', function (event) {
var invalidEnd = null;

View File

@ -565,6 +565,9 @@ Route::get('workspace/fund-management/fund-forecast/template', 'Business\Pages@f
->middleware('business.page:fund-management,fund-forecast')
->name('business.fund-forecast.template');
Route::get('workspace/financial-operations/installation-details/summary', 'Business\Pages@installationDetailsSummary')
->name('business.installation-details.summary');
Route::get('workspace/financial-operations/installation-details/details/{guid}', 'Business\Pages@installationDetails')
->where('guid', '[A-Za-z0-9-]+')
->name('business.installation-details.details');

View File

@ -258,6 +258,13 @@ class ManagementCrudTest extends FeatureTestCase
->assertSee('data-date-calendar', false)
->assertSee("window.CaiWuDatePicker.setup(form)", false)
->assertSee('结束日期不能早于开始日期。')
->assertSee('data-installation-summary', false)
->assertSeeText('安装公司')
->assertSeeText('结算明细金额')
->assertSeeText('收款明细金额')
->assertSeeText('选择客服审核时间后自动汇总')
->assertSee('refreshSummary()', false)
->assertSee("dispatchEvent(new Event('change'", false)
->assertSee('installation-details-table-wrap', false)
->assertSee('installation-details-table', false)
->assertSee('writing-mode: horizontal-tb', false)
@ -310,6 +317,50 @@ class ManagementCrudTest extends FeatureTestCase
->assertJsonPath('data.0.product_name', '测试商品');
}
public function testInstallationSummaryEndpointReturnsCompanyAmountsForCustomerReviewRange(): void
{
$mirror = Mockery::mock(InstallationDetailMirrorRepository::class);
$mirror->shouldReceive('companySummary')->once()->with([
'customer_review_from' => '2026-09-01',
'customer_review_to' => '2026-09-30',
])->andReturn([
'ready' => true,
'data' => [
['installation_company' => '万师傅', 'settled_amount' => 1250.50, 'received_amount' => 1000.00],
['installation_company' => '鲁班到家', 'settled_amount' => 750.00, 'received_amount' => 600.00],
],
'total_settled' => 2000.50,
'total_received' => 1600.00,
]);
$this->app->instance(InstallationDetailMirrorRepository::class, $mirror);
$this->loginAs()
->getJson(route('business.installation-details.summary', [
'customer_review_from' => '2026-09-01',
'customer_review_to' => '2026-09-30',
]))
->assertOk()
->assertJsonPath('data.0.installation_company', '万师傅')
->assertJsonPath('data.0.settled_amount', 1250.5)
->assertJsonPath('data.0.received_amount', 1000)
->assertJsonPath('totals.settled_amount', 2000.5)
->assertJsonPath('totals.received_amount', 1600);
}
public function testInstallationSummaryRequiresCompleteCustomerReviewRange(): void
{
$mirror = Mockery::mock(InstallationDetailMirrorRepository::class);
$mirror->shouldNotReceive('companySummary');
$this->app->instance(InstallationDetailMirrorRepository::class, $mirror);
$this->loginAs()
->getJson(route('business.installation-details.summary', [
'customer_review_from' => '2026-09-01',
]))
->assertUnprocessable()
->assertJsonPath('message', '请选择完整的客服审核起止日期');
}
public function testInstallationChildEndpointRequiresTheSameSidebarPermission(): void
{
$this->withExceptionHandling();
@ -317,8 +368,13 @@ class ManagementCrudTest extends FeatureTestCase
setting()->set('system.sidebar_permissions', ['configured'=>['user_'.$this->user->id], 'subjects'=>['user_'.$this->user->id=>['store-management/basic-information']]]);
$mirror=Mockery::mock(InstallationDetailMirrorRepository::class);
$mirror->shouldNotReceive('details');
$mirror->shouldNotReceive('companySummary');
$this->app->instance(InstallationDetailMirrorRepository::class,$mirror);
$this->loginAs()->getJson(route('business.installation-details.details',['guid'=>'guid-install-test']))->assertForbidden();
$this->loginAs()->getJson(route('business.installation-details.summary', [
'customer_review_from' => '2026-09-01',
'customer_review_to' => '2026-09-30',
]))->assertForbidden();
}
public function testCompanyInformationUsesWorkbookHeadersAndReadOnlyUpstreamRows(): void

View File

@ -32,7 +32,15 @@ class InstallationDetailMirrorRepositoryTest extends TestCase
$t->integer('StatusId')->nullable()->default(0);
foreach(['installcost','settleAmount','acceptAmount'] as $c) $t->decimal($c,14,2)->default(0);
});
$schema->create('fixture_items',function(Blueprint $t){$t->integer('Id');$t->string('guid');$t->string('shopproid');$t->string('Sourceno')->nullable();});
$schema->create('fixture_items',function(Blueprint $t){
$t->integer('Id');
$t->string('guid');
$t->string('shopproid');
$t->string('Sourceno')->nullable();
$t->dateTime('kfshTime')->nullable();
$t->decimal('settleItemAmount',14,2)->default(0);
$t->decimal('acceptItemAmount',14,2)->default(0);
});
foreach(array_keys($definitions) as $key) DB::connection('business_mirror')->table('business_mirror_table_states')->insert(['dataset_key'=>$key,'initial_completed_at'=>'2026-08-01']);
DB::connection('business_mirror')->table('fixture_install')->insert([
['Id'=>1,'SourceGuid'=>'A','OrderNum'=>'OLD','shop_name'=>'旧店','SubmitTime'=>'2026-08-01','installcost'=>500],
@ -105,6 +113,33 @@ class InstallationDetailMirrorRepositoryTest extends TestCase
}
}
public function test_company_summary_uses_item_review_time_and_latest_main_company(): void
{
DB::connection('business_mirror')->table('fixture_install')->where('Id',1)->update(['installCompanyName'=>'旧公司']);
DB::connection('business_mirror')->table('fixture_install')->where('Id',2)->update(['installCompanyName'=>'万师傅']);
DB::connection('business_mirror')->table('fixture_install')->where('Id',3)->update(['installCompanyName'=>'鲁班到家']);
DB::connection('business_mirror')->table('fixture_install')->where('Id',4)->update(['installCompanyName'=>'万师傅']);
DB::connection('business_mirror')->table('fixture_items')->insert([
['Id'=>20,'guid'=>'A','shopproid'=>'P1','Sourceno'=>'A-1','kfshTime'=>'2026-09-01 09:00:00','settleItemAmount'=>60.10,'acceptItemAmount'=>40.00],
['Id'=>21,'guid'=>'A','shopproid'=>'P2','Sourceno'=>'A-1','kfshTime'=>'2026-09-30 18:00:00','settleItemAmount'=>39.90,'acceptItemAmount'=>0.00],
['Id'=>22,'guid'=>'B','shopproid'=>'P3','Sourceno'=>'B-1','kfshTime'=>'2026-09-15 10:00:00','settleItemAmount'=>80.00,'acceptItemAmount'=>70.00],
['Id'=>23,'guid'=>'C','shopproid'=>'P4','Sourceno'=>'C-1','kfshTime'=>'2026-10-01 00:00:00','settleItemAmount'=>500.00,'acceptItemAmount'=>500.00],
]);
$result=$this->repository->companySummary([
'customer_review_from'=>'2026-09-01',
'customer_review_to'=>'2026-09-30',
]);
$this->assertTrue($result['ready']);
$this->assertSame([
['installation_company'=>'万师傅','settled_amount'=>100.0,'received_amount'=>40.0],
['installation_company'=>'鲁班到家','settled_amount'=>80.0,'received_amount'=>70.0],
],$result['data']);
$this->assertSame(180.0,$result['total_settled']);
$this->assertSame(110.0,$result['total_received']);
}
public function test_end_date_alone_is_valid_and_invalid_status_is_rejected(): void
{
request()->merge(['created_to'=>'2026-08-20']);