feat(退款待确认): 增加申请时间下钻明细 (#1444)

按退款月份数量查看申请日期分布,再点击具体日期加载待确认明细。
This commit is contained in:
renshen 2026-11-26 10:45:48 +08:00
parent 2386c92a15
commit a65b0b41ff
6 changed files with 626 additions and 84 deletions

View File

@ -44,6 +44,7 @@ use App\Business\CourierSurchargeTypeRepository;
use App\Models\StoreReceivables\StoreZhongcaiReconciliation;
use App\Utilities\BusinessOperationPermissions;
use App\Utilities\SidebarPermissions;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Pagination\LengthAwarePaginator;
@ -8035,30 +8036,19 @@ class Pages extends Controller
public function refundPendingMonthDetails(Request $request)
{
$month = trim((string) $request->query('month', ''));
$allMonths = $month === '' || $month === 'all';
if (! $allMonths && preg_match('/^\d{4}-\d{2}$/', $month) !== 1) {
return response()->json(['message' => '退款月份格式不正确'], 422);
$window = $this->refundPendingMonthWindow($request);
if ($window instanceof JsonResponse) {
return $window;
}
['month' => $monthKey, 'start' => $start, 'end' => $end] = $window;
$today = now()->startOfDay();
if ($allMonths) {
$monthKey = 'all';
$start = Carbon::createFromFormat('!Y-m-d', '2026-10-01')->startOfDay();
$end = $today;
} else {
$monthKey = $month;
$start = Carbon::createFromFormat('!Y-m', $month)->startOfMonth();
if ($start->format('Y-m') < '2026-10' || $start->greaterThan($today)) {
return response()->json(['message' => '退款月份超出可查询范围'], 422);
}
$end = $start->copy()->endOfMonth()->startOfDay();
if ($end->greaterThan($today)) {
$end = $today;
}
}
$platform = mb_substr(trim((string) $request->query('platform', '')), 0, 120);
$applicationDate = trim((string) $request->query('application_date', ''));
if ($applicationDate !== ''
&& $applicationDate !== 'unknown'
&& preg_match('/^\d{4}-\d{2}-\d{2}$/', $applicationDate) !== 1) {
return response()->json(['message' => '申请时间格式不正确'], 422);
}
$page = max((int) $request->query('page', 1), 1);
$limit = min(max((int) $request->query('limit', 25), 1), 50);
$filters = [
@ -8070,6 +8060,9 @@ class Pages extends Controller
'sku_id' => '',
'platform' => $platform,
];
if ($applicationDate !== '') {
$filters['application_date'] = $applicationDate;
}
try {
if (! $this->nonJingxiRefunds->available()
@ -8079,8 +8072,9 @@ class Pages extends Controller
}
$platformKey = sha1($platform);
$applicationDateKey = sha1($applicationDate);
$details = \Illuminate\Support\Facades\Cache::remember(
"refund-pending.details.v3:{$monthKey}:{$end->toDateString()}:{$platformKey}:{$page}:{$limit}",
"refund-pending.details.v4:{$monthKey}:{$end->toDateString()}:{$platformKey}:{$applicationDateKey}:{$page}:{$limit}",
now()->addMinutes(5),
function () use ($filters, $page, $limit): array {
$result = $this->nonJingxiRefunds->pagePendingConfirmation($filters, $page, $limit);
@ -8095,6 +8089,7 @@ class Pages extends Controller
'shop_name' => (string) ($row->shop_name ?? ''),
'platform' => (string) ($row->platform ?? ''),
'refund_date' => (string) ($row->refundDate ?? ''),
'application_time' => (string) ($row->createTime ?? ''),
'status' => (string) ($row->status ?? ''),
'online_status' => (string) ($row->shop_status ?? ''),
'after_sales_amount' => $row->AfSalesMoney ?? null,
@ -8116,6 +8111,7 @@ class Pages extends Controller
return response()->json([
'month' => $monthKey,
'platform' => $platform,
'application_date' => $applicationDate,
'page' => $page,
'limit' => $limit,
'has_more' => $details['has_more'],
@ -8123,6 +8119,85 @@ class Pages extends Controller
], 200, ['Cache-Control' => 'private, no-store']);
}
public function refundPendingApplicationSummary(Request $request)
{
$window = $this->refundPendingMonthWindow($request);
if ($window instanceof JsonResponse) {
return $window;
}
['month' => $monthKey, 'start' => $start, 'end' => $end] = $window;
$platform = mb_substr(trim((string) $request->query('platform', '')), 0, 120);
$filters = [
'from' => $start->toDateString(),
'to' => $end->toDateString(),
'order_no' => '',
'waybill_no' => '',
'shop_name' => '',
'sku_id' => '',
'platform' => $platform,
];
try {
if (! $this->nonJingxiRefunds->available()
|| ! $this->nonJingxiRefunds->ready()
|| ! $this->nonJingxiRefunds->queryReady()) {
return response()->json(['message' => '退款待确认镜像尚未就绪'], 503);
}
$platformKey = sha1($platform);
$summary = \Illuminate\Support\Facades\Cache::remember(
"refund-pending.application-summary.v1:{$monthKey}:{$end->toDateString()}:{$platformKey}",
now()->addMinutes(5),
fn (): array => $this->nonJingxiRefunds->pendingConfirmationApplicationDailySummary($filters),
);
} catch (Throwable $exception) {
report($exception);
return response()->json(['message' => '退款待确认申请时间统计暂时无法读取'], 503);
}
return response()->json([
'month' => $monthKey,
'platform' => $platform,
'total' => (int) ($summary['total'] ?? 0),
'rows' => $summary['rows'] ?? [],
], 200, ['Cache-Control' => 'private, no-store']);
}
/**
* @return array{month:string,start:Carbon,end:Carbon}|JsonResponse
*/
private function refundPendingMonthWindow(Request $request): array|JsonResponse
{
$month = trim((string) $request->query('month', ''));
$allMonths = $month === '' || $month === 'all';
if (! $allMonths && preg_match('/^\d{4}-\d{2}$/', $month) !== 1) {
return response()->json(['message' => '退款月份格式不正确'], 422);
}
$today = now()->startOfDay();
if ($allMonths) {
return [
'month' => 'all',
'start' => Carbon::createFromFormat('!Y-m-d', '2026-10-01')->startOfDay(),
'end' => $today,
];
}
$start = Carbon::createFromFormat('!Y-m', $month)->startOfMonth();
if ($start->format('Y-m') < '2026-10' || $start->greaterThan($today)) {
return response()->json(['message' => '退款月份超出可查询范围'], 422);
}
$end = $start->copy()->endOfMonth()->startOfDay();
if ($end->greaterThan($today)) {
$end = $today;
}
return ['month' => $month, 'start' => $start, 'end' => $end];
}
public function exportAfterSalesReturnRefunds(Request $request)
{
return $this->exportRefundRows(

View File

@ -56,6 +56,14 @@ class NonJingxiRefundMirrorRepository
private ?string $supplementDateIndex = null;
private ?bool $availableCache = null;
private ?bool $readyCache = null;
private ?bool $queryReadyCache = null;
private ?bool $pendingStatusReadyCache = null;
public function __construct(
private readonly BusinessMirrorDatasetRegistry $datasets,
private readonly GenericBusinessMirrorRepository $mirror,
@ -65,62 +73,102 @@ class NonJingxiRefundMirrorRepository
public function available(): bool
{
$schema = Schema::connection($this->connection->getName());
if ($this->availableCache !== null) {
return $this->availableCache;
}
return $schema->hasTable('business_mirror_table_states')
&& collect([self::INFO_DATASET, self::ITEM_DATASET, self::SUPPLEMENT_DATASET, self::SUPPLEMENT_ITEM_DATASET, self::SHOP_DATASET])
->every(fn (string $key): bool => $schema->hasTable($this->dataset($key)->targetTable()));
return $this->availableCache = cache()->remember(
'refund-pending.available.v1',
now()->addMinute(),
function (): bool {
$schema = Schema::connection($this->connection->getName());
return $schema->hasTable('business_mirror_table_states')
&& collect([self::INFO_DATASET, self::ITEM_DATASET, self::SUPPLEMENT_DATASET, self::SUPPLEMENT_ITEM_DATASET, self::SHOP_DATASET])
->every(fn (string $key): bool => $schema->hasTable($this->dataset($key)->targetTable()));
},
);
}
public function ready(): bool
{
return collect([self::INFO_DATASET, self::ITEM_DATASET, self::SUPPLEMENT_DATASET, self::SUPPLEMENT_ITEM_DATASET, self::SHOP_DATASET])
->every(fn (string $key): bool => $this->mirror->ready($this->dataset($key)));
if ($this->readyCache !== null) {
return $this->readyCache;
}
return $this->readyCache = cache()->remember(
'refund-pending.mirror-ready.v1',
now()->addMinute(),
fn (): bool => collect([self::INFO_DATASET, self::ITEM_DATASET, self::SUPPLEMENT_DATASET, self::SUPPLEMENT_ITEM_DATASET, self::SHOP_DATASET])
->every(fn (string $key): bool => $this->mirror->ready($this->dataset($key))),
);
}
public function pendingConfirmationStatusReady(): bool
{
if ($this->pendingStatusReadyCache !== null) {
return $this->pendingStatusReadyCache;
}
try {
return Schema::connection($this->connection->getName())->hasTable('ops_jst_refund_status')
&& $this->mirror->ready($this->dataset(self::STATUS_DATASET));
return $this->pendingStatusReadyCache = cache()->remember(
'refund-pending.status-ready.v1',
now()->addMinute(),
fn (): bool => Schema::connection($this->connection->getName())->hasTable('ops_jst_refund_status')
&& $this->mirror->ready($this->dataset(self::STATUS_DATASET)),
);
} catch (\Throwable) {
return false;
return $this->pendingStatusReadyCache = false;
}
}
public function queryReady(): bool
{
$schema = Schema::connection($this->connection->getName());
try {
foreach (self::REQUIRED_QUERY_INDEXES as $datasetKey => $requiredIndexes) {
$table = $this->dataset($datasetKey)->targetTable();
if (! $schema->hasTable($table)) {
return false;
}
$tableIndexes = collect($schema->getIndexes($table));
if ($datasetKey === self::SUPPLEMENT_DATASET) {
$this->supplementDateIndex = $tableIndexes->first(
static fn (array $index): bool => array_map('strtolower', $index['columns']) === ['as_date', 'as_id']
)['name'] ?? null;
}
$indexes = $tableIndexes
->map(static fn (array $index): array => array_map(
'strtolower',
(array) ($index['columns'] ?? []),
));
foreach ($requiredIndexes as $required) {
if (! $indexes->contains(array_map('strtolower', $required))) {
return false;
}
}
}
} catch (\Throwable) {
return false;
if ($this->queryReadyCache !== null) {
return $this->queryReadyCache;
}
return true;
$state = cache()->remember(
'refund-pending.query-ready.v2',
now()->addMinute(),
function (): array {
$schema = Schema::connection($this->connection->getName());
$supplementDateIndex = null;
try {
foreach (self::REQUIRED_QUERY_INDEXES as $datasetKey => $requiredIndexes) {
$table = $this->dataset($datasetKey)->targetTable();
if (! $schema->hasTable($table)) {
return ['ready' => false, 'supplement_date_index' => null];
}
$tableIndexes = collect($schema->getIndexes($table));
if ($datasetKey === self::SUPPLEMENT_DATASET) {
$supplementDateIndex = $tableIndexes->first(
static fn (array $index): bool => array_map('strtolower', $index['columns']) === ['as_date', 'as_id']
)['name'] ?? null;
}
$indexes = $tableIndexes
->map(static fn (array $index): array => array_map(
'strtolower',
(array) ($index['columns'] ?? []),
));
foreach ($requiredIndexes as $required) {
if (! $indexes->contains(array_map('strtolower', $required))) {
return ['ready' => false, 'supplement_date_index' => $supplementDateIndex];
}
}
}
} catch (\Throwable) {
return ['ready' => false, 'supplement_date_index' => null];
}
return ['ready' => true, 'supplement_date_index' => $supplementDateIndex];
},
);
$this->supplementDateIndex = $state['supplement_date_index'] ?? null;
return $this->queryReadyCache = (bool) ($state['ready'] ?? false);
}
/** @return array<string,array<string,mixed>|null> */
@ -344,6 +392,57 @@ class NonJingxiRefundMirrorRepository
return array_values($months);
}
/**
* 按售后申请时间汇总当前月份、平台下的待确认记录。
*
* @param array{from:string,to:string,order_no:string,waybill_no:string,shop_name:string,sku_id:string,platform?:string} $filters
* @return array{rows:list<array{application_date:string,count:int}>,total:int}
*/
public function pendingConfirmationApplicationDailySummary(array $filters): array
{
$this->assertPendingStatusReady();
if (! $this->ready() || ! $this->queryReady()) {
throw new RuntimeException('business_mirror_dataset_not_ready');
}
$pendingFilters = $this->pendingConfirmationFilters($filters);
$counts = [];
foreach ([false, true] as $supplement) {
$dateExpression = $this->applicationDateExpression($supplement);
$rows = $this->sourceQuery($pendingFilters, $supplement, false)
->selectRaw("{$dateExpression} AS application_date, COUNT(*) AS total")
->groupByRaw($dateExpression)
->get();
foreach ($rows as $row) {
$date = trim((string) ($row->application_date ?? ''));
$date = $date !== '' ? $date : 'unknown';
$counts[$date] = (int) ($counts[$date] ?? 0) + (int) ($row->total ?? 0);
}
}
uksort($counts, static function (string $left, string $right): int {
if ($left === 'unknown') {
return $right === 'unknown' ? 0 : 1;
}
if ($right === 'unknown') {
return -1;
}
return strcmp($right, $left);
});
return [
'rows' => collect($counts)
->map(static fn (int $count, string $date): array => [
'application_date' => $date,
'count' => $count,
])
->values()
->all(),
'total' => array_sum($counts),
];
}
/**
* 按平台和退款月份汇总待确认记录,并同时返回月份总计。
*
@ -616,6 +715,7 @@ class NonJingxiRefundMirrorRepository
}
$this->applyPlatformFilter($query, $filters, $supplement);
$this->applyFilters($query, $filters, $statusAlias, $statusAuthoritative);
$this->applyApplicationDateFilter($query, $filters, $supplement);
if ($filters['sku_id'] !== '') {
if ($withItems) {
$this->applySkuFilter($query, $filters['sku_id']);
@ -630,6 +730,37 @@ class NonJingxiRefundMirrorRepository
return $query;
}
/**
* @param array{application_date?:string} $filters
*/
private function applyApplicationDateFilter(Builder $query, array $filters, bool $supplement): void
{
$value = trim((string) ($filters['application_date'] ?? ''));
if ($value === '') {
return;
}
$column = $supplement ? 'r.local_created' : 'r.createTime';
if ($value === 'unknown') {
$query->whereNull($column);
return;
}
$start = Carbon::parse($value)->toDateString();
$query->where($column, '>=', $start . ' 00:00:00')
->where($column, '<', Carbon::parse($start)->addDay()->toDateString() . ' 00:00:00');
}
private function applicationDateExpression(bool $supplement): string
{
$column = $supplement ? 'r.local_created' : 'r.createTime';
return $this->connection->getDriverName() === 'sqlite'
? "strftime('%Y-%m-%d', {$column})"
: "DATE({$column})";
}
private const SORT_COLUMNS = ['refundDate', '_source_rank', '_head_id', '_source_id', '_item_id'];
private function orderedKeys(array $filters, ?object $cursor, int $limit): Builder

View File

@ -282,6 +282,101 @@
color: var(--vip-content-muted, #595959);
font-size: 0.75rem;
}
.refund-application-summary {
border: 1px solid var(--vip-border, #d8d2c7);
border-radius: 8px;
background: var(--vip-surface, #ffffff);
}
.refund-application-summary__head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 0.75rem;
padding: 0.7rem 0.85rem;
border-bottom: 1px solid var(--vip-border, #d8d2c7);
background: var(--vip-content-accent-soft, #f7f0de);
}
.refund-application-summary__head strong {
color: var(--vip-content-ink, #171717);
font-size: 0.78rem;
font-weight: 600;
}
.refund-application-summary__head span {
color: var(--vip-content-muted, #595959);
font-size: 0.72rem;
}
.refund-application-summary__scroll {
overflow: auto;
max-height: 18rem;
}
.refund-application-summary__table {
width: 100%;
border-collapse: collapse;
font-size: 0.75rem;
}
.refund-application-summary__table th,
.refund-application-summary__table td {
padding: 0.48rem 0.8rem;
border-bottom: 1px solid var(--vip-border, #d8d2c7);
text-align: left;
white-space: nowrap;
}
.refund-application-summary__table th {
position: sticky;
top: 0;
z-index: 1;
color: var(--vip-content-muted, #595959);
background: var(--vip-surface, #ffffff);
font-size: 0.72rem;
font-weight: 500;
}
.refund-application-summary__table td:last-child,
.refund-application-summary__table th:last-child { text-align: right; }
.refund-application-summary__table tr.is-selected td {
background: var(--vip-content-accent-soft, #f7f0de);
}
.refund-application-date-count {
min-width: 3rem;
min-height: 1.7rem;
padding: 0 0.45rem;
border: 1px solid transparent;
border-radius: 4px;
background: transparent;
color: var(--vip-content-accent-dark, #856632);
font: inherit;
font-variant-numeric: tabular-nums;
text-decoration: underline dotted;
text-underline-offset: 3px;
cursor: pointer;
}
.refund-application-date-count:hover,
.refund-application-date-count[aria-pressed="true"] {
border-color: var(--vip-content-accent, #b9954f);
background: var(--vip-content-accent-soft, #f7f0de);
text-decoration-style: solid;
}
.refund-application-date-count:focus-visible {
outline: 2px solid var(--vip-content-accent-dark, #856632);
outline-offset: 1px;
}
.refund-summary-detail__records {
margin-top: 0.9rem;
padding-top: 0.85rem;
border-top: 1px solid var(--vip-border, #d8d2c7);
}
.refund-summary-detail__records[hidden] { display: none; }
.refund-summary-detail__records-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
margin-bottom: 0.6rem;
}
.refund-summary-detail__records-title {
color: var(--vip-content-ink, #171717);
font-size: 0.78rem;
font-weight: 600;
}
.refund-summary-detail__scroll {
overflow: auto;
max-height: min(34rem, 62vh);
@ -406,11 +501,12 @@
class="refund-month-summary"
data-refund-month-summary
data-details-url="{{ route('business.refunds.refund-pending.month-details') }}"
data-application-summary-url="{{ route('business.refunds.refund-pending.application-summary') }}"
>
<div class="refund-month-summary__head">
<div class="refund-month-summary__heading">
<strong>按退款月份统计</strong>
<span>点击汇总数字查看对应待确认明细</span>
<span>点击汇总数字查看申请时间分布,再点日期查看待确认明细</span>
</div>
@if ($refundShowExport)
<a
@ -513,17 +609,30 @@
@endif
<section class="refund-summary-detail" data-refund-summary-detail hidden>
<div class="refund-summary-detail__head">
<strong class="refund-summary-detail__title" data-refund-summary-detail-title>待确认明细</strong>
<strong class="refund-summary-detail__title" data-refund-summary-detail-title>申请时间分布</strong>
<button type="button" class="refund-summary-detail__close" data-refund-summary-detail-close>关闭</button>
</div>
<div class="refund-summary-detail__status" role="status" data-refund-summary-detail-status>请选择汇总数字查看明细。</div>
<div class="refund-summary-detail__scroll" data-refund-summary-detail-scroll hidden></div>
<div class="refund-summary-detail__pagination" data-refund-summary-detail-pagination hidden>
<span data-refund-summary-detail-page-label></span>
<span>
<button type="button" data-refund-summary-detail-page="-1">上一页</button>
<button type="button" data-refund-summary-detail-page="1">下一页</button>
</span>
<section class="refund-application-summary" data-refund-application-summary hidden>
<div class="refund-application-summary__head">
<strong data-refund-application-title>按申请时间统计</strong>
<span>点击右侧数量查看当日明细</span>
</div>
<div class="refund-summary-detail__status" role="status" data-refund-application-status>正在统计申请时间…</div>
<div class="refund-application-summary__scroll" data-refund-application-scroll hidden></div>
</section>
<div class="refund-summary-detail__records" data-refund-summary-detail-records hidden>
<div class="refund-summary-detail__records-head">
<strong class="refund-summary-detail__records-title" data-refund-summary-records-title>待确认明细</strong>
</div>
<div class="refund-summary-detail__status" role="status" data-refund-summary-detail-status>请选择申请日期查看明细。</div>
<div class="refund-summary-detail__scroll" data-refund-summary-detail-scroll hidden></div>
<div class="refund-summary-detail__pagination" data-refund-summary-detail-pagination hidden>
<span data-refund-summary-detail-page-label></span>
<span>
<button type="button" data-refund-summary-detail-page="-1">上一页</button>
<button type="button" data-refund-summary-detail-page="1">下一页</button>
</span>
</div>
</div>
</section>
</div>
@ -536,6 +645,12 @@
const detailPanel = root.querySelector('[data-refund-summary-detail]');
const detailTitle = root.querySelector('[data-refund-summary-detail-title]');
const applicationSummary = root.querySelector('[data-refund-application-summary]');
const applicationTitle = root.querySelector('[data-refund-application-title]');
const applicationStatus = root.querySelector('[data-refund-application-status]');
const applicationScroll = root.querySelector('[data-refund-application-scroll]');
const detailRecords = root.querySelector('[data-refund-summary-detail-records]');
const recordsTitle = root.querySelector('[data-refund-summary-records-title]');
const detailStatus = root.querySelector('[data-refund-summary-detail-status]');
const detailScroll = root.querySelector('[data-refund-summary-detail-scroll]');
const pagination = root.querySelector('[data-refund-summary-detail-pagination]');
@ -548,6 +663,7 @@
['店铺名称', 'shop_name'],
['平台', 'platform'],
['退款日期', 'refund_date'],
['申请时间', 'application_time'],
['状态', 'status'],
['线上状态', 'online_status'],
['售后金额', 'after_sales_amount', true],
@ -557,8 +673,9 @@
['明细退款金额', 'detail_refund_amount', true],
['运单号', 'waybill_no'],
];
const selected = { month: '', platform: '', page: 1 };
let requestSerial = 0;
const selected = { month: '', platform: '', applicationDate: '', page: 1 };
let summarySerial = 0;
let detailSerial = 0;
const textValue = (value) => {
const text = value === null || value === undefined ? '' : String(value).trim();
@ -580,6 +697,7 @@
const [year, monthNumber] = month.split('-');
return `${year}年${Number(monthNumber)}月`;
};
const applicationDateLabel = (date) => date === 'unknown' ? '申请时间为空' : date;
const detailLabel = () => `${monthLabel(selected.month)} · ${selected.platform || '全部平台'}`;
const copyStateTimers = new WeakMap();
const fallbackCopy = (text) => {
@ -621,6 +739,55 @@
}
};
const selectApplicationDate = (date) => {
selected.applicationDate = date;
root.querySelectorAll('[data-refund-application-date]').forEach((button) => {
const active = button.dataset.refundApplicationDate === date;
button.setAttribute('aria-pressed', active ? 'true' : 'false');
button.closest('tr')?.classList.toggle('is-selected', active);
});
};
const renderApplicationSummary = (payload) => {
const table = document.createElement('table');
table.className = 'refund-application-summary__table';
const head = document.createElement('thead');
const headRow = document.createElement('tr');
['申请日期', '异常数量'].forEach((label) => {
const th = document.createElement('th');
th.textContent = label;
headRow.appendChild(th);
});
head.appendChild(headRow);
table.appendChild(head);
const body = document.createElement('tbody');
payload.rows.forEach((row) => {
const tr = document.createElement('tr');
const dateCell = document.createElement('td');
dateCell.textContent = applicationDateLabel(row.application_date);
const countCell = document.createElement('td');
const button = document.createElement('button');
button.type = 'button';
button.className = 'refund-application-date-count';
button.dataset.refundApplicationDate = row.application_date;
button.setAttribute('aria-pressed', 'false');
button.setAttribute(
'aria-label',
`查看${applicationDateLabel(row.application_date)} ${Number(row.count).toLocaleString('zh-CN')} 条待确认明细`,
);
button.textContent = Number(row.count).toLocaleString('zh-CN');
countCell.appendChild(button);
tr.append(dateCell, countCell);
body.appendChild(tr);
});
table.appendChild(body);
applicationTitle.textContent = `按申请时间统计 · 共 ${Number(payload.total).toLocaleString('zh-CN')} 条`;
applicationScroll.replaceChildren(table);
applicationScroll.hidden = false;
applicationStatus.hidden = true;
};
const render = (payload) => {
const table = document.createElement('table');
table.className = 'refund-summary-detail__table';
@ -650,7 +817,7 @@
if (isNumber) cell.className = 'is-number';
const value = key.includes('amount') || key === 'quantity'
? moneyValue(data[key])
: key === 'refund_date'
: key === 'refund_date' || key === 'application_time'
? dateValue(data[key])
: textValue(data[key]);
cell.textContent = value;
@ -669,6 +836,7 @@
detailScroll.hidden = false;
detailStatus.hidden = true;
pagination.hidden = false;
recordsTitle.textContent = `${applicationDateLabel(selected.applicationDate)} · 待确认明细`;
pagination.dataset.currentPage = String(payload.page);
root.querySelector('[data-refund-summary-detail-page-label]').textContent =
`明细第 ${payload.page} 页 · 当前显示 ${Number(payload.rows.length).toLocaleString('zh-CN')} 条`;
@ -676,11 +844,49 @@
root.querySelector('[data-refund-summary-detail-page="1"]').disabled = !payload.has_more;
};
const load = async (page = 1) => {
selected.page = page;
const serial = ++requestSerial;
const loadApplicationSummary = async () => {
const serial = ++summarySerial;
detailSerial += 1;
selected.applicationDate = '';
selected.page = 1;
detailPanel.hidden = false;
detailTitle.textContent = detailLabel();
applicationSummary.hidden = false;
applicationScroll.hidden = true;
applicationScroll.replaceChildren();
applicationStatus.hidden = false;
applicationStatus.textContent = '正在统计申请时间…';
detailRecords.hidden = true;
detailScroll.hidden = true;
pagination.hidden = true;
detailTitle.textContent = `${detailLabel()} · 申请时间分布`;
const url = new URL(root.dataset.applicationSummaryUrl, window.location.origin);
url.searchParams.set('month', selected.month || 'all');
if (selected.platform) url.searchParams.set('platform', selected.platform);
try {
const response = await fetch(url, {
credentials: 'same-origin',
headers: { Accept: 'application/json' },
});
if (!response.ok) throw new Error('request_failed');
const payload = await response.json();
if (serial !== summarySerial) return;
if (!payload.rows.length) {
applicationStatus.textContent = '当前范围没有可统计的申请日期。';
return;
}
renderApplicationSummary(payload);
} catch (_) {
if (serial !== summarySerial) return;
applicationStatus.hidden = false;
applicationStatus.textContent = '申请时间统计加载失败,请稍后重试。';
}
};
const loadDetails = async (page = 1) => {
selected.page = page;
const serial = ++detailSerial;
detailRecords.hidden = false;
detailStatus.hidden = false;
detailStatus.textContent = '正在加载明细数据…';
detailScroll.hidden = true;
@ -688,6 +894,7 @@
const url = new URL(root.dataset.detailsUrl, window.location.origin);
url.searchParams.set('month', selected.month || 'all');
if (selected.platform) url.searchParams.set('platform', selected.platform);
url.searchParams.set('application_date', selected.applicationDate);
url.searchParams.set('page', String(page));
try {
const response = await fetch(url, {
@ -696,10 +903,10 @@
});
if (!response.ok) throw new Error('request_failed');
const payload = await response.json();
if (serial !== requestSerial) return;
if (serial !== detailSerial) return;
render(payload);
} catch (_) {
if (serial !== requestSerial) return;
if (serial !== detailSerial) return;
detailStatus.hidden = false;
detailStatus.textContent = '明细加载失败,请稍后重试。';
}
@ -711,11 +918,18 @@
button.setAttribute('aria-pressed', 'true');
selected.month = button.dataset.refundDetailMonth || '';
selected.platform = button.dataset.refundDetailPlatform || '';
load(1);
loadApplicationSummary();
window.requestAnimationFrame(() => detailPanel.scrollIntoView({ behavior: 'smooth', block: 'nearest' }));
});
});
applicationScroll.addEventListener('click', (event) => {
const button = event.target.closest('[data-refund-application-date]');
if (!button) return;
selectApplicationDate(button.dataset.refundApplicationDate || '');
loadDetails(1);
});
detailScroll.addEventListener('click', (event) => {
const cell = event.target.closest('td.is-copyable');
if (cell) copyCell(cell);
@ -732,13 +946,16 @@
button.addEventListener('click', () => {
const current = Number(pagination.dataset.currentPage || 1);
const next = Math.max(current + Number(button.dataset.refundSummaryDetailPage), 1);
if (next !== current) load(next);
if (next !== current) loadDetails(next);
});
});
root.querySelector('[data-refund-summary-detail-close]').addEventListener('click', () => {
requestSerial += 1;
summarySerial += 1;
detailSerial += 1;
detailPanel.hidden = true;
applicationSummary.hidden = true;
detailRecords.hidden = true;
triggers.forEach((item) => item.setAttribute('aria-pressed', 'false'));
});
})();

View File

@ -567,6 +567,10 @@ Route::get('workspace/fee-ratio-monitoring/refund-pending/month-details', 'Busin
->middleware('business.page:fee-ratio-monitoring,refund-pending')
->name('business.refunds.refund-pending.month-details');
Route::get('workspace/fee-ratio-monitoring/refund-pending/application-summary', 'Business\Pages@refundPendingApplicationSummary')
->middleware('business.page:fee-ratio-monitoring,refund-pending')
->name('business.refunds.refund-pending.application-summary');
Route::get('workspace/refunds/refund-pending/export', 'Business\Pages@redirectLegacyRefundPendingExport')
->name('business.refunds.refund-pending.legacy-export');

View File

@ -197,12 +197,15 @@ class NonJingxiRefundPageTest extends FeatureTestCase
->assertSeeText('天猫')
->assertSeeText('2026年10月')
->assertSeeText('2026年11月')
->assertSeeText('点击汇总数字查看对应待确认明细')
->assertSeeText('点击汇总数字查看申请时间分布,再点日期查看待确认明细')
->assertSeeText('月度合计')
->assertSee('data-refund-detail-trigger', false)
->assertSee('data-refund-detail-month="2026-10"', false)
->assertSee('data-refund-detail-platform="京东商城"', false)
->assertSee('data-refund-summary-detail', false)
->assertSee('data-refund-application-summary', false)
->assertSee('refund-application-date-count', false)
->assertSeeText('按申请时间统计')
->assertDontSee('data-refund-month-toggle', false)
->assertDontSeeText('5,641 条待确认')
->assertSeeText('导出全部明细')
@ -214,7 +217,8 @@ class NonJingxiRefundPageTest extends FeatureTestCase
->assertDontSee('data-refund-month-export', false)
->assertSee('data-refund-page="pending-confirmation"', false)
->assertSee('data-refund-month-summary', false)
->assertSee('workspace/fee-ratio-monitoring/refund-pending/month-details', false);
->assertSee('workspace/fee-ratio-monitoring/refund-pending/month-details', false)
->assertSee('workspace/fee-ratio-monitoring/refund-pending/application-summary', false);
}
public function test_refund_pending_hides_export_and_blocks_export_url_without_operation_permission(): void
@ -279,6 +283,7 @@ class NonJingxiRefundPageTest extends FeatureTestCase
'shop_name' => '',
'sku_id' => '',
'platform' => '京东商城',
'application_date' => '2026-10-29',
] && $page === 2 && $limit === 25
)->andReturn([
'data' => [(object) [
@ -297,6 +302,7 @@ class NonJingxiRefundPageTest extends FeatureTestCase
'detailRefundMoney' => '99.50',
'status' => '待确认',
'shop_status' => '退款成功',
'createTime' => '2026-10-29 12:40:00',
]],
'has_more' => true,
]);
@ -306,22 +312,63 @@ class NonJingxiRefundPageTest extends FeatureTestCase
'month' => '2026-10',
'page' => 2,
'platform' => '京东商城',
'application_date' => '2026-10-29',
]))
->assertOk()
->assertJsonPath('month', '2026-10')
->assertJsonPath('platform', '京东商城')
->assertJsonPath('page', 2)
->assertJsonPath('application_date', '2026-10-29')
->assertJsonPath('has_more', true)
->assertJsonPath('rows.0.after_sales_no', '743441809')
->assertJsonPath('rows.0.external_after_sales_no', '47467351078')
->assertJsonPath('rows.0.online_order_no', '3668475003538709')
->assertJsonPath('rows.0.internal_order_no', '10001001')
->assertJsonPath('rows.0.platform', '京东商城')
->assertJsonPath('rows.0.application_time', '2026-10-29 12:40:00')
->assertJsonPath('rows.0.status', '待确认')
->assertJsonPath('rows.0.online_status', '退款成功')
->assertJsonPath('rows.0.sku_id', 'SKU-PENDING-1');
}
public function test_refund_pending_application_summary_groups_selected_platform_by_application_date(): void
{
$this->grantAdminPermission();
$repository = \Mockery::mock(NonJingxiRefundMirrorRepository::class);
$repository->shouldReceive('available')->once()->andReturnTrue();
$repository->shouldReceive('ready')->once()->andReturnTrue();
$repository->shouldReceive('queryReady')->once()->andReturnTrue();
$repository->shouldReceive('pendingConfirmationApplicationDailySummary')->once()->with([
'from' => '2026-11-01',
'to' => '2026-11-04',
'order_no' => '',
'waybill_no' => '',
'shop_name' => '',
'sku_id' => '',
'platform' => '京东商城',
])->andReturn([
'total' => 4,
'rows' => [
['application_date' => '2026-11-04', 'count' => 3],
['application_date' => '2026-11-01', 'count' => 1],
],
]);
$this->app->instance(NonJingxiRefundMirrorRepository::class, $repository);
$this->loginAs()->getJson(route('business.refunds.refund-pending.application-summary', [
'month' => '2026-11',
'platform' => '京东商城',
]))
->assertOk()
->assertJsonPath('month', '2026-11')
->assertJsonPath('platform', '京东商城')
->assertJsonPath('total', 4)
->assertJsonPath('rows.0.application_date', '2026-11-04')
->assertJsonPath('rows.0.count', 3)
->assertJsonPath('rows.1.application_date', '2026-11-01')
->assertJsonPath('rows.1.count', 1);
}
public function test_refund_pending_all_details_endpoint_uses_october_to_today(): void
{
$this->grantAdminPermission();

View File

@ -362,6 +362,74 @@ class NonJingxiRefundMirrorRepositoryTest extends TestCase
], $platformSummary['platforms']);
}
public function test_pending_confirmation_application_summary_and_date_filter_cover_both_sources(): void
{
$db = DB::connection('business_mirror');
$db->table('ops_jst_return_refund_info')->insert([
array_replace($this->refundInfo(1, 101, '2026-10-01 10:00:00', '天猫', '测试店'), [
'createTime' => '2026-10-01 08:00:00',
'status' => 'WaitConfirm',
'shop_status' => 'SUCCESS',
]),
array_replace($this->refundInfo(2, 102, '2026-10-02 10:00:00', '天猫', '测试店'), [
'createTime' => '2026-10-02 08:00:00',
'status' => 'WaitConfirm',
'shop_status' => 'SUCCESS',
]),
array_replace($this->refundInfo(3, 103, '2026-10-03 10:00:00', '天猫', '测试店'), [
'createTime' => null,
'status' => 'WaitConfirm',
'shop_status' => 'SUCCESS',
]),
]);
$supplement = array_replace($this->supplement(201, '2026-10-05 10:00:00', 'SHOP-SJ'), [
'local_created' => '2026-10-02 09:00:00',
'status' => 'WaitConfirm',
'shop_status' => 'SUCCESS',
]);
$db->table('ops_jst_qmcust_refunds')->insert($supplement);
$db->table('ops_jst_shop_info')->insert([
['Id' => 1, 'shop_id' => 'SHOP-SJ', 'shop_site' => '天猫'],
]);
$db->table('ops_jst_refund_status')->insert([
['as_id' => '101', 'status' => 'WaitConfirm', 'shop_status' => 'SUCCESS'],
['as_id' => '102', 'status' => 'WaitConfirm', 'shop_status' => 'SUCCESS'],
['as_id' => '103', 'status' => 'WaitConfirm', 'shop_status' => 'SUCCESS'],
['as_id' => '201', 'status' => 'WaitConfirm', 'shop_status' => 'SUCCESS'],
]);
$filters = [
'from' => '2026-10-01',
'to' => '2026-10-31',
'order_no' => '',
'waybill_no' => '',
'shop_name' => '',
'sku_id' => '',
'platform' => '天猫',
];
$summary = $this->repository->pendingConfirmationApplicationDailySummary($filters);
$this->assertSame(4, $summary['total']);
$this->assertSame([
['application_date' => '2026-10-02', 'count' => 2],
['application_date' => '2026-10-01', 'count' => 1],
['application_date' => 'unknown', 'count' => 1],
], $summary['rows']);
$dated = $this->repository->pagePendingConfirmation($filters + [
'application_date' => '2026-10-02',
], 1, 25);
$this->assertEqualsCanonicalizing(
[102, 201],
array_map(static fn (object $row): int => (int) $row->as_id, $dated['data']),
);
$unknown = $this->repository->pagePendingConfirmation($filters + [
'application_date' => 'unknown',
], 1, 25);
$this->assertCount(1, $unknown['data']);
$this->assertSame(103, (int) $unknown['data'][0]->as_id);
}
public function test_pending_confirmation_details_filter_by_platform_across_both_sources(): void
{
$db = DB::connection('business_mirror');