feat(科目映射): 未映射清单改为跨月汇总 #1699
@ -7,12 +7,12 @@ use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 后台重建某月账单项目覆盖快照,供科目映射页即时读取。
|
||||
* 后台重建跨月或指定月份账单项目覆盖快照,供科目映射页即时读取。
|
||||
*/
|
||||
class RefreshAccountMappingCoverage extends Command
|
||||
{
|
||||
protected $signature = 'account-mapping:refresh-coverage
|
||||
{month? : 账单月份,格式 YYYY-MM}
|
||||
{month? : all 或账单月份 YYYY-MM}
|
||||
{--pending : 处理页面登记的下一个刷新请求}';
|
||||
|
||||
protected $description = '刷新科目映射的未映射账单项目清单';
|
||||
@ -33,7 +33,10 @@ class RefreshAccountMappingCoverage extends Command
|
||||
}
|
||||
|
||||
try {
|
||||
$raw = $coverage->refreshForMonth($month);
|
||||
$isAll = $month === 'all';
|
||||
$raw = $isAll
|
||||
? $coverage->refreshAllMonths()
|
||||
: $coverage->refreshForMonth($month);
|
||||
if (($raw['status'] ?? '') === 'refreshing') {
|
||||
$this->warn('已有刷新任务正在执行,本次跳过。');
|
||||
if ($runningPath !== null) {
|
||||
@ -43,10 +46,12 @@ class RefreshAccountMappingCoverage extends Command
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$summary = $coverage->missingForMonth($month);
|
||||
$summary = $isAll
|
||||
? $coverage->missingAcrossMonths()
|
||||
: $coverage->missingForMonth($month);
|
||||
$this->info(sprintf(
|
||||
'%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d;PHP 峰值内存 %.1f MiB。',
|
||||
(string) $summary['month'],
|
||||
$isAll ? '跨月全部账单' : (string) $summary['month'],
|
||||
(int) $summary['missing_item_count'],
|
||||
(int) $summary['missing_row_count'],
|
||||
(int) $summary['source_rows'],
|
||||
|
||||
@ -96,11 +96,13 @@ class AccountMappingActions extends Controller
|
||||
]);
|
||||
|
||||
try {
|
||||
return response()->json($this->coverage->missingForMonth(
|
||||
trim((string) ($data['month'] ?? '')) ?: null,
|
||||
(bool) ($data['refresh'] ?? false),
|
||||
false,
|
||||
));
|
||||
$month = trim((string) ($data['month'] ?? ''));
|
||||
$refresh = (bool) ($data['refresh'] ?? false);
|
||||
$payload = $month === ''
|
||||
? $this->coverage->missingAcrossMonths($refresh, false)
|
||||
: $this->coverage->missingForMonth($month, $refresh, false);
|
||||
|
||||
return response()->json($payload);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages(['month' => $exception->getMessage()]);
|
||||
} catch (Throwable $exception) {
|
||||
|
||||
@ -31,6 +31,10 @@ class AccountMappingCoverage
|
||||
|
||||
private const RETRY_SECONDS = 8;
|
||||
|
||||
private const ALL_SCOPE = 'all';
|
||||
|
||||
private const ALL_SCOPE_MONTHS = 60;
|
||||
|
||||
private const SOURCES = [
|
||||
'淘系支付宝' => ['table' => 'taobao_alipay_bill_rows', 'date' => 'occurred_at', 'periods' => null],
|
||||
'淘系微信' => ['table' => 'taobao_wechat_bill_rows', 'date' => 'occurred_at', 'periods' => null],
|
||||
@ -203,9 +207,99 @@ class AccountMappingCoverage
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面使用:读取跨月账单项目清单;不会在读取时自动创建扫描任务。
|
||||
*
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function missingAcrossMonths(bool $refresh = false, bool $queueIfMissing = false): array
|
||||
{
|
||||
$snapshotKey = self::ALL_SCOPE;
|
||||
$sourceKey = $this->allSourceKey();
|
||||
$snapshot = $this->readSnapshot($snapshotKey, $sourceKey);
|
||||
$status = Cache::get($this->statusCacheKey($snapshotKey), []);
|
||||
|
||||
if (! $refresh && $snapshot !== null) {
|
||||
return $this->missingAcrossPayload($snapshot['raw'], $snapshot['refreshed_at']);
|
||||
}
|
||||
|
||||
$raw = Cache::get($sourceKey);
|
||||
if (! $refresh && is_array($raw)) {
|
||||
$refreshedAt = is_array($status) ? (string) ($status['refreshed_at'] ?? '') : '';
|
||||
$this->writeSnapshot($snapshotKey, $sourceKey, $raw, $refreshedAt);
|
||||
|
||||
return $this->missingAcrossPayload($raw, $refreshedAt);
|
||||
}
|
||||
|
||||
if (is_array($status) && ($status['status'] ?? '') === 'refreshing') {
|
||||
return $this->waitingPayload($snapshotKey, 'refreshing');
|
||||
}
|
||||
if (! $refresh && is_array($status) && ($status['status'] ?? '') === 'failed') {
|
||||
return $this->waitingPayload($snapshotKey, 'failed', (string) ($status['message'] ?? ''));
|
||||
}
|
||||
if ($this->hasLiveRefreshRequest($snapshotKey)) {
|
||||
return $this->waitingPayload($snapshotKey, 'refreshing');
|
||||
}
|
||||
if (! $refresh && ! $queueIfMissing) {
|
||||
return $this->waitingPayload($snapshotKey, 'missing');
|
||||
}
|
||||
|
||||
$requested = $this->requestRefresh($snapshotKey);
|
||||
if (($requested['status'] ?? '') === 'failed') {
|
||||
return $this->waitingPayload($snapshotKey, 'failed', (string) ($requested['message'] ?? ''));
|
||||
}
|
||||
|
||||
return $this->waitingPayload($snapshotKey, 'refreshing');
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台命令使用:一次性按月份聚合最近 60 个月的全部账单项目。
|
||||
*
|
||||
* @return array{status:string,source_rows:int,pending_sources:list<string>,pairs:list<array<string,mixed>>}
|
||||
*/
|
||||
public function refreshAllMonths(): array
|
||||
{
|
||||
$snapshotKey = self::ALL_SCOPE;
|
||||
$lock = Cache::lock('account-mapping-coverage-refresh:' . $snapshotKey, 900);
|
||||
|
||||
try {
|
||||
return $lock->block(20, function () use ($snapshotKey): array {
|
||||
Cache::put($this->statusCacheKey($snapshotKey), [
|
||||
'status' => 'refreshing',
|
||||
'started_at' => now()->toDateTimeString(),
|
||||
], now()->addMinutes(self::STATUS_MINUTES));
|
||||
|
||||
try {
|
||||
$sourceKey = $this->allSourceKey();
|
||||
[$start, $end] = $this->allPeriodBounds();
|
||||
$raw = $this->buildAllSourceCoverage($start, $end);
|
||||
$refreshedAt = now()->toDateTimeString();
|
||||
Cache::put($sourceKey, $raw, now()->addHours(self::CACHE_HOURS));
|
||||
$this->writeSnapshot($snapshotKey, $sourceKey, $raw, $refreshedAt);
|
||||
Cache::put($this->statusCacheKey($snapshotKey), [
|
||||
'status' => 'ready',
|
||||
'refreshed_at' => $refreshedAt,
|
||||
], now()->addMinutes(self::STATUS_MINUTES));
|
||||
|
||||
return $raw;
|
||||
} catch (Throwable $exception) {
|
||||
$this->markFailed($snapshotKey, $exception->getMessage());
|
||||
throw $exception;
|
||||
}
|
||||
});
|
||||
} catch (\Illuminate\Contracts\Cache\LockTimeoutException) {
|
||||
return [
|
||||
'status' => 'refreshing',
|
||||
'source_rows' => 0,
|
||||
'pending_sources' => [],
|
||||
'pairs' => [],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public function markFailed(string $month, string $message): void
|
||||
{
|
||||
$period = $this->parseMonth($month);
|
||||
$period = $this->normalizeRefreshKey($month);
|
||||
Cache::put($this->statusCacheKey($period), [
|
||||
'status' => 'failed',
|
||||
'message' => $message,
|
||||
@ -239,6 +333,7 @@ class AccountMappingCoverage
|
||||
|
||||
return [
|
||||
'status' => $raw['status'],
|
||||
'scope' => 'month',
|
||||
'month' => $period,
|
||||
'source_rows' => $raw['source_rows'],
|
||||
'missing_item_count' => count($items),
|
||||
@ -252,12 +347,60 @@ class AccountMappingCoverage
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{status:string,source_rows:int,pending_sources:list<string>,pairs:list<array<string,mixed>>} $raw
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function missingAcrossPayload(array $raw, string $refreshedAt = ''): array
|
||||
{
|
||||
$mapping = $this->coverageMappingKeys($this->store->all());
|
||||
$items = [];
|
||||
$missingRows = 0;
|
||||
|
||||
foreach ($raw['pairs'] as $pair) {
|
||||
if ($this->isMapped($pair, $mapping)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$months = array_values(array_filter(
|
||||
(array) ($pair['months'] ?? []),
|
||||
static fn (mixed $month): bool => is_string($month) && $month !== '',
|
||||
));
|
||||
sort($months);
|
||||
$pair['months'] = $months;
|
||||
$missingRows += (int) $pair['source_rows'];
|
||||
$items[] = $pair;
|
||||
}
|
||||
|
||||
usort($items, static fn (array $left, array $right): int => (
|
||||
$right['source_rows'] <=> $left['source_rows']
|
||||
) ?: (
|
||||
strcmp((string) $left['platform'], (string) $right['platform'])
|
||||
) ?: strcmp((string) $left['item'], (string) $right['item']));
|
||||
|
||||
return [
|
||||
'status' => $raw['status'],
|
||||
'scope' => self::ALL_SCOPE,
|
||||
'month' => null,
|
||||
'source_rows' => $raw['source_rows'],
|
||||
'missing_item_count' => count($items),
|
||||
'missing_row_count' => $missingRows,
|
||||
'pending_sources' => $raw['pending_sources'],
|
||||
'items' => $items,
|
||||
'months' => [],
|
||||
'retry_after' => null,
|
||||
'message' => '',
|
||||
'refreshed_at' => $refreshedAt,
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function waitingPayload(string $period, string $status, string $message = ''): array
|
||||
{
|
||||
return [
|
||||
'status' => $status,
|
||||
'month' => $period,
|
||||
'scope' => $period === self::ALL_SCOPE ? self::ALL_SCOPE : 'month',
|
||||
'month' => $period === self::ALL_SCOPE ? null : $period,
|
||||
'source_rows' => 0,
|
||||
'missing_item_count' => 0,
|
||||
'missing_row_count' => 0,
|
||||
@ -273,6 +416,7 @@ class AccountMappingCoverage
|
||||
/** @return array{status:string,message:string} */
|
||||
private function requestRefresh(string $period): array
|
||||
{
|
||||
$period = $this->normalizeRefreshKey($period);
|
||||
Cache::put($this->statusCacheKey($period), [
|
||||
'status' => 'refreshing',
|
||||
'started_at' => now()->toDateTimeString(),
|
||||
@ -315,7 +459,7 @@ class AccountMappingCoverage
|
||||
continue;
|
||||
}
|
||||
$month = basename((string) $running, '.running');
|
||||
if ($this->isValidMonth($month)) {
|
||||
if ($this->isValidRefreshKey($month)) {
|
||||
File::move($running, $directory . DIRECTORY_SEPARATOR . $month . '.pending', true);
|
||||
}
|
||||
}
|
||||
@ -324,7 +468,7 @@ class AccountMappingCoverage
|
||||
sort($pendingFiles);
|
||||
foreach ($pendingFiles as $pending) {
|
||||
$month = basename((string) $pending, '.pending');
|
||||
if (! $this->isValidMonth($month)) {
|
||||
if (! $this->isValidRefreshKey($month)) {
|
||||
continue;
|
||||
}
|
||||
$running = $directory . DIRECTORY_SEPARATOR . $month . '.running';
|
||||
@ -368,7 +512,7 @@ class AccountMappingCoverage
|
||||
return;
|
||||
}
|
||||
$month = basename($runningPath, '.running');
|
||||
if (! $this->isValidMonth($month)) {
|
||||
if (! $this->isValidRefreshKey($month)) {
|
||||
return;
|
||||
}
|
||||
File::move(
|
||||
@ -472,6 +616,168 @@ class AccountMappingCoverage
|
||||
. $period . '-' . substr(hash('sha256', $sourceKey), 0, 16) . '.json';
|
||||
}
|
||||
|
||||
/** @return array{0:CarbonImmutable,1:CarbonImmutable} */
|
||||
private function allPeriodBounds(): array
|
||||
{
|
||||
$timezone = trim((string) config('app.platform_timezone', ''));
|
||||
if ($timezone === '') {
|
||||
$timezone = (string) config('app.timezone', 'UTC');
|
||||
}
|
||||
|
||||
try {
|
||||
$end = CarbonImmutable::now($timezone)->endOfMonth();
|
||||
} catch (Throwable) {
|
||||
$end = CarbonImmutable::now()->endOfMonth();
|
||||
}
|
||||
|
||||
return [
|
||||
$end->startOfMonth()->subMonthsNoOverflow(self::ALL_SCOPE_MONTHS - 1),
|
||||
$end,
|
||||
];
|
||||
}
|
||||
|
||||
private function allSourceKey(): string
|
||||
{
|
||||
[$start, $end] = $this->allPeriodBounds();
|
||||
$parts = [$start->format('Y-m-d'), $end->format('Y-m-d')];
|
||||
foreach (self::SOURCES as $label => $source) {
|
||||
if ($source['periods'] === null) {
|
||||
$parts[] = $label . ':none';
|
||||
continue;
|
||||
}
|
||||
$parts[] = $label . ':' . implode(',', $this->generations(
|
||||
(string) $source['periods'],
|
||||
$start->toDateString(),
|
||||
$end->toDateString(),
|
||||
));
|
||||
}
|
||||
|
||||
return self::CACHE_PREFIX . self::ALL_SCOPE . ':' . hash('sha256', implode('|', $parts));
|
||||
}
|
||||
|
||||
private function monthSql(\Illuminate\Database\ConnectionInterface $connection, string $dateColumn): string
|
||||
{
|
||||
return match ($connection->getDriverName()) {
|
||||
'mysql', 'mariadb' => "DATE_FORMAT({$dateColumn}, '%Y-%m')",
|
||||
'pgsql' => "TO_CHAR({$dateColumn}, 'YYYY-MM')",
|
||||
'sqlite' => "strftime('%Y-%m', {$dateColumn})",
|
||||
default => throw new RuntimeException('当前数据库不支持跨月账单聚合。'),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* status:string,
|
||||
* source_rows:int,
|
||||
* pending_sources:list<string>,
|
||||
* pairs:list<array<string,mixed>>
|
||||
* }
|
||||
*/
|
||||
private function buildAllSourceCoverage(CarbonImmutable $start, CarbonImmutable $end): array
|
||||
{
|
||||
$connection = $this->databases->connection(
|
||||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||||
);
|
||||
$schema = $connection->getSchemaBuilder();
|
||||
$pairs = [];
|
||||
$sourceRows = 0;
|
||||
$pendingSources = [];
|
||||
|
||||
foreach (self::SOURCES as $label => $source) {
|
||||
$table = (string) $source['table'];
|
||||
if (! $schema->hasTable($table)) {
|
||||
throw new RuntimeException('账单表尚未迁移:' . $table);
|
||||
}
|
||||
|
||||
$dateColumn = (string) $source['date'];
|
||||
$query = $connection->table($table);
|
||||
if ($dateColumn === 'bill_date') {
|
||||
$query->whereBetween($dateColumn, [$start->toDateString(), $end->toDateString()]);
|
||||
} else {
|
||||
$query->whereBetween($dateColumn, [
|
||||
$start->toDateString() . ' 00:00:00',
|
||||
$end->toDateString() . ' 23:59:59',
|
||||
]);
|
||||
}
|
||||
|
||||
if ($source['periods'] !== null) {
|
||||
$generations = $this->generations(
|
||||
(string) $source['periods'],
|
||||
$start->toDateString(),
|
||||
$end->toDateString(),
|
||||
);
|
||||
if ($generations === []) {
|
||||
$pendingSources[] = $label;
|
||||
continue;
|
||||
}
|
||||
$query->whereIn('generation', $generations);
|
||||
}
|
||||
|
||||
$monthExpression = $this->monthSql($connection, $dateColumn);
|
||||
$platformExpression = $this->platformSql($connection);
|
||||
$itemExpression = $this->normalizedItemSql();
|
||||
$groups = $query
|
||||
->selectRaw($monthExpression . ' AS bill_month')
|
||||
->selectRaw($platformExpression . ' AS platform, ' . $itemExpression . ' AS item')
|
||||
->selectRaw('COUNT(*) AS source_rows, COUNT(DISTINCT store_name) AS store_count')
|
||||
->groupByRaw($monthExpression . ', ' . $platformExpression . ', ' . $itemExpression)
|
||||
->cursor();
|
||||
|
||||
foreach ($groups as $group) {
|
||||
$month = trim((string) $group->bill_month);
|
||||
if (! $this->isValidMonth($month)) {
|
||||
continue;
|
||||
}
|
||||
$rows = (int) $group->source_rows;
|
||||
$sourceRows += $rows;
|
||||
$item = trim((string) $group->item);
|
||||
$displayItem = $item === '' ? '(未填写账单项目)' : $item;
|
||||
$platform = trim((string) $group->platform);
|
||||
$key = $platform . "\0" . $displayItem;
|
||||
|
||||
if (! isset($pairs[$key])) {
|
||||
$pairs[$key] = [
|
||||
'platform' => $platform,
|
||||
'platform_label' => $platform === '' ? '未识别平台' : $platform,
|
||||
'item' => $displayItem,
|
||||
'source_rows' => 0,
|
||||
'store_count' => 0,
|
||||
'source_labels' => [],
|
||||
'raw_items' => [],
|
||||
'month_rows' => [],
|
||||
];
|
||||
}
|
||||
|
||||
$pairs[$key]['source_rows'] += $rows;
|
||||
$pairs[$key]['source_labels'][$label] = ($pairs[$key]['source_labels'][$label] ?? 0) + $rows;
|
||||
$pairs[$key]['raw_items'][$displayItem] = true;
|
||||
$pairs[$key]['month_rows'][$month] = ($pairs[$key]['month_rows'][$month] ?? 0) + $rows;
|
||||
$pairs[$key]['store_count'] = max(
|
||||
(int) $pairs[$key]['store_count'],
|
||||
(int) $group->store_count,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($pairs as &$pair) {
|
||||
ksort($pair['month_rows']);
|
||||
$pair['months'] = array_keys($pair['month_rows']);
|
||||
$pair['raw_items'] = array_values(array_filter(
|
||||
array_keys($pair['raw_items']),
|
||||
static fn (string $item): bool => $item !== '',
|
||||
));
|
||||
$pair['source_labels'] = array_keys($pair['source_labels']);
|
||||
}
|
||||
unset($pair);
|
||||
|
||||
return [
|
||||
'status' => $sourceRows > 0 ? 'ready' : 'unavailable',
|
||||
'source_rows' => $sourceRows,
|
||||
'pending_sources' => $pendingSources,
|
||||
'pairs' => array_values($pairs),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* status:string,
|
||||
@ -710,6 +1016,21 @@ class AccountMappingCoverage
|
||||
return $month;
|
||||
}
|
||||
|
||||
private function normalizeRefreshKey(string $key): string
|
||||
{
|
||||
$key = trim($key);
|
||||
if ($key === self::ALL_SCOPE) {
|
||||
return self::ALL_SCOPE;
|
||||
}
|
||||
|
||||
return $this->parseMonth($key);
|
||||
}
|
||||
|
||||
private function isValidRefreshKey(string $key): bool
|
||||
{
|
||||
return $key === self::ALL_SCOPE || $this->isValidMonth($key);
|
||||
}
|
||||
|
||||
private function isValidMonth(string $month): bool
|
||||
{
|
||||
try {
|
||||
|
||||
@ -11,22 +11,6 @@
|
||||
|
||||
$platforms = $amOptions['platforms'] ?? [];
|
||||
$categories = $amOptions['categories'] ?? [];
|
||||
$coverageTimezone = trim((string) config('app.platform_timezone', ''))
|
||||
?: (string) config('app.timezone', 'UTC');
|
||||
$coverageDefaultMonth = \Carbon\CarbonImmutable::now($coverageTimezone)
|
||||
->subMonthNoOverflow()
|
||||
->format('Y-m');
|
||||
$coverageMonth = trim((string) request()->query('am_month', $coverageDefaultMonth));
|
||||
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $coverageMonth) !== 1) {
|
||||
$coverageMonth = $coverageDefaultMonth;
|
||||
}
|
||||
$coverageMonths = [];
|
||||
$coverageMonthCursor = \Carbon\CarbonImmutable::createFromFormat('!Y-m', $coverageMonth);
|
||||
for ($coverageMonthIndex = 0; $coverageMonthIndex < 18; $coverageMonthIndex++) {
|
||||
$coverageMonths[] = $coverageMonthCursor
|
||||
->subMonthsNoOverflow($coverageMonthIndex)
|
||||
->format('Y-m');
|
||||
}
|
||||
$coverageInitialView = request()->query('am_view') === 'unmapped' ? 'unmapped' : 'rules';
|
||||
$outBase = 0;
|
||||
$inBase = 0;
|
||||
@ -202,6 +186,11 @@
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
.am-coverage-range {
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.am-coverage-toolbar select {
|
||||
min-width: 9rem;
|
||||
height: 2.125rem;
|
||||
@ -254,12 +243,13 @@
|
||||
line-height: 1.5;
|
||||
}
|
||||
.am-coverage-notice[hidden] { display: none; }
|
||||
.am-coverage-table { min-width: 62rem; table-layout: fixed; }
|
||||
.am-coverage-table { min-width: 72rem; table-layout: fixed; }
|
||||
.am-coverage-table th,
|
||||
.am-coverage-table td { overflow: hidden; text-overflow: ellipsis; }
|
||||
.am-coverage-table .am-coverage-index { width: 3.5rem; }
|
||||
.am-coverage-table .am-coverage-platform { width: 7.5rem; }
|
||||
.am-coverage-table .am-coverage-item { width: 18rem; }
|
||||
.am-coverage-table .am-coverage-months { width: 10rem; }
|
||||
.am-coverage-table .am-coverage-source { width: 12rem; }
|
||||
.am-coverage-table .am-coverage-count { width: 7rem; text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.am-coverage-table .am-coverage-stores { width: 10rem; text-align: right; font-variant-numeric: tabular-nums; }
|
||||
@ -274,6 +264,18 @@
|
||||
font-size: 0.6875rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.am-coverage-month-tag {
|
||||
display: inline-block;
|
||||
margin: 0.1rem 0.2rem 0.1rem 0;
|
||||
padding: 0.1rem 0.4rem;
|
||||
border: 1px solid #ddd5c7;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
color: #595959;
|
||||
font-size: 0.6875rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.am-coverage-store-hint { color: var(--vip-content-muted, #595959); font-size: 0.6875rem; }
|
||||
|
||||
/* 表格必须锁列宽(table-layout:fixed)。默认的自动列宽会按内容互相挤压,
|
||||
@ -876,24 +878,17 @@
|
||||
>
|
||||
<div class="am-coverage-toolbar">
|
||||
<div class="am-coverage-toolbar__fields">
|
||||
<label for="amCoverageMonth">
|
||||
账单月份
|
||||
<select id="amCoverageMonth">
|
||||
@foreach ($coverageMonths as $monthOption)
|
||||
<option value="{{ $monthOption }}" @selected($monthOption === $coverageMonth)>{{ $monthOption }}</option>
|
||||
@endforeach
|
||||
</select>
|
||||
</label>
|
||||
<span class="am-coverage-range">统计最近 60 个月的已导入账单</span>
|
||||
<button type="button" class="am-btn" id="amCoverageRefresh">生成最新清单</button>
|
||||
</div>
|
||||
<div class="am-coverage-summary" id="amCoverageSummary" aria-live="polite">
|
||||
<strong>{{ $coverageMonth }}</strong>
|
||||
<span>正在读取该月账单项目……</span>
|
||||
<strong>跨月全部账单</strong>
|
||||
<span>正在读取未映射账单项目……</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="am-coverage-notice" id="amCoverageNotice" role="status" hidden></div>
|
||||
<div class="am-coverage-state" id="amCoverageState">
|
||||
正在读取该月账单项目,请稍候。
|
||||
正在读取最近 60 个月的账单项目,请稍候。
|
||||
</div>
|
||||
<div class="upstream-data-table-panel" id="amCoverageTableWrap" hidden>
|
||||
<div class="upstream-data-table-scroll">
|
||||
@ -903,6 +898,7 @@
|
||||
<th class="am-coverage-index">序号</th>
|
||||
<th class="am-coverage-platform">平台</th>
|
||||
<th class="am-coverage-item">账单项目</th>
|
||||
<th class="am-coverage-months">账单月份</th>
|
||||
<th class="am-coverage-source">来源账单</th>
|
||||
<th class="am-coverage-count">影响行数</th>
|
||||
<th class="am-coverage-stores">店铺数</th>
|
||||
@ -956,7 +952,6 @@
|
||||
var ROWS = @json($amRows, JSON_UNESCAPED_UNICODE);
|
||||
var OPTIONS = @json($amOptions, JSON_UNESCAPED_UNICODE);
|
||||
var SUMMARY = @json($amSummary, JSON_UNESCAPED_UNICODE);
|
||||
var INITIAL_COVERAGE_MONTH = @json($coverageMonth);
|
||||
var INITIAL_VIEW = @json($coverageInitialView);
|
||||
var COA = null;
|
||||
var editingId = null;
|
||||
@ -1215,7 +1210,6 @@
|
||||
/* ---------- 账单覆盖:已配置规则 / 未映射账单项目 ---------- */
|
||||
var viewButtons = Array.prototype.slice.call(document.querySelectorAll('[data-am-view-tab]'));
|
||||
var viewPanels = Array.prototype.slice.call(document.querySelectorAll('[data-am-view-panel]'));
|
||||
var coverageMonthEl = document.getElementById('amCoverageMonth');
|
||||
var coverageCountEl = document.getElementById('amCoverageCount');
|
||||
var coverageSummaryEl = document.getElementById('amCoverageSummary');
|
||||
var coverageStateEl = document.getElementById('amCoverageState');
|
||||
@ -1258,18 +1252,18 @@
|
||||
if (updateUrl !== false) {
|
||||
var url = new URL(window.location.href);
|
||||
url.searchParams.set('am_view', selected);
|
||||
url.searchParams.set('am_month', coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH);
|
||||
url.searchParams.delete('am_month');
|
||||
window.history.replaceState({}, '', url);
|
||||
}
|
||||
if (selected === 'unmapped' && !coverageData && !coverageLoading) {
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH);
|
||||
loadCoverage();
|
||||
}
|
||||
}
|
||||
|
||||
function renderCoverageSummary(data) {
|
||||
if (!coverageSummaryEl) { return; }
|
||||
coverageSummaryEl.innerHTML = '';
|
||||
var month = String(data && data.month ? data.month : (coverageMonthEl ? coverageMonthEl.value : ''));
|
||||
var month = data && data.scope === 'all' ? '跨月全部账单' : String(data && data.month || '');
|
||||
var title = document.createElement('strong');
|
||||
title.textContent = month;
|
||||
coverageSummaryEl.appendChild(title);
|
||||
@ -1306,6 +1300,7 @@
|
||||
|
||||
function coverageRowHtml(row, index) {
|
||||
var rawItems = Array.isArray(row.raw_items) ? row.raw_items : [];
|
||||
var months = Array.isArray(row.months) ? row.months : [];
|
||||
var sourceLabels = Array.isArray(row.source_labels) ? row.source_labels : [];
|
||||
var storeSamples = Array.isArray(row.store_samples) ? row.store_samples : [];
|
||||
var platform = String(row.platform || '');
|
||||
@ -1317,6 +1312,9 @@
|
||||
+ '<td title="' + esc(row.platform_label || row.platform || '未识别平台') + '">' + esc(row.platform_label || row.platform || '未识别平台') + '</td>'
|
||||
+ '<td title="' + esc(rawHint ? item + ';原始项目:' + rawHint : item) + '"><strong>' + esc(item) + '</strong>'
|
||||
+ (rawHint ? '<div class="am-coverage-store-hint">原始:' + esc(rawHint) + '</div>' : '') + '</td>'
|
||||
+ '<td title="' + esc(months.join('、')) + '">' + months.map(function (month) {
|
||||
return '<span class="am-coverage-month-tag">' + esc(month) + '</span>';
|
||||
}).join('') + '</td>'
|
||||
+ '<td>' + sourceLabels.map(function (label) {
|
||||
return '<span class="am-coverage-source-tag">' + esc(label) + '</span>';
|
||||
}).join('') + '</td>'
|
||||
@ -1334,10 +1332,10 @@
|
||||
coverageCountEl.textContent = '…';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '正在读取该月账单项目,请稍候。';
|
||||
coverageStateEl.textContent = '正在读取最近 60 个月的账单项目,请稍候。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
if (coverageSummaryEl) {
|
||||
coverageSummaryEl.innerHTML = '<strong>' + esc(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH) + '</strong><span>正在读取……</span>';
|
||||
coverageSummaryEl.innerHTML = '<strong>跨月全部账单</strong><span>正在读取……</span>';
|
||||
}
|
||||
return;
|
||||
}
|
||||
@ -1349,7 +1347,7 @@
|
||||
coverageStateEl.textContent = coverageError;
|
||||
coverageTableWrapEl.hidden = true;
|
||||
if (coverageSummaryEl) {
|
||||
coverageSummaryEl.innerHTML = '<strong>' + esc(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH) + '</strong><span>读取失败</span>';
|
||||
coverageSummaryEl.innerHTML = '<strong>跨月全部账单</strong><span>读取失败</span>';
|
||||
}
|
||||
return;
|
||||
}
|
||||
@ -1358,7 +1356,7 @@
|
||||
coverageCountEl.textContent = '—';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '切换到此视图后读取该月已有快照。';
|
||||
coverageStateEl.textContent = '切换到此视图后读取跨月已有快照。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
return;
|
||||
}
|
||||
@ -1367,7 +1365,7 @@
|
||||
coverageCountEl.textContent = '…';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '后台正在按月生成。批处理完成后,点击“读取生成结果”;本页不会自动轮询。';
|
||||
coverageStateEl.textContent = '后台正在生成跨月清单。批处理完成后,点击“读取生成结果”;本页不会自动轮询。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
renderCoverageSummary(coverageData);
|
||||
return;
|
||||
@ -1377,7 +1375,7 @@
|
||||
coverageCountEl.textContent = '—';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '所选月份尚未生成未映射清单,请点击“生成最新清单”。';
|
||||
coverageStateEl.textContent = '跨月未映射清单尚未生成,请点击“生成最新清单”。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
renderCoverageSummary(coverageData);
|
||||
return;
|
||||
@ -1387,7 +1385,7 @@
|
||||
coverageCountEl.textContent = '—';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state am-coverage-state--error';
|
||||
coverageStateEl.textContent = coverageData.message || '该月未映射清单生成失败,请点击“生成最新清单”重试。';
|
||||
coverageStateEl.textContent = coverageData.message || '跨月未映射清单生成失败,请点击“生成最新清单”重试。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
renderCoverageSummary(coverageData);
|
||||
return;
|
||||
@ -1397,7 +1395,7 @@
|
||||
coverageCountEl.textContent = '—';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '所选月份暂无已导入账单,暂时无法生成未映射科目清单。请更换月份或等待账单同步完成。';
|
||||
coverageStateEl.textContent = '最近 60 个月暂无已导入账单,暂时无法生成未映射科目清单。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
renderCoverageSummary(coverageData);
|
||||
return;
|
||||
@ -1409,7 +1407,7 @@
|
||||
if (!items.length) {
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '所选月份的所有账单项目均已配置科目映射。';
|
||||
coverageStateEl.textContent = '当前账单中的所有账单项目均已配置科目映射。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
coverageBodyEl.innerHTML = '';
|
||||
return;
|
||||
@ -1420,28 +1418,17 @@
|
||||
coverageBodyEl.innerHTML = items.map(coverageRowHtml).join('');
|
||||
}
|
||||
|
||||
function loadCoverage(month, bypassLocalCache, refreshServer) {
|
||||
function loadCoverage(bypassLocalCache, refreshServer) {
|
||||
if (coverageLoading) { return; }
|
||||
month = String(month || INITIAL_COVERAGE_MONTH || '');
|
||||
if (!bypassLocalCache && coverageData && coverageData.month === month) {
|
||||
if (!bypassLocalCache && coverageData) {
|
||||
renderCoverage();
|
||||
return;
|
||||
}
|
||||
coverageLoading = true;
|
||||
coverageError = '';
|
||||
renderCoverage();
|
||||
api('GET', '/coverage?month=' + encodeURIComponent(month) + (refreshServer ? '&refresh=1' : '')).then(function (data) {
|
||||
api('GET', '/coverage' + (refreshServer ? '?refresh=1' : '')).then(function (data) {
|
||||
coverageData = data;
|
||||
if (Array.isArray(data.months) && coverageMonthEl) {
|
||||
var current = coverageMonthEl.value;
|
||||
coverageMonthEl.innerHTML = data.months.map(function (value) {
|
||||
return '<option value="' + esc(value) + '">' + esc(value) + '</option>';
|
||||
}).join('');
|
||||
coverageMonthEl.value = data.months.indexOf(current) >= 0 ? current : month;
|
||||
if (coverageMonthEl.value !== month && data.months.indexOf(month) >= 0) {
|
||||
coverageMonthEl.value = month;
|
||||
}
|
||||
}
|
||||
}).catch(function (error) {
|
||||
coverageData = null;
|
||||
coverageError = '未映射账单项目读取失败:' + error.message;
|
||||
@ -1471,16 +1458,10 @@
|
||||
selectView(button.getAttribute('data-am-view-tab'));
|
||||
});
|
||||
});
|
||||
coverageMonthEl?.addEventListener('change', function () {
|
||||
coverageData = null;
|
||||
hideCoverageNotice();
|
||||
loadCoverage(coverageMonthEl.value, true, false);
|
||||
});
|
||||
coverageRefreshEl?.addEventListener('click', function () {
|
||||
var month = coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH;
|
||||
var readOnly = coverageData && coverageData.status === 'refreshing';
|
||||
hideCoverageNotice();
|
||||
loadCoverage(month, true, !readOnly);
|
||||
loadCoverage(true, !readOnly);
|
||||
});
|
||||
|
||||
function mappingField(label, control, fullWidth) {
|
||||
@ -1573,7 +1554,7 @@
|
||||
showCoverageNotice('已保存映射:' + savedLabel + '。未映射清单已按新规则更新。');
|
||||
toast('映射已保存。');
|
||||
coverageData = null;
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH, true, false);
|
||||
loadCoverage(true, false);
|
||||
}).catch(function (e) {
|
||||
showCoverageMappingError(e.message);
|
||||
toast(e.message, 'err');
|
||||
|
||||
@ -103,7 +103,8 @@ class AccountMappingPageTest extends FeatureTestCase
|
||||
->assertSeeText('已配置规则')
|
||||
->assertSeeText('未映射账单项目')
|
||||
->assertSee('id="amCoveragePanel"', false)
|
||||
->assertSee('id="amCoverageMonth"', false)
|
||||
->assertSee('统计最近 60 个月的已导入账单')
|
||||
->assertSee('am-coverage-months">账单月份</th>', false)
|
||||
->assertSee('data-am-coverage-add', false)
|
||||
->assertSee('生成最新清单')
|
||||
->assertSee('本页不会自动轮询', false)
|
||||
@ -133,13 +134,14 @@ class AccountMappingPageTest extends FeatureTestCase
|
||||
->assertJsonStructure(['rules', 'summary', 'options' => ['platforms', 'categories', 'basis', 'invoices']]);
|
||||
}
|
||||
|
||||
public function test_coverage_endpoint_returns_unmapped_items_for_selected_month(): void
|
||||
public function test_coverage_endpoint_returns_unmapped_items_across_months(): void
|
||||
{
|
||||
$this->grantAdminPermission();
|
||||
$coverage = Mockery::mock(AccountMappingCoverage::class);
|
||||
$coverage->shouldReceive('missingForMonth')->once()->with('2026-11', false, false)->andReturn([
|
||||
$coverage->shouldReceive('missingAcrossMonths')->once()->with(false, false)->andReturn([
|
||||
'status' => 'ready',
|
||||
'month' => '2026-11',
|
||||
'scope' => 'all',
|
||||
'month' => null,
|
||||
'source_rows' => 120,
|
||||
'missing_item_count' => 1,
|
||||
'missing_row_count' => 7,
|
||||
@ -153,43 +155,46 @@ class AccountMappingPageTest extends FeatureTestCase
|
||||
'store_count' => 3,
|
||||
'store_samples' => ['抖音-甲店'],
|
||||
'source_labels' => ['抖音'],
|
||||
'months' => ['2026-10', '2026-11'],
|
||||
]],
|
||||
'months' => ['2026-11', '2026-10'],
|
||||
'months' => [],
|
||||
]);
|
||||
$this->app->instance(AccountMappingCoverage::class, $coverage);
|
||||
|
||||
$this->loginAs()->getJson($this->actionUrl('coverage') . '?month=2026-11')
|
||||
$this->loginAs()->getJson($this->actionUrl('coverage'))
|
||||
->assertOk()
|
||||
->assertJsonPath('status', 'ready')
|
||||
->assertJsonPath('scope', 'all')
|
||||
->assertJsonPath('missing_item_count', 1)
|
||||
->assertJsonPath('items.0.platform', '抖音')
|
||||
->assertJsonPath('items.0.item', '商家货款入账')
|
||||
->assertJsonPath('items.0.source_rows', 7);
|
||||
}
|
||||
|
||||
public function test_coverage_endpoint_can_queue_a_manual_month_refresh(): void
|
||||
public function test_coverage_endpoint_can_queue_a_manual_cross_month_refresh(): void
|
||||
{
|
||||
$this->grantAdminPermission();
|
||||
$coverage = Mockery::mock(AccountMappingCoverage::class);
|
||||
$coverage->shouldReceive('missingForMonth')->once()->with('2026-11', true, false)->andReturn([
|
||||
$coverage->shouldReceive('missingAcrossMonths')->once()->with(true, false)->andReturn([
|
||||
'status' => 'refreshing',
|
||||
'month' => '2026-11',
|
||||
'scope' => 'all',
|
||||
'month' => null,
|
||||
'source_rows' => 0,
|
||||
'missing_item_count' => 0,
|
||||
'missing_row_count' => 0,
|
||||
'pending_sources' => [],
|
||||
'items' => [],
|
||||
'months' => ['2026-11', '2026-10'],
|
||||
'months' => [],
|
||||
'retry_after' => 8,
|
||||
'message' => '',
|
||||
'refreshed_at' => null,
|
||||
]);
|
||||
$this->app->instance(AccountMappingCoverage::class, $coverage);
|
||||
|
||||
$this->loginAs()->getJson($this->actionUrl('coverage') . '?month=2026-11&refresh=1')
|
||||
$this->loginAs()->getJson($this->actionUrl('coverage') . '?refresh=1')
|
||||
->assertOk()
|
||||
->assertJsonPath('status', 'refreshing')
|
||||
->assertJsonPath('month', '2026-11');
|
||||
->assertJsonPath('scope', 'all');
|
||||
}
|
||||
|
||||
public function test_coverage_endpoint_rejects_invalid_month(): void
|
||||
|
||||
@ -125,6 +125,50 @@ class AccountMappingCoverageTest extends TestCase
|
||||
$this->assertNotContains('商家货款入账', array_column($second['items'], 'item'));
|
||||
}
|
||||
|
||||
public function test_cross_month_snapshot_lists_each_unmapped_item_with_its_months(): void
|
||||
{
|
||||
$store = app(AccountMappingStore::class);
|
||||
$this->rule($store, '天猫', '已映射项目');
|
||||
|
||||
$this->insertBill('taobao_alipay_bill_rows', 'occurred_at', [
|
||||
['store_name' => '天猫-测试店', 'bill_item' => '跨月未映射', 'day' => '2026-06-03 10:00:00'],
|
||||
['store_name' => '天猫-测试店', 'bill_item' => '跨月未映射', 'day' => '2026-07-03 10:00:00'],
|
||||
['store_name' => '天猫-测试店', 'bill_item' => '跨月未映射', 'day' => '2026-11-03 10:00:00'],
|
||||
['store_name' => '天猫-测试店', 'bill_item' => '已映射项目', 'day' => '2026-10-03 10:00:00'],
|
||||
]);
|
||||
|
||||
$coverage = app(AccountMappingCoverage::class);
|
||||
$this->assertSame('missing', $coverage->missingAcrossMonths()['status']);
|
||||
$queued = $coverage->missingAcrossMonths(false, true);
|
||||
$this->assertSame('refreshing', $queued['status']);
|
||||
|
||||
$request = $coverage->claimPendingRefresh();
|
||||
$this->assertNotNull($request);
|
||||
$this->assertSame('all', $request['month']);
|
||||
$coverage->refreshAllMonths();
|
||||
$coverage->finishPendingRefresh($request['path'], true);
|
||||
|
||||
$summary = $coverage->missingAcrossMonths();
|
||||
$this->assertSame('ready', $summary['status']);
|
||||
$this->assertSame('all', $summary['scope']);
|
||||
$this->assertSame(4, $summary['source_rows']);
|
||||
$this->assertSame(1, $summary['missing_item_count']);
|
||||
$this->assertSame(3, $summary['missing_row_count']);
|
||||
$this->assertSame('跨月未映射', $summary['items'][0]['item']);
|
||||
$this->assertSame(
|
||||
['2026-06', '2026-07', '2026-11'],
|
||||
$summary['items'][0]['months'],
|
||||
);
|
||||
|
||||
Cache::flush();
|
||||
$persisted = app(AccountMappingCoverage::class)->missingAcrossMonths();
|
||||
$this->assertSame('ready', $persisted['status']);
|
||||
$this->assertSame(3, $persisted['missing_row_count']);
|
||||
$this->assertCount(1, glob(
|
||||
$this->storageRoot . '/app/account-mapping/coverage-snapshots/all-*.json',
|
||||
) ?: []);
|
||||
}
|
||||
|
||||
public function test_interrupted_refresh_request_is_recovered_after_stale_timeout(): void
|
||||
{
|
||||
$coverage = app(AccountMappingCoverage::class);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user