363 lines
13 KiB
PHP
363 lines
13 KiB
PHP
<?php
|
|
|
|
namespace Modules\EcommerceFinance\Services;
|
|
|
|
use Carbon\CarbonImmutable;
|
|
use Illuminate\Database\DatabaseManager;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use RuntimeException;
|
|
use Throwable;
|
|
|
|
/**
|
|
* 从已导入账单反推「平台 + 账单项目」覆盖情况。
|
|
*
|
|
* 原始账单项目按月份聚合后缓存;每次请求再用当前科目映射过滤。
|
|
* 因此补完一条映射后,不用重新扫描数百万行账单就能立刻从待补清单消失。
|
|
*/
|
|
class AccountMappingCoverage
|
|
{
|
|
private const CACHE_PREFIX = 'account-mapping-coverage-source:v1:';
|
|
|
|
private const CACHE_MINUTES = 10;
|
|
|
|
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
|
|
{
|
|
$timezone = trim((string) config('app.platform_timezone', ''));
|
|
if ($timezone === '') {
|
|
$timezone = (string) config('app.timezone', 'UTC');
|
|
}
|
|
|
|
try {
|
|
return CarbonImmutable::now($timezone)->subMonthNoOverflow()->format('Y-m');
|
|
} catch (Throwable) {
|
|
return CarbonImmutable::now()->subMonthNoOverflow()->format('Y-m');
|
|
}
|
|
}
|
|
|
|
/** @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): array
|
|
{
|
|
$period = $this->parseMonth($month);
|
|
$raw = $this->sourceCoverage($period);
|
|
[$exact, $normalized] = $this->coverageMappingKeys($this->store->all());
|
|
|
|
$items = [];
|
|
$missingRows = 0;
|
|
foreach ($raw['pairs'] as $pair) {
|
|
if ($this->isMapped($pair, $exact, $normalized)) {
|
|
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'],
|
|
'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(),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* @return array{
|
|
* status:string,
|
|
* source_rows:int,
|
|
* pending_sources:list<string>,
|
|
* pairs:list<array<string,mixed>>
|
|
* }
|
|
*/
|
|
private function sourceCoverage(string $month): array
|
|
{
|
|
$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(),
|
|
));
|
|
}
|
|
|
|
$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 array{array<string,true>,array<string,true>} */
|
|
private function coverageMappingKeys(array $rules): array
|
|
{
|
|
$exact = [];
|
|
$normalized = [];
|
|
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;
|
|
}
|
|
|
|
return [$exact, $normalized];
|
|
}
|
|
|
|
private function isMapped(array $pair, array $exact, array $normalized): 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 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 platformFromStore(string $store): string
|
|
{
|
|
$prefix = $store === '' ? '' : explode('-', $store, 2)[0];
|
|
|
|
return self::PLATFORM_PREFIX[$prefix] ?? '';
|
|
}
|
|
|
|
private function normalizeItem(string $item): string
|
|
{
|
|
$item = trim($item);
|
|
|
|
return preg_match('/^wx/i', $item) === 1 ? ltrim(substr($item, 2)) : $item;
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|