feat(科目映射): 增加未映射账单项目清单 #1663
50
app/Console/Commands/RefreshAccountMappingCoverage.php
Normal file
50
app/Console/Commands/RefreshAccountMappingCoverage.php
Normal file
@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 后台重建某月账单项目覆盖快照,供科目映射页即时读取。
|
||||
*/
|
||||
class RefreshAccountMappingCoverage extends Command
|
||||
{
|
||||
protected $signature = 'account-mapping:refresh-coverage {month? : 账单月份,格式 YYYY-MM}';
|
||||
|
||||
protected $description = '刷新科目映射的未映射账单项目清单';
|
||||
|
||||
public function handle(AccountMappingCoverage $coverage): int
|
||||
{
|
||||
$month = trim((string) $this->argument('month')) ?: null;
|
||||
|
||||
try {
|
||||
$raw = $coverage->refreshForMonth($month);
|
||||
if (($raw['status'] ?? '') === 'refreshing') {
|
||||
$this->warn('已有刷新任务正在执行,本次跳过。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$summary = $coverage->missingForMonth($month);
|
||||
$this->info(sprintf(
|
||||
'%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d。',
|
||||
(string) $summary['month'],
|
||||
(int) $summary['missing_item_count'],
|
||||
(int) $summary['missing_row_count'],
|
||||
(int) $summary['source_rows'],
|
||||
));
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
if ($month !== null) {
|
||||
$coverage->markFailed($month, $exception->getMessage());
|
||||
}
|
||||
$this->error('未映射账单项目刷新失败:' . $exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -77,11 +77,13 @@ class AccountMappingActions extends Controller
|
||||
{
|
||||
$data = $request->validate([
|
||||
'month' => ['nullable', 'string', 'regex:/^\d{4}-(0[1-9]|1[0-2])$/'],
|
||||
'refresh' => ['nullable', 'boolean'],
|
||||
]);
|
||||
|
||||
try {
|
||||
return response()->json($this->coverage->missingForMonth(
|
||||
trim((string) ($data['month'] ?? '')) ?: null,
|
||||
(bool) ($data['refresh'] ?? false),
|
||||
));
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
throw ValidationException::withMessages(['month' => $exception->getMessage()]);
|
||||
|
||||
@ -5,20 +5,26 @@ namespace Modules\EcommerceFinance\Services;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\Process\Process;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 从已导入账单反推「平台 + 账单项目」覆盖情况。
|
||||
*
|
||||
* 原始账单项目按月份聚合后缓存;每次请求再用当前科目映射过滤。
|
||||
* 因此补完一条映射后,不用重新扫描数百万行账单就能立刻从待补清单消失。
|
||||
* 原始账单项目由后台命令按月份聚合后缓存,页面只读缓存并用当前科目映射过滤。
|
||||
* 因此页面请求不会被数百万行账单扫描卡住;补完一条映射后也能立刻从待补清单消失。
|
||||
*/
|
||||
class AccountMappingCoverage
|
||||
{
|
||||
private const CACHE_PREFIX = 'account-mapping-coverage-source:v1:';
|
||||
private const CACHE_PREFIX = 'account-mapping-coverage-source:v3:';
|
||||
|
||||
private const CACHE_MINUTES = 10;
|
||||
private const STATUS_PREFIX = 'account-mapping-coverage-status:v1:';
|
||||
|
||||
private const CACHE_HOURS = 24;
|
||||
|
||||
private const STATUS_MINUTES = 30;
|
||||
|
||||
private const SOURCES = [
|
||||
'淘系支付宝' => ['table' => 'taobao_alipay_bill_rows', 'date' => 'occurred_at', 'periods' => null],
|
||||
@ -96,16 +102,93 @@ class AccountMappingCoverage
|
||||
* months:list<string>
|
||||
* }
|
||||
*/
|
||||
public function missingForMonth(?string $month = null): array
|
||||
public function missingForMonth(?string $month = null, bool $refresh = false): array
|
||||
{
|
||||
$period = $this->parseMonth($month);
|
||||
$raw = $this->sourceCoverage($period);
|
||||
[$exact, $normalized] = $this->coverageMappingKeys($this->store->all());
|
||||
$raw = Cache::get($this->rawCacheKey($period));
|
||||
|
||||
if (! $refresh && is_array($raw)) {
|
||||
return $this->missingPayload($period, $raw);
|
||||
}
|
||||
|
||||
$status = Cache::get($this->statusCacheKey($period), []);
|
||||
if (! $refresh && is_array($status) && ($status['status'] ?? '') === 'refreshing') {
|
||||
return $this->waitingPayload($period, 'refreshing');
|
||||
}
|
||||
if (! $refresh && is_array($status) && ($status['status'] ?? '') === 'failed') {
|
||||
return $this->waitingPayload($period, 'failed', (string) ($status['message'] ?? ''));
|
||||
}
|
||||
|
||||
$requested = $this->requestRefresh($period);
|
||||
if (($requested['status'] ?? '') === 'failed') {
|
||||
return $this->waitingPayload($period, 'failed', (string) ($requested['message'] ?? ''));
|
||||
}
|
||||
|
||||
return $this->waitingPayload($period, 'refreshing');
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台命令使用:重建某月账单项目聚合,并写入长期缓存。
|
||||
*
|
||||
* @return array{status:string,source_rows:int,pending_sources:list<string>,pairs:list<array<string,mixed>>}
|
||||
*/
|
||||
public function refreshForMonth(?string $month = null): array
|
||||
{
|
||||
$period = $this->parseMonth($month);
|
||||
$lock = Cache::lock('account-mapping-coverage-refresh:' . $period, 900);
|
||||
|
||||
try {
|
||||
return $lock->block(20, function () use ($period): array {
|
||||
Cache::put($this->statusCacheKey($period), [
|
||||
'status' => 'refreshing',
|
||||
'started_at' => now()->toDateTimeString(),
|
||||
], now()->addMinutes(self::STATUS_MINUTES));
|
||||
|
||||
try {
|
||||
$raw = $this->buildSourceCoverage($period);
|
||||
Cache::put($this->rawCacheKey($period), $raw, now()->addHours(self::CACHE_HOURS));
|
||||
Cache::put($this->statusCacheKey($period), [
|
||||
'status' => 'ready',
|
||||
'refreshed_at' => now()->toDateTimeString(),
|
||||
], now()->addMinutes(self::STATUS_MINUTES));
|
||||
|
||||
return $raw;
|
||||
} catch (Throwable $exception) {
|
||||
$this->markFailed($period, $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);
|
||||
Cache::put($this->statusCacheKey($period), [
|
||||
'status' => 'failed',
|
||||
'message' => $message,
|
||||
'failed_at' => now()->toDateTimeString(),
|
||||
], now()->addMinutes(self::STATUS_MINUTES));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{status:string,source_rows:int,pending_sources:list<string>,pairs:list<array<string,mixed>>} $raw
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function missingPayload(string $period, array $raw): array
|
||||
{
|
||||
$mapping = $this->coverageMappingKeys($this->store->all());
|
||||
$items = [];
|
||||
$missingRows = 0;
|
||||
foreach ($raw['pairs'] as $pair) {
|
||||
if ($this->isMapped($pair, $exact, $normalized)) {
|
||||
if ($this->isMapped($pair, $mapping)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -128,9 +211,59 @@ class AccountMappingCoverage
|
||||
'pending_sources' => $raw['pending_sources'],
|
||||
'items' => $items,
|
||||
'months' => $this->monthOptions(),
|
||||
'retry_after' => null,
|
||||
'message' => '',
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function waitingPayload(string $period, string $status, string $message = ''): array
|
||||
{
|
||||
return [
|
||||
'status' => $status,
|
||||
'month' => $period,
|
||||
'source_rows' => 0,
|
||||
'missing_item_count' => 0,
|
||||
'missing_row_count' => 0,
|
||||
'pending_sources' => [],
|
||||
'items' => [],
|
||||
'months' => $this->monthOptions(),
|
||||
'retry_after' => 4,
|
||||
'message' => $message,
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{status:string,message:string} */
|
||||
private function requestRefresh(string $period): array
|
||||
{
|
||||
Cache::put($this->statusCacheKey($period), [
|
||||
'status' => 'refreshing',
|
||||
'started_at' => now()->toDateTimeString(),
|
||||
], now()->addMinutes(self::STATUS_MINUTES));
|
||||
|
||||
if (app()->environment('testing')) {
|
||||
return ['status' => 'refreshing', 'message' => ''];
|
||||
}
|
||||
|
||||
try {
|
||||
$php = escapeshellarg(PHP_BINARY ?: 'php');
|
||||
$command = 'cd ' . escapeshellarg(base_path())
|
||||
. ' && nohup ' . $php . ' artisan account-mapping:refresh-coverage '
|
||||
. escapeshellarg($period) . ' >/dev/null 2>&1 &';
|
||||
Process::fromShellCommandline($command, base_path())
|
||||
->disableOutput()
|
||||
->setTimeout(10)
|
||||
->run();
|
||||
} catch (Throwable $exception) {
|
||||
$this->markFailed($period, $exception->getMessage());
|
||||
Log::warning('科目映射未映射清单后台刷新启动失败:' . $exception->getMessage());
|
||||
|
||||
return ['status' => 'failed', 'message' => '后台刷新进程启动失败,请稍后重试。'];
|
||||
}
|
||||
|
||||
return ['status' => 'refreshing', 'message' => ''];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* status:string,
|
||||
@ -139,7 +272,104 @@ class AccountMappingCoverage
|
||||
* pairs:list<array<string,mixed>>
|
||||
* }
|
||||
*/
|
||||
private function sourceCoverage(string $month): array
|
||||
private function buildSourceCoverage(string $month): array
|
||||
{
|
||||
$start = CarbonImmutable::createFromFormat('!Y-m', $month)->startOfMonth();
|
||||
$end = $start->endOfMonth();
|
||||
$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);
|
||||
}
|
||||
|
||||
$query = $connection->table($table);
|
||||
$dateColumn = (string) $source['date'];
|
||||
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);
|
||||
}
|
||||
|
||||
$platformExpression = $this->platformSql($connection);
|
||||
$itemExpression = $this->normalizedItemSql();
|
||||
$groups = $query
|
||||
->selectRaw($platformExpression . ' AS platform, ' . $itemExpression . ' AS item')
|
||||
->selectRaw('COUNT(*) AS source_rows, COUNT(DISTINCT store_name) AS store_count')
|
||||
->groupByRaw($platformExpression . ', ' . $itemExpression)
|
||||
->cursor();
|
||||
|
||||
foreach ($groups as $group) {
|
||||
$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' => [],
|
||||
];
|
||||
}
|
||||
|
||||
$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]['store_count'] = max(
|
||||
(int) $pairs[$key]['store_count'],
|
||||
(int) $group->store_count,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($pairs as &$pair) {
|
||||
$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),
|
||||
];
|
||||
}
|
||||
|
||||
private function rawCacheKey(string $month): string
|
||||
{
|
||||
$start = CarbonImmutable::createFromFormat('!Y-m', $month)->startOfMonth();
|
||||
$end = $start->endOfMonth();
|
||||
@ -156,140 +386,39 @@ class AccountMappingCoverage
|
||||
));
|
||||
}
|
||||
|
||||
$cacheKey = self::CACHE_PREFIX . $month . ':' . hash('sha256', implode('|', $parts));
|
||||
|
||||
return Cache::remember($cacheKey, now()->addMinutes(self::CACHE_MINUTES), function () use ($start, $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);
|
||||
}
|
||||
|
||||
$query = $connection->table($table);
|
||||
$dateColumn = (string) $source['date'];
|
||||
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);
|
||||
}
|
||||
|
||||
$groups = $query
|
||||
->select(['store_name', 'bill_item'])
|
||||
->selectRaw('COUNT(*) AS source_rows')
|
||||
->groupBy('store_name', 'bill_item')
|
||||
->cursor();
|
||||
|
||||
foreach ($groups as $group) {
|
||||
$rows = (int) $group->source_rows;
|
||||
$sourceRows += $rows;
|
||||
$rawItem = trim((string) $group->bill_item);
|
||||
$displayItem = $rawItem === '' ? '(未填写账单项目)' : $this->normalizeItem($rawItem);
|
||||
$store = trim((string) $group->store_name);
|
||||
$platform = $this->platformFromStore($store);
|
||||
$key = $platform . "\0" . $displayItem;
|
||||
|
||||
if (! isset($pairs[$key])) {
|
||||
$pairs[$key] = [
|
||||
'platform' => $platform,
|
||||
'platform_label' => $platform === '' ? '未识别平台' : $platform,
|
||||
'item' => $displayItem,
|
||||
'source_rows' => 0,
|
||||
'store_count' => 0,
|
||||
'store_samples' => [],
|
||||
'source_labels' => [],
|
||||
'raw_items' => [],
|
||||
];
|
||||
}
|
||||
|
||||
$pairs[$key]['source_rows'] += $rows;
|
||||
$pairs[$key]['source_labels'][$label] = ($pairs[$key]['source_labels'][$label] ?? 0) + $rows;
|
||||
$pairs[$key]['raw_items'][$rawItem] = true;
|
||||
if ($store !== '' && ! in_array($store, $pairs[$key]['store_samples'], true)) {
|
||||
$pairs[$key]['store_count']++;
|
||||
if (count($pairs[$key]['store_samples']) < 5) {
|
||||
$pairs[$key]['store_samples'][] = $store;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($pairs as &$pair) {
|
||||
$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 self::CACHE_PREFIX . $month . ':' . hash('sha256', implode('|', $parts));
|
||||
}
|
||||
|
||||
/** @return array{array<string,true>,array<string,true>} */
|
||||
private function statusCacheKey(string $month): string
|
||||
{
|
||||
return self::STATUS_PREFIX . $month;
|
||||
}
|
||||
|
||||
/** @return array<string,true> */
|
||||
private function coverageMappingKeys(array $rules): array
|
||||
{
|
||||
$exact = [];
|
||||
$normalized = [];
|
||||
$keys = [];
|
||||
foreach ($rules as $rule) {
|
||||
$platform = trim((string) ($rule['platform'] ?? ''));
|
||||
$item = trim((string) ($rule['item'] ?? ''));
|
||||
if ($platform === '' || $item === '') {
|
||||
continue;
|
||||
}
|
||||
$exact[$platform . '|' . $item] = true;
|
||||
$normalized[$platform . '|' . $this->normalizeItem($item)] = true;
|
||||
$keys[$platform . '|' . $this->normalizeItem($item)] = true;
|
||||
}
|
||||
|
||||
return [$exact, $normalized];
|
||||
return $keys;
|
||||
}
|
||||
|
||||
private function isMapped(array $pair, array $exact, array $normalized): bool
|
||||
private function isMapped(array $pair, array $mapping): bool
|
||||
{
|
||||
$platform = (string) ($pair['platform'] ?? '');
|
||||
$item = (string) ($pair['item'] ?? '');
|
||||
if ($platform === '' || $item === '') {
|
||||
return false;
|
||||
}
|
||||
if (isset($normalized[$platform . '|' . $item])) {
|
||||
return true;
|
||||
}
|
||||
foreach ((array) ($pair['raw_items'] ?? []) as $rawItem) {
|
||||
if (isset($exact[$platform . '|' . $rawItem])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
return isset($mapping[$platform . '|' . $item]);
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
@ -325,11 +454,18 @@ class AccountMappingCoverage
|
||||
return $this->generationCache[$cacheKey] = $generations;
|
||||
}
|
||||
|
||||
private function platformFromStore(string $store): string
|
||||
private function platformSql(\Illuminate\Database\ConnectionInterface $connection): string
|
||||
{
|
||||
$prefix = $store === '' ? '' : explode('-', $store, 2)[0];
|
||||
$cases = [];
|
||||
foreach (self::PLATFORM_PREFIX as $prefix => $platform) {
|
||||
$quotedPrefix = $connection->getPdo()->quote($prefix);
|
||||
$quotedPlatform = $connection->getPdo()->quote($platform);
|
||||
$cases[] = 'WHEN store_name = ' . $quotedPrefix
|
||||
. ' OR store_name LIKE ' . $connection->getPdo()->quote($prefix . '-%')
|
||||
. ' THEN ' . $quotedPlatform;
|
||||
}
|
||||
|
||||
return self::PLATFORM_PREFIX[$prefix] ?? '';
|
||||
return 'CASE ' . implode(' ', $cases) . " ELSE '' END";
|
||||
}
|
||||
|
||||
private function normalizeItem(string $item): string
|
||||
@ -339,6 +475,12 @@ class AccountMappingCoverage
|
||||
return preg_match('/^wx/i', $item) === 1 ? ltrim(substr($item, 2)) : $item;
|
||||
}
|
||||
|
||||
private function normalizedItemSql(): string
|
||||
{
|
||||
return "(CASE WHEN LOWER(COALESCE(bill_item, '')) LIKE 'wx%' "
|
||||
. "THEN LTRIM(SUBSTR(bill_item, 3)) ELSE COALESCE(bill_item, '') END)";
|
||||
}
|
||||
|
||||
private function parseMonth(?string $month): string
|
||||
{
|
||||
$month = trim((string) $month);
|
||||
|
||||
@ -138,7 +138,10 @@
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font: 600 0.875rem/1.25 inherit;
|
||||
font-family: inherit;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
cursor: pointer;
|
||||
transition: color 150ms ease;
|
||||
}
|
||||
@ -207,7 +210,10 @@
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
color: var(--vip-content-ink, #171717);
|
||||
font: 400 0.8125rem/1.5 inherit;
|
||||
font-family: inherit;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 400;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.am-coverage-toolbar select:focus {
|
||||
border-color: var(--vip-content-accent-dark, #856632);
|
||||
@ -224,6 +230,7 @@
|
||||
line-height: 1.5;
|
||||
}
|
||||
.am-coverage-summary strong { color: var(--vip-content-ink, #171717); font-size: 0.8125rem; }
|
||||
.am-coverage-summary .is-warning { color: #935f07; }
|
||||
.am-coverage-state {
|
||||
margin-top: 0.75rem;
|
||||
padding: 2rem 1rem;
|
||||
@ -562,7 +569,7 @@
|
||||
<br>
|
||||
· 同一个账单项目在业务上不是同一件事时,用<b>财务备注</b>/<b>商品名称关键词</b>区分:财务备注匹配账单的二次备注、账务备注等(<b>202607订单</b> 这类月份式备注不参与匹配),商品名称按包含匹配;两个都填最优先,其次商品名称,再次财务备注,都不填就是兜底规则。
|
||||
<br>
|
||||
<span style="color:#8a8377;">点行展开看两种收支下的最终分录与校验结果;点「编辑」可直接改这一行;有新增账单项目时用「导入」追加。</span>
|
||||
<span style="color:#8a8377;">点行展开看两种收支下的最终分录与校验结果;点「编辑」可直接改这一行。新增账单项目先去「未映射账单项目」核对,再点「补映射」填写规则。</span>
|
||||
</section>
|
||||
|
||||
@if ($amError)
|
||||
@ -577,6 +584,7 @@
|
||||
aria-selected="{{ $coverageInitialView === 'rules' ? 'true' : 'false' }}"
|
||||
aria-controls="amRulesPanel"
|
||||
data-am-view-tab="rules"
|
||||
tabindex="{{ $coverageInitialView === 'rules' ? '0' : '-1' }}"
|
||||
>
|
||||
已配置规则 <span class="am-view-count">{{ number_format((int) $amSummary['total']) }}</span>
|
||||
</button>
|
||||
@ -587,6 +595,7 @@
|
||||
aria-selected="{{ $coverageInitialView === 'unmapped' ? 'true' : 'false' }}"
|
||||
aria-controls="amCoveragePanel"
|
||||
data-am-view-tab="unmapped"
|
||||
tabindex="{{ $coverageInitialView === 'unmapped' ? '0' : '-1' }}"
|
||||
>
|
||||
未映射账单项目 <span class="am-view-count" id="amCoverageCount">—</span>
|
||||
</button>
|
||||
@ -728,7 +737,7 @@
|
||||
</div>
|
||||
<div class="upstream-data-table-panel" id="amCoverageTableWrap" hidden>
|
||||
<div class="upstream-data-table-scroll">
|
||||
<table class="upstream-data-table am-coverage-table">
|
||||
<table class="upstream-data-table am-coverage-table" data-finance-table-native>
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="am-coverage-index">序号</th>
|
||||
@ -779,6 +788,7 @@
|
||||
var coverageData = null;
|
||||
var coverageLoading = false;
|
||||
var coverageError = '';
|
||||
var coveragePollTimer = null;
|
||||
var returnToCoverageAfterCreate = false;
|
||||
|
||||
// 大类 → 预期方向基准:改大类时顺手把基准带过去,避免两者打架
|
||||
@ -1059,6 +1069,13 @@
|
||||
var title = document.createElement('strong');
|
||||
title.textContent = month;
|
||||
coverageSummaryEl.appendChild(title);
|
||||
if (data && (data.status === 'refreshing' || data.status === 'failed')) {
|
||||
var state = document.createElement('span');
|
||||
state.textContent = data.status === 'refreshing' ? '后台生成中……' : '生成失败';
|
||||
if (data.status === 'failed') { state.className = 'is-warning'; }
|
||||
coverageSummaryEl.appendChild(state);
|
||||
return;
|
||||
}
|
||||
[
|
||||
'未映射 ' + Number(data && data.missing_item_count || 0).toLocaleString('zh-CN') + ' 个项目',
|
||||
'涉及 ' + Number(data && data.missing_row_count || 0).toLocaleString('zh-CN') + ' 行',
|
||||
@ -1068,6 +1085,12 @@
|
||||
span.textContent = text;
|
||||
coverageSummaryEl.appendChild(span);
|
||||
});
|
||||
if (data && Array.isArray(data.pending_sources) && data.pending_sources.length) {
|
||||
var warning = document.createElement('span');
|
||||
warning.className = 'is-warning';
|
||||
warning.textContent = '待同步:' + data.pending_sources.join('、');
|
||||
coverageSummaryEl.appendChild(warning);
|
||||
}
|
||||
}
|
||||
|
||||
function coverageRowHtml(row, index) {
|
||||
@ -1129,6 +1152,26 @@
|
||||
return;
|
||||
}
|
||||
|
||||
if (coverageData.status === 'refreshing') {
|
||||
coverageCountEl.textContent = '…';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '正在后台生成该月未映射清单。账单数据量较大,完成后会自动刷新。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
renderCoverageSummary(coverageData);
|
||||
return;
|
||||
}
|
||||
|
||||
if (coverageData.status === 'failed') {
|
||||
coverageCountEl.textContent = '—';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state am-coverage-state--error';
|
||||
coverageStateEl.textContent = coverageData.message || '该月未映射清单生成失败,请点击“重新读取”重试。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
renderCoverageSummary(coverageData);
|
||||
return;
|
||||
}
|
||||
|
||||
if (coverageData.status !== 'ready') {
|
||||
coverageCountEl.textContent = '—';
|
||||
coverageStateEl.hidden = false;
|
||||
@ -1156,17 +1199,21 @@
|
||||
coverageBodyEl.innerHTML = items.map(coverageRowHtml).join('');
|
||||
}
|
||||
|
||||
function loadCoverage(month, force) {
|
||||
function loadCoverage(month, bypassLocalCache, refreshServer) {
|
||||
if (coverageLoading) { return; }
|
||||
month = String(month || INITIAL_COVERAGE_MONTH || '');
|
||||
if (!force && coverageData && coverageData.month === month) {
|
||||
if (!bypassLocalCache && coverageData && coverageData.month === month) {
|
||||
renderCoverage();
|
||||
return;
|
||||
}
|
||||
if (coveragePollTimer) {
|
||||
clearTimeout(coveragePollTimer);
|
||||
coveragePollTimer = null;
|
||||
}
|
||||
coverageLoading = true;
|
||||
coverageError = '';
|
||||
renderCoverage();
|
||||
api('GET', '/coverage?month=' + encodeURIComponent(month)).then(function (data) {
|
||||
api('GET', '/coverage?month=' + encodeURIComponent(month) + (refreshServer ? '&refresh=1' : '')).then(function (data) {
|
||||
coverageData = data;
|
||||
if (Array.isArray(data.months) && coverageMonthEl) {
|
||||
var current = coverageMonthEl.value;
|
||||
@ -1184,6 +1231,13 @@
|
||||
}).finally(function () {
|
||||
coverageLoading = false;
|
||||
renderCoverage();
|
||||
if (coverageData && coverageData.status === 'refreshing') {
|
||||
var retrySeconds = Math.max(2, Number(coverageData.retry_after || 4));
|
||||
coveragePollTimer = setTimeout(function () {
|
||||
coveragePollTimer = null;
|
||||
loadCoverage(month, true, false);
|
||||
}, retrySeconds * 1000);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@ -1204,10 +1258,10 @@
|
||||
});
|
||||
coverageMonthEl?.addEventListener('change', function () {
|
||||
coverageData = null;
|
||||
loadCoverage(coverageMonthEl.value, true);
|
||||
loadCoverage(coverageMonthEl.value, true, false);
|
||||
});
|
||||
document.getElementById('amCoverageRefresh')?.addEventListener('click', function () {
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH, true);
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH, true, true);
|
||||
});
|
||||
|
||||
/* ---------- 核心:按账单实际收支 + 本行基准,决定照抄还是互换 ---------- */
|
||||
@ -1626,7 +1680,10 @@
|
||||
render();
|
||||
var focus = body.querySelector('tr[data-id="new"] input[data-f="' + (platform ? 'item' : 'platform') + '"]');
|
||||
if (focus) { focus.focus(); }
|
||||
}).catch(function (e) { toast('科目清单加载失败:' + e.message, 'err'); });
|
||||
}).catch(function (e) {
|
||||
returnToCoverageAfterCreate = false;
|
||||
toast('科目清单加载失败:' + e.message, 'err');
|
||||
});
|
||||
}
|
||||
|
||||
document.getElementById('amAdd').addEventListener('click', function () {
|
||||
@ -1667,7 +1724,7 @@
|
||||
if (returnToCoverage) {
|
||||
coverageData = null;
|
||||
selectView('unmapped');
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH, true);
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH, true, false);
|
||||
}
|
||||
}).catch(function (e) { toast(e.message, 'err'); });
|
||||
}
|
||||
@ -1944,7 +2001,7 @@
|
||||
// 平台 / 大类 的候选过去由 Blade 直接渲染,现在改成多选组件后统一由这里灌一次
|
||||
rebuildFilterOptions();
|
||||
selectView(INITIAL_VIEW, false);
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH, true);
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH, true, false);
|
||||
|
||||
// 后台预取账套科目清单(160KB 左右)。不做这一步的话,第一次点「编辑」要等它下载完
|
||||
// 才有反应,用户会以为按钮坏了。
|
||||
|
||||
@ -126,7 +126,7 @@ class AccountMappingPageTest extends FeatureTestCase
|
||||
{
|
||||
$this->grantAdminPermission();
|
||||
$coverage = Mockery::mock(AccountMappingCoverage::class);
|
||||
$coverage->shouldReceive('missingForMonth')->once()->with('2026-11')->andReturn([
|
||||
$coverage->shouldReceive('missingForMonth')->once()->with('2026-11', false)->andReturn([
|
||||
'status' => 'ready',
|
||||
'month' => '2026-11',
|
||||
'source_rows' => 120,
|
||||
|
||||
@ -72,6 +72,11 @@ class AccountMappingCoverageTest extends TestCase
|
||||
]);
|
||||
|
||||
$coverage = app(AccountMappingCoverage::class);
|
||||
$cold = $coverage->missingForMonth('2026-11');
|
||||
$this->assertSame('refreshing', $cold['status']);
|
||||
$this->assertSame(4, $cold['retry_after']);
|
||||
|
||||
$coverage->refreshForMonth('2026-11');
|
||||
$first = $coverage->missingForMonth('2026-11');
|
||||
|
||||
$this->assertSame('ready', $first['status']);
|
||||
@ -79,10 +84,10 @@ class AccountMappingCoverageTest extends TestCase
|
||||
$this->assertSame(4, $first['missing_item_count']);
|
||||
$this->assertSame(7, $first['missing_row_count']);
|
||||
$this->assertSame([
|
||||
'(未填写账单项目)|天猫|1',
|
||||
'交易收款|支付宝|3',
|
||||
'商家货款入账|天猫|2',
|
||||
'未映射售后费|京东|1',
|
||||
'(未填写账单项目)|天猫|1',
|
||||
], $this->missingSignature($first['items']));
|
||||
$this->assertNotContains('上期项目', array_column($first['items'], 'item'));
|
||||
$this->assertNotContains('wx商户费', array_column($first['items'], 'item'));
|
||||
@ -126,12 +131,20 @@ class AccountMappingCoverageTest extends TestCase
|
||||
|
||||
private function insertBill(string $table, string $dateColumn, array $rows): void
|
||||
{
|
||||
foreach ($rows as $row) {
|
||||
foreach ($rows as $index => $row) {
|
||||
$values = [
|
||||
'store_name' => $row['store_name'],
|
||||
'bill_item' => $row['bill_item'],
|
||||
$dateColumn => $row['day'],
|
||||
];
|
||||
if ($table === 'jd_daily_bill_rows') {
|
||||
$values += [
|
||||
'record_code' => 'row-' . $index . '-' . md5($row['store_name'] . $row['day']),
|
||||
'income' => 0,
|
||||
'expense' => 0,
|
||||
'row_data' => '{}',
|
||||
];
|
||||
}
|
||||
if (isset($row['generation'])) {
|
||||
$values['generation'] = $row['generation'];
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user