1102 lines
40 KiB
PHP
1102 lines
40 KiB
PHP
<?php
|
||
|
||
namespace Modules\EcommerceFinance\Services;
|
||
|
||
use Carbon\CarbonImmutable;
|
||
use Illuminate\Database\DatabaseManager;
|
||
use Illuminate\Support\Facades\Cache;
|
||
use Illuminate\Support\Facades\File;
|
||
use RuntimeException;
|
||
use Throwable;
|
||
|
||
/**
|
||
* 从已导入账单反推「平台 + 账单项目」覆盖情况。
|
||
*
|
||
* 原始账单项目由后台命令按月份聚合后缓存,页面只读缓存并用当前科目映射过滤。
|
||
* 因此页面请求不会被数百万行账单扫描卡住;补完一条映射后也能立刻从待补清单消失。
|
||
*/
|
||
class AccountMappingCoverage
|
||
{
|
||
private const CACHE_PREFIX = 'account-mapping-coverage-source:v3:';
|
||
|
||
private const STATUS_PREFIX = 'account-mapping-coverage-status:v1:';
|
||
|
||
private const CACHE_HOURS = 24;
|
||
|
||
private const SNAPSHOT_VERSION = 1;
|
||
|
||
private const STATUS_MINUTES = 30;
|
||
|
||
private const REQUEST_STALE_MINUTES = 15;
|
||
|
||
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],
|
||
'拼多多' => ['table' => 'pdd_settlement_bill_rows', 'date' => 'occurred_at', 'periods' => null],
|
||
'京东账单' => ['table' => 'jd_daily_bill_rows', 'date' => 'occurred_at', 'periods' => 'jd_daily_bill_periods'],
|
||
'京东钱包' => ['table' => 'jd_wallet_bill_rows', 'date' => 'occurred_at', 'periods' => 'jd_wallet_bill_periods'],
|
||
'抖音' => ['table' => 'douyin_authoritative_bills', 'date' => 'occurred_at', 'periods' => 'douyin_authoritative_periods'],
|
||
'得物' => ['table' => 'dewu_settlement_bill_rows', 'date' => 'bill_date', 'periods' => null],
|
||
];
|
||
|
||
private const PLATFORM_PREFIX = [
|
||
'天猫' => '天猫',
|
||
'淘宝' => '淘宝',
|
||
'京东' => '京东',
|
||
'京喜' => '京喜',
|
||
'京喜小店' => '京喜',
|
||
'拼多多' => '拼多多',
|
||
'抖音' => '抖音',
|
||
'头条放心购' => '抖音',
|
||
'得物' => '得物',
|
||
'阿里巴巴' => '阿里巴巴',
|
||
'新佰广1688' => '阿里巴巴',
|
||
'淘工厂' => '阿里巴巴',
|
||
'唯品会MP' => '唯品会MP',
|
||
'唯品会JX' => '唯品会JX',
|
||
'支付宝' => '支付宝',
|
||
];
|
||
|
||
/** @var array<string,list<string>> */
|
||
private array $generationCache = [];
|
||
|
||
public function __construct(
|
||
private readonly DatabaseManager $databases,
|
||
private readonly AccountMappingStore $store,
|
||
) {
|
||
}
|
||
|
||
public function defaultMonth(): string
|
||
{
|
||
try {
|
||
return $this->platformNow()->subMonthNoOverflow()->format('Y-m');
|
||
} catch (Throwable) {
|
||
return CarbonImmutable::now()->subMonthNoOverflow()->format('Y-m');
|
||
}
|
||
}
|
||
|
||
/** 本月是否还没有成功生成过跨月清单。 */
|
||
public function monthlyRefreshDue(): bool
|
||
{
|
||
$snapshot = $this->readLatestSnapshot(self::ALL_SCOPE);
|
||
if ($snapshot === null) {
|
||
return true;
|
||
}
|
||
|
||
try {
|
||
return CarbonImmutable::parse($snapshot['refreshed_at'], $this->platformTimezone())
|
||
->format('Y-m') !== $this->platformNow()->format('Y-m');
|
||
} catch (Throwable) {
|
||
return true;
|
||
}
|
||
}
|
||
|
||
/** @return list<string> */
|
||
public function monthOptions(int $months = 18): array
|
||
{
|
||
$months = min(max($months, 1), 60);
|
||
$start = CarbonImmutable::createFromFormat('!Y-m', $this->defaultMonth());
|
||
$options = [];
|
||
for ($index = 0; $index < $months; $index++) {
|
||
$options[] = $start->subMonthsNoOverflow($index)->format('Y-m');
|
||
}
|
||
|
||
return $options;
|
||
}
|
||
|
||
/**
|
||
* @return array{
|
||
* status:string,
|
||
* month:string,
|
||
* source_rows:int,
|
||
* missing_item_count:int,
|
||
* missing_row_count:int,
|
||
* pending_sources:list<string>,
|
||
* items:list<array<string,mixed>>,
|
||
* months:list<string>
|
||
* }
|
||
*/
|
||
public function missingForMonth(
|
||
?string $month = null,
|
||
bool $refresh = false,
|
||
bool $queueIfMissing = false,
|
||
): array
|
||
{
|
||
$period = $this->parseMonth($month);
|
||
$sourceKey = $this->rawCacheKey($period);
|
||
$snapshot = $this->readSnapshot($period, $sourceKey);
|
||
$status = Cache::get($this->statusCacheKey($period), []);
|
||
|
||
if (! $refresh && $snapshot !== null) {
|
||
return $this->missingPayload(
|
||
$period,
|
||
$snapshot['raw'],
|
||
$snapshot['refreshed_at'],
|
||
);
|
||
}
|
||
|
||
$raw = Cache::get($sourceKey);
|
||
if (! $refresh && is_array($raw)) {
|
||
$refreshedAt = is_array($status) ? (string) ($status['refreshed_at'] ?? '') : '';
|
||
$this->writeSnapshot($period, $sourceKey, $raw, $refreshedAt);
|
||
|
||
return $this->missingPayload(
|
||
$period,
|
||
$raw,
|
||
$refreshedAt,
|
||
);
|
||
}
|
||
|
||
if (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'] ?? ''));
|
||
}
|
||
if ($this->hasLiveRefreshRequest($period)) {
|
||
return $this->waitingPayload($period, 'refreshing');
|
||
}
|
||
if (! $refresh && ! $queueIfMissing) {
|
||
return $this->waitingPayload($period, 'missing');
|
||
}
|
||
|
||
$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' => $this->platformNow()->toDateTimeString(),
|
||
], now()->addMinutes(self::STATUS_MINUTES));
|
||
|
||
try {
|
||
$sourceKey = $this->rawCacheKey($period);
|
||
$raw = $this->buildSourceCoverage($period);
|
||
$refreshedAt = $this->platformNow()->toDateTimeString();
|
||
Cache::put($sourceKey, $raw, now()->addHours(self::CACHE_HOURS));
|
||
$this->writeSnapshot($period, $sourceKey, $raw, $refreshedAt);
|
||
Cache::put($this->statusCacheKey($period), [
|
||
'status' => 'ready',
|
||
'refreshed_at' => $refreshedAt,
|
||
], 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' => [],
|
||
];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 页面使用:读取跨月账单项目清单;不会在读取时自动创建扫描任务。
|
||
*
|
||
* @return array<string,mixed>
|
||
*/
|
||
public function missingAcrossMonths(bool $refresh = false, bool $queueIfMissing = false): array
|
||
{
|
||
$snapshotKey = self::ALL_SCOPE;
|
||
if (! $refresh) {
|
||
// 页面只读最近一次成功快照。源数据版本或月份边界变化不能让已有清单失效,
|
||
// 否则用户每次进入页面都会重新看到“尚未生成”。
|
||
$snapshot = $this->readLatestSnapshot($snapshotKey);
|
||
if ($snapshot !== null) {
|
||
return $this->missingAcrossPayload($snapshot['raw'], $snapshot['refreshed_at']);
|
||
}
|
||
}
|
||
|
||
$sourceKey = $this->allSourceKey();
|
||
$status = Cache::get($this->statusCacheKey($snapshotKey), []);
|
||
$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' => $this->platformNow()->toDateTimeString(),
|
||
], now()->addMinutes(self::STATUS_MINUTES));
|
||
|
||
try {
|
||
$sourceKey = $this->allSourceKey();
|
||
[$start, $end] = $this->allPeriodBounds();
|
||
$raw = $this->buildAllSourceCoverage($start, $end);
|
||
$refreshedAt = $this->platformNow()->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->normalizeRefreshKey($month);
|
||
Cache::put($this->statusCacheKey($period), [
|
||
'status' => 'failed',
|
||
'message' => $message,
|
||
'failed_at' => $this->platformNow()->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, string $refreshedAt = ''): array
|
||
{
|
||
$mapping = $this->coverageMappingKeys($this->store->all());
|
||
$items = [];
|
||
$missingRows = 0;
|
||
foreach ($raw['pairs'] as $pair) {
|
||
if ($this->isMapped($pair, $mapping)) {
|
||
continue;
|
||
}
|
||
|
||
$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' => 'month',
|
||
'month' => $period,
|
||
'source_rows' => $raw['source_rows'],
|
||
'missing_item_count' => count($items),
|
||
'missing_row_count' => $missingRows,
|
||
'pending_sources' => $raw['pending_sources'],
|
||
'items' => $items,
|
||
'months' => $this->monthOptions(),
|
||
'retry_after' => null,
|
||
'message' => '',
|
||
'refreshed_at' => $refreshedAt,
|
||
];
|
||
}
|
||
|
||
/**
|
||
* @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,
|
||
'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,
|
||
'pending_sources' => [],
|
||
'items' => [],
|
||
'months' => $this->monthOptions(),
|
||
'retry_after' => self::RETRY_SECONDS,
|
||
'message' => $message,
|
||
'refreshed_at' => null,
|
||
];
|
||
}
|
||
|
||
/** @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' => $this->platformNow()->toDateTimeString(),
|
||
], now()->addMinutes(self::STATUS_MINUTES));
|
||
|
||
try {
|
||
$directory = $this->requestDirectory();
|
||
File::ensureDirectoryExists($directory, 0775, true);
|
||
$pending = $directory . DIRECTORY_SEPARATOR . $period . '.pending';
|
||
$temporary = $pending . '.' . getmypid() . '.tmp';
|
||
$payload = json_encode([
|
||
'month' => $period,
|
||
'requested_at' => $this->platformNow()->toDateTimeString(),
|
||
], JSON_UNESCAPED_UNICODE);
|
||
if ($payload === false || File::put($temporary, $payload, true) === false) {
|
||
throw new RuntimeException('无法写入未映射清单刷新请求。');
|
||
}
|
||
File::move($temporary, $pending, true);
|
||
} catch (Throwable $exception) {
|
||
$this->markFailed($period, $exception->getMessage());
|
||
report($exception);
|
||
|
||
return ['status' => 'failed', 'message' => '刷新请求写入失败,请稍后重试。'];
|
||
}
|
||
|
||
return ['status' => 'refreshing', 'message' => ''];
|
||
}
|
||
|
||
/** @return array{month:string,path:string}|null */
|
||
public function claimPendingRefresh(): ?array
|
||
{
|
||
$directory = $this->requestDirectory();
|
||
if (! File::isDirectory($directory)) {
|
||
return null;
|
||
}
|
||
|
||
$staleBefore = now()->subMinutes(self::REQUEST_STALE_MINUTES)->getTimestamp();
|
||
foreach (File::glob($directory . DIRECTORY_SEPARATOR . '*.running') as $running) {
|
||
if (@filemtime($running) > $staleBefore) {
|
||
continue;
|
||
}
|
||
$month = basename((string) $running, '.running');
|
||
if ($this->isValidRefreshKey($month)) {
|
||
File::move($running, $directory . DIRECTORY_SEPARATOR . $month . '.pending', true);
|
||
}
|
||
}
|
||
|
||
$pendingFiles = File::glob($directory . DIRECTORY_SEPARATOR . '*.pending') ?: [];
|
||
sort($pendingFiles);
|
||
foreach ($pendingFiles as $pending) {
|
||
$month = basename((string) $pending, '.pending');
|
||
if (! $this->isValidRefreshKey($month)) {
|
||
continue;
|
||
}
|
||
$running = $directory . DIRECTORY_SEPARATOR . $month . '.running';
|
||
if (File::exists($running) && @filemtime($running) > $staleBefore) {
|
||
continue;
|
||
}
|
||
File::move($pending, $running, true);
|
||
|
||
return ['month' => $month, 'path' => $running];
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
public function finishPendingRefresh(string $runningPath, bool $succeeded, string $error = ''): void
|
||
{
|
||
if (! File::exists($runningPath)) {
|
||
return;
|
||
}
|
||
|
||
if ($succeeded) {
|
||
File::delete($runningPath);
|
||
|
||
return;
|
||
}
|
||
|
||
$directory = dirname($runningPath);
|
||
$month = basename($runningPath, '.running');
|
||
$failed = $directory . DIRECTORY_SEPARATOR . $month . '.failed';
|
||
File::move($runningPath, $failed, true);
|
||
File::put($failed, json_encode([
|
||
'month' => $month,
|
||
'failed_at' => $this->platformNow()->toDateTimeString(),
|
||
'message' => $error,
|
||
], JSON_UNESCAPED_UNICODE), true);
|
||
}
|
||
|
||
public function requeuePendingRefresh(string $runningPath): void
|
||
{
|
||
if (! File::exists($runningPath)) {
|
||
return;
|
||
}
|
||
$month = basename($runningPath, '.running');
|
||
if (! $this->isValidRefreshKey($month)) {
|
||
return;
|
||
}
|
||
File::move(
|
||
$runningPath,
|
||
dirname($runningPath) . DIRECTORY_SEPARATOR . $month . '.pending',
|
||
true,
|
||
);
|
||
}
|
||
|
||
public function requestDirectory(): string
|
||
{
|
||
return storage_path('app/account-mapping/coverage-requests');
|
||
}
|
||
|
||
/**
|
||
* 持久化快照不放在 storage/framework/cache,避免每次发布 optimize:clear 后重建。
|
||
*
|
||
* @return array{
|
||
* raw: array{status:string,source_rows:int,pending_sources:list<string>,pairs:list<array<string,mixed>>},
|
||
* refreshed_at:string
|
||
* }|null
|
||
*/
|
||
private function readSnapshot(string $period, string $sourceKey): ?array
|
||
{
|
||
return $this->decodeSnapshot($this->snapshotPath($period, $sourceKey), $period, $sourceKey);
|
||
}
|
||
|
||
/**
|
||
* 读取某类清单最近一次成功快照,不要求 source_key 与当前数据版本一致。
|
||
* 这保证手动或月初刷新后的结果会一直保留到下一次成功刷新。
|
||
*
|
||
* @return array{
|
||
* raw: array{status:string,source_rows:int,pending_sources:list<string>,pairs:list<array<string,mixed>>},
|
||
* refreshed_at:string
|
||
* }|null
|
||
*/
|
||
private function readLatestSnapshot(string $period): ?array
|
||
{
|
||
$paths = File::glob($this->snapshotDirectory() . DIRECTORY_SEPARATOR . $period . '-*.json') ?: [];
|
||
usort($paths, static fn (string $left, string $right): int => @filemtime($right) <=> @filemtime($left));
|
||
|
||
foreach ($paths as $path) {
|
||
$snapshot = $this->decodeSnapshot($path, $period);
|
||
if ($snapshot !== null) {
|
||
return $snapshot;
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* @return array{
|
||
* raw: array{status:string,source_rows:int,pending_sources:list<string>,pairs:list<array<string,mixed>>},
|
||
* refreshed_at:string
|
||
* }|null
|
||
*/
|
||
private function decodeSnapshot(string $path, string $period, ?string $sourceKey = null): ?array
|
||
{
|
||
if (! File::isFile($path)) {
|
||
return null;
|
||
}
|
||
|
||
try {
|
||
$snapshot = json_decode(File::get($path), true, 512, JSON_THROW_ON_ERROR);
|
||
if (! is_array($snapshot)
|
||
|| (int) ($snapshot['version'] ?? 0) !== self::SNAPSHOT_VERSION
|
||
|| (string) ($snapshot['month'] ?? '') !== $period
|
||
|| ($sourceKey !== null && (string) ($snapshot['source_key'] ?? '') !== $sourceKey)
|
||
|| ! is_array($snapshot['raw'] ?? null)) {
|
||
return null;
|
||
}
|
||
|
||
$refreshedAt = (string) ($snapshot['refreshed_at'] ?? '');
|
||
CarbonImmutable::parse($refreshedAt);
|
||
|
||
return [
|
||
'raw' => $snapshot['raw'],
|
||
'refreshed_at' => $refreshedAt,
|
||
];
|
||
} catch (Throwable) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/** @param array{status:string,source_rows:int,pending_sources:list<string>,pairs:list<array<string,mixed>>} $raw */
|
||
private function writeSnapshot(string $period, string $sourceKey, array $raw, string $refreshedAt): void
|
||
{
|
||
$directory = $this->snapshotDirectory();
|
||
File::ensureDirectoryExists($directory, 0775, true);
|
||
$path = $this->snapshotPath($period, $sourceKey);
|
||
$temporary = $path . '.' . getmypid() . '.tmp';
|
||
$payload = json_encode([
|
||
'version' => self::SNAPSHOT_VERSION,
|
||
'month' => $period,
|
||
'source_key' => $sourceKey,
|
||
'refreshed_at' => $refreshedAt !== '' ? $refreshedAt : $this->platformNow()->toDateTimeString(),
|
||
'raw' => $raw,
|
||
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
|
||
|
||
if (File::put($temporary, $payload, true) === false || ! File::move($temporary, $path, true)) {
|
||
File::delete($temporary);
|
||
throw new RuntimeException('无法写入未映射清单快照。');
|
||
}
|
||
|
||
foreach (File::glob($directory . DIRECTORY_SEPARATOR . $period . '-*.json') ?: [] as $oldSnapshot) {
|
||
if ($oldSnapshot !== $path) {
|
||
File::delete($oldSnapshot);
|
||
}
|
||
}
|
||
}
|
||
|
||
private function hasLiveRefreshRequest(string $period): bool
|
||
{
|
||
$staleBefore = now()->subMinutes(self::REQUEST_STALE_MINUTES)->getTimestamp();
|
||
foreach (['.pending', '.running'] as $suffix) {
|
||
$path = $this->requestDirectory() . DIRECTORY_SEPARATOR . $period . $suffix;
|
||
if (File::isFile($path) && @filemtime($path) > $staleBefore) {
|
||
return true;
|
||
}
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
private function snapshotDirectory(): string
|
||
{
|
||
return storage_path('app/account-mapping/coverage-snapshots');
|
||
}
|
||
|
||
private function snapshotPath(string $period, string $sourceKey): string
|
||
{
|
||
return $this->snapshotDirectory()
|
||
. DIRECTORY_SEPARATOR
|
||
. $period . '-' . substr(hash('sha256', $sourceKey), 0, 16) . '.json';
|
||
}
|
||
|
||
/** @return array{0:CarbonImmutable,1:CarbonImmutable} */
|
||
private function allPeriodBounds(): array
|
||
{
|
||
try {
|
||
$end = $this->platformNow()->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,
|
||
* source_rows:int,
|
||
* pending_sources:list<string>,
|
||
* pairs:list<array<string,mixed>>
|
||
* }
|
||
*/
|
||
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();
|
||
$parts = [];
|
||
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 . $month . ':' . hash('sha256', implode('|', $parts));
|
||
}
|
||
|
||
private function statusCacheKey(string $month): string
|
||
{
|
||
return self::STATUS_PREFIX . $month;
|
||
}
|
||
|
||
/** @return array<string,true> */
|
||
private function coverageMappingKeys(array $rules): array
|
||
{
|
||
$keys = [];
|
||
foreach ($rules as $rule) {
|
||
$platform = trim((string) ($rule['platform'] ?? ''));
|
||
$item = trim((string) ($rule['item'] ?? ''));
|
||
if ($platform === '' || $item === '') {
|
||
continue;
|
||
}
|
||
$keys[$platform . '|' . $this->normalizeItem($item)] = true;
|
||
}
|
||
|
||
return $keys;
|
||
}
|
||
|
||
private function isMapped(array $pair, array $mapping): bool
|
||
{
|
||
$platform = (string) ($pair['platform'] ?? '');
|
||
$item = (string) ($pair['item'] ?? '');
|
||
if ($platform === '' || $item === '') {
|
||
return false;
|
||
}
|
||
|
||
return isset($mapping[$platform . '|' . $item]);
|
||
}
|
||
|
||
/** @return list<string> */
|
||
private function generations(string $periodsTable, string $start, string $end): array
|
||
{
|
||
$cacheKey = $periodsTable . '|' . $start . '|' . $end;
|
||
if (array_key_exists($cacheKey, $this->generationCache)) {
|
||
return $this->generationCache[$cacheKey];
|
||
}
|
||
|
||
$connection = $this->databases->connection(
|
||
(string) config('upstream_mirrors.connection', 'business_mirror'),
|
||
);
|
||
$schema = $connection->getSchemaBuilder();
|
||
if (! $schema->hasTable($periodsTable)) {
|
||
throw new RuntimeException('账期表尚未迁移:' . $periodsTable);
|
||
}
|
||
|
||
$query = $connection->table($periodsTable)->whereNotNull('active_generation');
|
||
if ($schema->hasColumn($periodsTable, 'period_start')
|
||
&& $schema->hasColumn($periodsTable, 'period_end')) {
|
||
$query->where('period_start', '<=', $end)->where('period_end', '>=', $start);
|
||
}
|
||
|
||
$generations = $query->distinct()->pluck('active_generation')
|
||
->filter(static fn (mixed $value): bool => is_string($value) && $value !== '')
|
||
->unique()
|
||
->values()
|
||
->all();
|
||
|
||
sort($generations);
|
||
|
||
return $this->generationCache[$cacheKey] = $generations;
|
||
}
|
||
|
||
private function platformSql(\Illuminate\Database\ConnectionInterface $connection): string
|
||
{
|
||
$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 'CASE ' . implode(' ', $cases) . " ELSE '' END";
|
||
}
|
||
|
||
private function normalizeItem(string $item): string
|
||
{
|
||
$item = trim($item);
|
||
|
||
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);
|
||
if ($month === '') {
|
||
$month = $this->defaultMonth();
|
||
}
|
||
|
||
try {
|
||
$parsed = preg_match('/^\d{4}-\d{2}$/', $month) === 1
|
||
? CarbonImmutable::createFromFormat('!Y-m', $month)
|
||
: null;
|
||
} catch (Throwable) {
|
||
$parsed = null;
|
||
}
|
||
if ($parsed === null || $parsed->format('Y-m') !== $month) {
|
||
throw new \InvalidArgumentException('账单月份格式必须是 YYYY-MM。');
|
||
}
|
||
|
||
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 {
|
||
return preg_match('/^\d{4}-\d{2}$/', $month) === 1
|
||
&& CarbonImmutable::createFromFormat('!Y-m', $month)->format('Y-m') === $month;
|
||
} catch (Throwable) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
private function platformTimezone(): string
|
||
{
|
||
$timezone = trim((string) config('app.platform_timezone', ''));
|
||
if ($timezone === '') {
|
||
$timezone = (string) config('app.timezone', 'UTC');
|
||
}
|
||
|
||
return $timezone;
|
||
}
|
||
|
||
private function platformNow(): CarbonImmutable
|
||
{
|
||
return CarbonImmutable::now($this->platformTimezone());
|
||
}
|
||
}
|