parent
8e1135bc59
commit
0156a89f87
73
app/Console/Commands/RefreshAccountMappingCoverage.php
Normal file
73
app/Console/Commands/RefreshAccountMappingCoverage.php
Normal file
@ -0,0 +1,73 @@
|
||||
<?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}
|
||||
{--pending : 处理页面登记的下一个刷新请求}';
|
||||
|
||||
protected $description = '刷新科目映射的未映射账单项目清单';
|
||||
|
||||
public function handle(AccountMappingCoverage $coverage): int
|
||||
{
|
||||
$runningPath = null;
|
||||
$month = trim((string) $this->argument('month')) ?: null;
|
||||
if ($this->option('pending')) {
|
||||
$request = $coverage->claimPendingRefresh();
|
||||
if ($request === null) {
|
||||
$this->line('没有待处理的未映射清单刷新请求。');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
$month = $request['month'];
|
||||
$runningPath = $request['path'];
|
||||
}
|
||||
|
||||
try {
|
||||
$raw = $coverage->refreshForMonth($month);
|
||||
if (($raw['status'] ?? '') === 'refreshing') {
|
||||
$this->warn('已有刷新任务正在执行,本次跳过。');
|
||||
if ($runningPath !== null) {
|
||||
$coverage->requeuePendingRefresh($runningPath);
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$summary = $coverage->missingForMonth($month);
|
||||
$this->info(sprintf(
|
||||
'%s 未映射账单项目刷新完成:%d 个项目,涉及 %d 行,账单总行数 %d;PHP 峰值内存 %.1f MiB。',
|
||||
(string) $summary['month'],
|
||||
(int) $summary['missing_item_count'],
|
||||
(int) $summary['missing_row_count'],
|
||||
(int) $summary['source_rows'],
|
||||
memory_get_peak_usage(true) / 1048576,
|
||||
));
|
||||
if ($runningPath !== null) {
|
||||
$coverage->finishPendingRefresh($runningPath, true);
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
if ($month !== null) {
|
||||
$coverage->markFailed($month, $exception->getMessage());
|
||||
}
|
||||
if ($runningPath !== null) {
|
||||
$coverage->finishPendingRefresh($runningPath, false, $exception->getMessage());
|
||||
}
|
||||
$this->error('未映射账单项目刷新失败:' . $exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -9,12 +9,14 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingCoa;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingStore;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingValidator;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingWorkbookImporter;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher;
|
||||
use RuntimeException;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* 财务规则 · 科目映射表的维护接口。
|
||||
@ -56,6 +58,7 @@ class AccountMappingActions extends Controller
|
||||
private readonly AccountMappingValidator $validator,
|
||||
private readonly AccountMappingCoa $coa,
|
||||
private readonly AccountMappingWorkbookImporter $importer,
|
||||
private readonly AccountMappingCoverage $coverage,
|
||||
) {
|
||||
$this->middleware('auth');
|
||||
$this->middleware('company.identify');
|
||||
@ -67,6 +70,32 @@ class AccountMappingActions extends Controller
|
||||
return response()->json($this->payload());
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前账单里有、但科目映射表里没有同平台同项目的账单项目。
|
||||
*/
|
||||
public function coverage(Request $request): JsonResponse
|
||||
{
|
||||
$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()]);
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return response()->json([
|
||||
'message' => '未映射账单项目暂时无法读取,请稍后重试。',
|
||||
], 503);
|
||||
}
|
||||
}
|
||||
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$values = $this->payloadValues($request);
|
||||
|
||||
@ -263,6 +263,8 @@ CRON_TZ=Asia/Shanghai
|
||||
*/15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1
|
||||
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1
|
||||
# 科目映射未映射清单按需在受限批容器刷新,网页只登记请求并读取缓存。
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1
|
||||
# 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。
|
||||
|
||||
@ -267,6 +267,8 @@ CRON_TZ=Asia/Shanghai
|
||||
*/15 * * * * root /usr/bin/flock -n /run/caiwu-ding-attendance-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-attendance --quiet >/dev/null 2>&1
|
||||
# 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1
|
||||
# 科目映射未映射清单按需在受限批容器刷新,网页只登记请求并读取缓存。
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1
|
||||
* * * * * root /usr/bin/flock -n /run/caiwu-portal-freight.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh portal-freight:import-pending --quiet >/dev/null 2>&1
|
||||
# 生产发货同步由系统 cron 执行,Laravel Kernel 的 40 天计划不生效;凌晨补拉 40 天,避免三天前的数据长期未刷新。
|
||||
|
||||
@ -12,7 +12,7 @@ case "${1:-}" in
|
||||
planting-reimbursement:auto-confirm) is_import=1 ;;
|
||||
jushuitan:apply-shipping-corrections|*:import|*:import-*|*:import:*|payables:final-import|payables:unpriced-cycle|payables:unpriced-cycle:auto|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;;
|
||||
jushuitan:align-weights|jushuitan:calc-freight|courier:sync-unshipped-waybills|courier:seed-unshipped-history) ;;
|
||||
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-jushuitan-shop-promotion-fees|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
|
||||
jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-promotion-expenses|business-mirror:sync-jushuitan-shop-promotion-fees|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|account-mapping:refresh-coverage|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;;
|
||||
*) echo 'Unsupported finance batch command' >&2; exit 64 ;;
|
||||
esac
|
||||
case "${1:-}" in
|
||||
@ -58,6 +58,15 @@ if [ "$1" = 'business-mirror:process-ding-refresh-requests' ]; then
|
||||
pending_request="$(find "$storage_root/app/ding-process-refresh" -maxdepth 1 -type f -name '*.pending' -print -quit)"
|
||||
[ -n "$pending_request" ] || exit 0
|
||||
fi
|
||||
if [ "$1" = 'account-mapping:refresh-coverage' ] && [ "${2:-}" = '--pending' ]; then
|
||||
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
|
||||
[ -n "$storage_root" ] || exit 0
|
||||
pending_request="$(find "$storage_root/app/account-mapping/coverage-requests" -maxdepth 1 -type f -name '*.pending' -print -quit 2>/dev/null || true)"
|
||||
if [ -z "$pending_request" ]; then
|
||||
pending_request="$(find "$storage_root/app/account-mapping/coverage-requests" -maxdepth 1 -type f -name '*.running' -mmin +15 -print -quit 2>/dev/null || true)"
|
||||
fi
|
||||
[ -n "$pending_request" ] || exit 0
|
||||
fi
|
||||
if [ "$1" = 'ding-invoices:process-refresh-requests' ]; then
|
||||
storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')"
|
||||
[ -n "$storage_root" ] && [ -d "$storage_root/app/ding-invoice-refresh" ] || exit 0
|
||||
@ -106,4 +115,14 @@ if [ "$1" = 'jushuitan:sync-shipping' ]; then
|
||||
sleep "${CAIWU_JST_SYNC_RETRY_WAIT:-300}"
|
||||
done
|
||||
fi
|
||||
if [ "$1" = 'account-mapping:refresh-coverage' ]; then
|
||||
container_name="caiwu_account_mapping_coverage_$$"
|
||||
cleanup_coverage_batch() {
|
||||
docker rm --force "$container_name" >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup_coverage_batch EXIT INT TERM
|
||||
/usr/bin/timeout 1800 docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps \
|
||||
--name "$container_name" batch "$@"
|
||||
exit $?
|
||||
fi
|
||||
docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps batch "$@"
|
||||
|
||||
603
modules/EcommerceFinance/Services/AccountMappingCoverage.php
Normal file
603
modules/EcommerceFinance/Services/AccountMappingCoverage.php
Normal file
@ -0,0 +1,603 @@
|
||||
<?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 STATUS_MINUTES = 30;
|
||||
|
||||
private const REQUEST_STALE_MINUTES = 15;
|
||||
|
||||
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, bool $refresh = false): array
|
||||
{
|
||||
$period = $this->parseMonth($month);
|
||||
$raw = Cache::get($this->rawCacheKey($period));
|
||||
$status = Cache::get($this->statusCacheKey($period), []);
|
||||
|
||||
if (! $refresh && is_array($raw)) {
|
||||
return $this->missingPayload(
|
||||
$period,
|
||||
$raw,
|
||||
is_array($status) ? (string) ($status['refreshed_at'] ?? '') : '',
|
||||
);
|
||||
}
|
||||
|
||||
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, 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'],
|
||||
'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,
|
||||
];
|
||||
}
|
||||
|
||||
/** @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,
|
||||
'refreshed_at' => null,
|
||||
];
|
||||
}
|
||||
|
||||
/** @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));
|
||||
|
||||
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' => now()->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->isValidMonth($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->isValidMonth($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' => now()->toDateTimeString(),
|
||||
'message' => $error,
|
||||
], JSON_UNESCAPED_UNICODE), true);
|
||||
}
|
||||
|
||||
public function requeuePendingRefresh(string $runningPath): void
|
||||
{
|
||||
if (! File::exists($runningPath)) {
|
||||
return;
|
||||
}
|
||||
$month = basename($runningPath, '.running');
|
||||
if (! $this->isValidMonth($month)) {
|
||||
return;
|
||||
}
|
||||
File::move(
|
||||
$runningPath,
|
||||
dirname($runningPath) . DIRECTORY_SEPARATOR . $month . '.pending',
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
public function requestDirectory(): string
|
||||
{
|
||||
return storage_path('app/account-mapping/coverage-requests');
|
||||
}
|
||||
|
||||
/**
|
||||
* @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 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -11,6 +11,23 @@
|
||||
|
||||
$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;
|
||||
foreach ($amRows as $r) {
|
||||
@ -100,6 +117,154 @@
|
||||
.am-issue--提示 { border-color: #dce6ef; background: #f8fbfd; }
|
||||
.am-issue--提示 .am-issue__tag { color: #40607e; }
|
||||
|
||||
.am-views {
|
||||
display: flex;
|
||||
min-height: 48px;
|
||||
align-items: center;
|
||||
gap: 2rem;
|
||||
margin-top: 1rem;
|
||||
padding: 0 1.25rem;
|
||||
border: 1px solid var(--vip-border, #d8d2c7);
|
||||
border-radius: 12px 12px 0 0;
|
||||
background: var(--vip-surface, #fff);
|
||||
}
|
||||
.am-view-tab {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
min-height: 48px;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-family: inherit;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
cursor: pointer;
|
||||
transition: color 150ms ease;
|
||||
}
|
||||
.am-view-tab:hover,
|
||||
.am-view-tab[aria-selected="true"] { color: var(--vip-content-accent-dark, #856632); }
|
||||
.am-view-tab[aria-selected="true"]::after {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
height: 3px;
|
||||
border-radius: 999px 999px 0 0;
|
||||
background: var(--vip-content-accent, #b9954f);
|
||||
content: '';
|
||||
}
|
||||
.am-view-tab:focus-visible {
|
||||
outline: 2px solid var(--vip-content-accent-dark, #856632);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
.am-view-count {
|
||||
display: inline-flex;
|
||||
min-width: 1.75rem;
|
||||
height: 1.25rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 0.4rem;
|
||||
border: 1px solid var(--vip-border, #d8d2c7);
|
||||
border-radius: 999px;
|
||||
background: var(--vip-content-bg, #f8f6f1);
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.6875rem;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1;
|
||||
}
|
||||
.am-view-panel { padding-top: 0.75rem; }
|
||||
.am-coverage-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem 1rem;
|
||||
margin-top: 0.75rem;
|
||||
padding: 0.9rem 1rem;
|
||||
border: 1px solid var(--vip-border, #d8d2c7);
|
||||
border-radius: 12px;
|
||||
background: var(--vip-surface, #fff);
|
||||
}
|
||||
.am-coverage-toolbar__fields {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.am-coverage-toolbar label {
|
||||
display: grid;
|
||||
gap: 0.3rem;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
.am-coverage-toolbar select {
|
||||
min-width: 9rem;
|
||||
height: 2.125rem;
|
||||
padding: 0 0.65rem;
|
||||
border: 1px solid var(--vip-border, #d8d2c7);
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
color: var(--vip-content-ink, #171717);
|
||||
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);
|
||||
box-shadow: 0 0 0 3px rgba(133, 102, 50, 0.2);
|
||||
outline: none;
|
||||
}
|
||||
.am-coverage-summary {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.4rem 1rem;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.75rem;
|
||||
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;
|
||||
border: 1px dashed var(--vip-border, #d8d2c7);
|
||||
border-radius: 12px;
|
||||
background: var(--vip-surface, #fff);
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.8125rem;
|
||||
line-height: 1.7;
|
||||
text-align: center;
|
||||
}
|
||||
.am-coverage-state--error { border-color: #e5bcbc; color: #8e2f2f; }
|
||||
.am-coverage-table { min-width: 62rem; 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-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; }
|
||||
.am-coverage-table .am-coverage-action { width: 8rem; }
|
||||
.am-coverage-source-tag {
|
||||
display: inline-block;
|
||||
margin: 0.1rem 0.2rem 0.1rem 0;
|
||||
padding: 0.1rem 0.4rem;
|
||||
border-radius: 999px;
|
||||
background: var(--vip-content-accent-soft, #f7f0de);
|
||||
color: var(--vip-content-accent-dark, #856632);
|
||||
font-size: 0.6875rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.am-coverage-store-hint { color: var(--vip-content-muted, #595959); font-size: 0.6875rem; }
|
||||
|
||||
/* 表格必须锁列宽(table-layout:fixed)。默认的自动列宽会按内容互相挤压,
|
||||
「借方/贷方科目」两列会被挤到文字被截断;锁死后按上面 th 的宽度分配,
|
||||
窗口不够宽时由外层 .upstream-data-table-scroll 横向滚动。
|
||||
@ -404,13 +569,45 @@
|
||||
<br>
|
||||
· 同一个账单项目在业务上不是同一件事时,用<b>财务备注</b>/<b>商品名称关键词</b>区分:财务备注匹配账单的二次备注、账务备注等(<b>202607订单</b> 这类月份式备注不参与匹配),商品名称按包含匹配;两个都填最优先,其次商品名称,再次财务备注,都不填就是兜底规则。
|
||||
<br>
|
||||
<span style="color:#8a8377;">点行展开看两种收支下的最终分录与校验结果;点「编辑」可直接改这一行;有新增账单项目时用「导入」追加。</span>
|
||||
<span style="color:#8a8377;">点行展开看两种收支下的最终分录与校验结果;点「编辑」可直接改这一行。新增账单项目先去「未映射账单项目」核对,再点「补映射」填写规则。</span>
|
||||
</section>
|
||||
|
||||
@if ($amError)
|
||||
<div class="am-alert">读取映射表失败:{{ $amError }}</div>
|
||||
@endif
|
||||
|
||||
<nav class="am-views" role="tablist" aria-label="科目映射视图" data-am-views>
|
||||
<button
|
||||
type="button"
|
||||
class="am-view-tab"
|
||||
role="tab"
|
||||
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>
|
||||
<button
|
||||
type="button"
|
||||
class="am-view-tab"
|
||||
role="tab"
|
||||
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>
|
||||
</nav>
|
||||
|
||||
<div
|
||||
id="amRulesPanel"
|
||||
class="am-view-panel"
|
||||
role="tabpanel"
|
||||
data-am-view-panel="rules"
|
||||
@if ($coverageInitialView !== 'rules') hidden @endif
|
||||
>
|
||||
<div class="upstream-data-summary">
|
||||
<div class="am-summary" id="amSummaryBar">
|
||||
<span>共 <b id="amTotal">{{ $amSummary['total'] }}</b> 条规则</span>
|
||||
@ -509,6 +706,54 @@
|
||||
</div>
|
||||
<div class="am-empty" id="amEmpty" hidden>没有符合条件的数据。</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="amCoveragePanel"
|
||||
class="am-view-panel"
|
||||
role="tabpanel"
|
||||
data-am-view-panel="unmapped"
|
||||
@if ($coverageInitialView !== 'unmapped') hidden @endif
|
||||
>
|
||||
<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>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
<div class="am-coverage-state" id="amCoverageState">
|
||||
正在读取该月账单项目,请稍候。
|
||||
</div>
|
||||
<div class="upstream-data-table-panel" id="amCoverageTableWrap" hidden>
|
||||
<div class="upstream-data-table-scroll">
|
||||
<table class="upstream-data-table am-coverage-table" data-finance-table-native>
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="am-coverage-index">序号</th>
|
||||
<th class="am-coverage-platform">平台</th>
|
||||
<th class="am-coverage-item">账单项目</th>
|
||||
<th class="am-coverage-source">来源账单</th>
|
||||
<th class="am-coverage-count">影响行数</th>
|
||||
<th class="am-coverage-stores">店铺数</th>
|
||||
<th class="am-coverage-action">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="amCoverageBody"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="am-modal" id="amModal" hidden>
|
||||
@ -534,10 +779,17 @@
|
||||
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;
|
||||
var draft = null;
|
||||
var openId = null;
|
||||
var coverageData = null;
|
||||
var coverageLoading = false;
|
||||
var coverageError = '';
|
||||
var coveragePollTimer = null;
|
||||
var returnToCoverageAfterCreate = false;
|
||||
|
||||
// 大类 → 预期方向基准:改大类时顺手把基准带过去,避免两者打架
|
||||
var CATEGORY_BASIS = {
|
||||
@ -778,6 +1030,245 @@
|
||||
toastEl._t = setTimeout(function () { toastEl.hidden = true; }, 4200);
|
||||
}
|
||||
|
||||
/* ---------- 账单覆盖:已配置规则 / 未映射账单项目 ---------- */
|
||||
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');
|
||||
var coverageBodyEl = document.getElementById('amCoverageBody');
|
||||
var coverageTableWrapEl = document.getElementById('amCoverageTableWrap');
|
||||
|
||||
function selectView(name, updateUrl) {
|
||||
var selected = name === 'unmapped' ? 'unmapped' : 'rules';
|
||||
viewButtons.forEach(function (button) {
|
||||
var active = button.getAttribute('data-am-view-tab') === selected;
|
||||
button.setAttribute('aria-selected', active ? 'true' : 'false');
|
||||
button.tabIndex = active ? 0 : -1;
|
||||
});
|
||||
viewPanels.forEach(function (panel) {
|
||||
panel.hidden = panel.getAttribute('data-am-view-panel') !== selected;
|
||||
});
|
||||
|
||||
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);
|
||||
window.history.replaceState({}, '', url);
|
||||
}
|
||||
if (selected === 'unmapped' && !coverageData && !coverageLoading) {
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH);
|
||||
}
|
||||
}
|
||||
|
||||
function renderCoverageSummary(data) {
|
||||
if (!coverageSummaryEl) { return; }
|
||||
coverageSummaryEl.innerHTML = '';
|
||||
var month = String(data && data.month ? data.month : (coverageMonthEl ? coverageMonthEl.value : ''));
|
||||
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') + ' 行',
|
||||
'账单总行数 ' + Number(data && data.source_rows || 0).toLocaleString('zh-CN'),
|
||||
].forEach(function (text) {
|
||||
var span = document.createElement('span');
|
||||
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);
|
||||
}
|
||||
if (data && data.refreshed_at) {
|
||||
var refreshedAt = document.createElement('span');
|
||||
refreshedAt.textContent = '更新于 ' + data.refreshed_at;
|
||||
coverageSummaryEl.appendChild(refreshedAt);
|
||||
}
|
||||
}
|
||||
|
||||
function coverageRowHtml(row, index) {
|
||||
var rawItems = Array.isArray(row.raw_items) ? row.raw_items : [];
|
||||
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 || '');
|
||||
var item = String(row.item || '');
|
||||
var rawHint = rawItems.filter(function (value) { return value !== item; }).join('、');
|
||||
var storeHint = storeSamples.length ? '店铺示例:' + storeSamples.join('、') : '';
|
||||
return '<tr>'
|
||||
+ '<td>' + (index + 1) + '</td>'
|
||||
+ '<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>' + sourceLabels.map(function (label) {
|
||||
return '<span class="am-coverage-source-tag">' + esc(label) + '</span>';
|
||||
}).join('') + '</td>'
|
||||
+ '<td class="am-coverage-count">' + Number(row.source_rows || 0).toLocaleString('zh-CN') + '</td>'
|
||||
+ '<td class="am-coverage-stores" title="' + esc(storeHint) + '">' + Number(row.store_count || 0).toLocaleString('zh-CN') + '</td>'
|
||||
+ '<td>' + (platform
|
||||
? '<button type="button" class="am-btn am-btn--primary" data-am-coverage-add data-platform="' + esc(platform) + '" data-item="' + esc(item) + '">补映射</button>'
|
||||
: '<span class="am-coverage-store-hint">先补充平台识别</span>') + '</td>'
|
||||
+ '</tr>';
|
||||
}
|
||||
|
||||
function renderCoverage() {
|
||||
if (!coverageStateEl || !coverageTableWrapEl || !coverageBodyEl || !coverageCountEl) { return; }
|
||||
if (coverageLoading) {
|
||||
coverageCountEl.textContent = '…';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '正在读取该月账单项目,请稍候。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
if (coverageSummaryEl) {
|
||||
coverageSummaryEl.innerHTML = '<strong>' + esc(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH) + '</strong><span>正在读取……</span>';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (coverageError) {
|
||||
coverageCountEl.textContent = '—';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state am-coverage-state--error';
|
||||
coverageStateEl.textContent = coverageError;
|
||||
coverageTableWrapEl.hidden = true;
|
||||
if (coverageSummaryEl) {
|
||||
coverageSummaryEl.innerHTML = '<strong>' + esc(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH) + '</strong><span>读取失败</span>';
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!coverageData) {
|
||||
coverageCountEl.textContent = '—';
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '切换到此视图后开始读取账单项目。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
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;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '所选月份暂无已导入账单,暂时无法生成未映射科目清单。请更换月份或等待账单同步完成。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
renderCoverageSummary(coverageData);
|
||||
return;
|
||||
}
|
||||
|
||||
var items = Array.isArray(coverageData.items) ? coverageData.items : [];
|
||||
coverageCountEl.textContent = Number(coverageData.missing_item_count || 0).toLocaleString('zh-CN');
|
||||
renderCoverageSummary(coverageData);
|
||||
if (!items.length) {
|
||||
coverageStateEl.hidden = false;
|
||||
coverageStateEl.className = 'am-coverage-state';
|
||||
coverageStateEl.textContent = '所选月份的所有账单项目均已配置科目映射。';
|
||||
coverageTableWrapEl.hidden = true;
|
||||
coverageBodyEl.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
|
||||
coverageStateEl.hidden = true;
|
||||
coverageTableWrapEl.hidden = false;
|
||||
coverageBodyEl.innerHTML = items.map(coverageRowHtml).join('');
|
||||
}
|
||||
|
||||
function loadCoverage(month, bypassLocalCache, refreshServer) {
|
||||
if (coverageLoading) { return; }
|
||||
month = String(month || INITIAL_COVERAGE_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) + (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;
|
||||
}).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);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
document.querySelector('[data-am-views]')?.addEventListener('keydown', function (event) {
|
||||
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key) || !viewButtons.length) { return; }
|
||||
event.preventDefault();
|
||||
var current = viewButtons.findIndex(function (button) { return button.getAttribute('aria-selected') === 'true'; });
|
||||
var next = event.key === 'Home' ? 0
|
||||
: event.key === 'End' ? viewButtons.length - 1
|
||||
: (current + (event.key === 'ArrowRight' ? 1 : -1) + viewButtons.length) % viewButtons.length;
|
||||
selectView(viewButtons[next].getAttribute('data-am-view-tab'));
|
||||
viewButtons[next].focus();
|
||||
});
|
||||
viewButtons.forEach(function (button) {
|
||||
button.addEventListener('click', function () {
|
||||
selectView(button.getAttribute('data-am-view-tab'));
|
||||
});
|
||||
});
|
||||
coverageMonthEl?.addEventListener('change', function () {
|
||||
coverageData = null;
|
||||
loadCoverage(coverageMonthEl.value, true, false);
|
||||
});
|
||||
document.getElementById('amCoverageRefresh')?.addEventListener('click', function () {
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH, true, true);
|
||||
});
|
||||
|
||||
/* ---------- 核心:按账单实际收支 + 本行基准,决定照抄还是互换 ---------- */
|
||||
function entry(r, flow) {
|
||||
var natural = (r.basis === '支出基准') ? 'out' : 'in';
|
||||
@ -1076,7 +1567,16 @@
|
||||
var act = btn.getAttribute('data-act');
|
||||
var isNew = tr.getAttribute('data-id') === 'new';
|
||||
if (act === 'edit') { startEdit(id); }
|
||||
else if (act === 'cancel') { editingId = null; draft = null; render(); }
|
||||
else if (act === 'cancel') {
|
||||
var returnToCoverage = returnToCoverageAfterCreate;
|
||||
returnToCoverageAfterCreate = false;
|
||||
editingId = null;
|
||||
draft = null;
|
||||
render();
|
||||
if (returnToCoverage) {
|
||||
selectView('unmapped');
|
||||
}
|
||||
}
|
||||
else if (act === 'save') { if (isNew) { createRow(); } else { saveEdit(id); } }
|
||||
else if (act === 'delete') { removeRow(id); }
|
||||
return;
|
||||
@ -1171,19 +1671,28 @@
|
||||
}
|
||||
|
||||
/* ---------- 新增 ---------- */
|
||||
document.getElementById('amAdd').addEventListener('click', function () {
|
||||
function startNewRule(platform, item, fromCoverage) {
|
||||
if (editingId) { toast('请先保存或取消正在编辑的那一行。', 'err'); return; }
|
||||
returnToCoverageAfterCreate = fromCoverage === true;
|
||||
loadCoa().then(function () {
|
||||
draft = {
|
||||
platform: '', item: '', memo: '', goods: '', invoice: '-', category: '费用',
|
||||
platform: platform || '', item: item || '', memo: '', goods: '', invoice: '-', category: '费用',
|
||||
feeMemo: '', dAcct: '', dSub: '', cAcct: '', cSub: '', basis: '支出基准'
|
||||
};
|
||||
editingId = 'new';
|
||||
collapseDetail();
|
||||
selectView('rules');
|
||||
render();
|
||||
var focus = body.querySelector('tr[data-id="new"] input[data-f="platform"]');
|
||||
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 () {
|
||||
startNewRule('', '', false);
|
||||
});
|
||||
|
||||
function newRowHtml() {
|
||||
@ -1213,11 +1722,24 @@
|
||||
return;
|
||||
}
|
||||
api('POST', '/rules', { values: values }).then(function (data) {
|
||||
var returnToCoverage = returnToCoverageAfterCreate;
|
||||
returnToCoverageAfterCreate = false;
|
||||
applyState(data);
|
||||
toast(data.message || '已新增。');
|
||||
if (returnToCoverage) {
|
||||
coverageData = null;
|
||||
selectView('unmapped');
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH, true, false);
|
||||
}
|
||||
}).catch(function (e) { toast(e.message, 'err'); });
|
||||
}
|
||||
|
||||
coverageBodyEl?.addEventListener('click', function (event) {
|
||||
var button = event.target.closest('[data-am-coverage-add]');
|
||||
if (!button) { return; }
|
||||
startNewRule(button.getAttribute('data-platform') || '', button.getAttribute('data-item') || '', true);
|
||||
});
|
||||
|
||||
/* ---------- 导入 ---------- */
|
||||
var fileInput = document.getElementById('amFile');
|
||||
document.getElementById('amImportBtn').addEventListener('click', function () { fileInput.click(); });
|
||||
@ -1483,6 +2005,8 @@
|
||||
render();
|
||||
// 平台 / 大类 的候选过去由 Blade 直接渲染,现在改成多选组件后统一由这里灌一次
|
||||
rebuildFilterOptions();
|
||||
selectView(INITIAL_VIEW, false);
|
||||
loadCoverage(coverageMonthEl ? coverageMonthEl.value : INITIAL_COVERAGE_MONTH, true, false);
|
||||
|
||||
// 后台预取账套科目清单(160KB 左右)。不做这一步的话,第一次点「编辑」要等它下载完
|
||||
// 才有反应,用户会以为按钮坏了。
|
||||
|
||||
@ -521,6 +521,7 @@ Route::prefix('workspace/financial-rules/account-mapping/actions')
|
||||
Route::patch('rules/{id}', [AccountMappingActions::class, 'update'])->whereNumber('id')->name('rules.update');
|
||||
Route::delete('rules/{id}', [AccountMappingActions::class, 'destroy'])->whereNumber('id')->name('rules.destroy');
|
||||
Route::get('accounts', [AccountMappingActions::class, 'accounts'])->name('accounts');
|
||||
Route::get('coverage', [AccountMappingActions::class, 'coverage'])->name('coverage');
|
||||
// 操作记录:新增 / 修改 / 删除 / 导入 / 重置 的历史,供页面「操作记录」查看
|
||||
Route::get('history', [AccountMappingActions::class, 'history'])->name('history');
|
||||
Route::get('history/export', [AccountMappingActions::class, 'historyExport'])->name('history.export');
|
||||
|
||||
@ -5,6 +5,8 @@ namespace Tests\Feature\Business;
|
||||
use App\Models\Auth\Permission;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Mockery;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingStore;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingValidator;
|
||||
use Tests\Feature\FeatureTestCase;
|
||||
@ -98,6 +100,12 @@ class AccountMappingPageTest extends FeatureTestCase
|
||||
->assertSee('var ROWS = [', false)
|
||||
->assertSee('"platform":"得物"', false)
|
||||
->assertSeeText('科目映射表')
|
||||
->assertSeeText('已配置规则')
|
||||
->assertSeeText('未映射账单项目')
|
||||
->assertSee('id="amCoveragePanel"', false)
|
||||
->assertSee('id="amCoverageMonth"', false)
|
||||
->assertSee('data-am-coverage-add', false)
|
||||
->assertSee('class="upstream-data-table am-coverage-table" data-finance-table-native', false)
|
||||
// 序号列表头固定为「序号」且宽度 3.5rem:2.5rem 时三位数会被省略号截成「1…」
|
||||
->assertSee('class="am-index" style="width:3.5rem;">序号</th>', false)
|
||||
// ENDPOINT 经 @json 输出,斜杠会被转义成 \/,所以只断言变量名
|
||||
@ -115,6 +123,50 @@ class AccountMappingPageTest extends FeatureTestCase
|
||||
->assertJsonStructure(['rules', 'summary', 'options' => ['platforms', 'categories', 'basis', 'invoices']]);
|
||||
}
|
||||
|
||||
public function test_coverage_endpoint_returns_unmapped_items_for_selected_month(): void
|
||||
{
|
||||
$this->grantAdminPermission();
|
||||
$coverage = Mockery::mock(AccountMappingCoverage::class);
|
||||
$coverage->shouldReceive('missingForMonth')->once()->with('2026-11', false)->andReturn([
|
||||
'status' => 'ready',
|
||||
'month' => '2026-11',
|
||||
'source_rows' => 120,
|
||||
'missing_item_count' => 1,
|
||||
'missing_row_count' => 7,
|
||||
'pending_sources' => [],
|
||||
'items' => [[
|
||||
'platform' => '抖音',
|
||||
'platform_label' => '抖音',
|
||||
'item' => '商家货款入账',
|
||||
'raw_items' => ['商家货款入账'],
|
||||
'source_rows' => 7,
|
||||
'store_count' => 3,
|
||||
'store_samples' => ['抖音-甲店'],
|
||||
'source_labels' => ['抖音'],
|
||||
]],
|
||||
'months' => ['2026-11', '2026-10'],
|
||||
]);
|
||||
$this->app->instance(AccountMappingCoverage::class, $coverage);
|
||||
|
||||
$this->loginAs()->getJson($this->actionUrl('coverage') . '?month=2026-11')
|
||||
->assertOk()
|
||||
->assertJsonPath('status', 'ready')
|
||||
->assertJsonPath('missing_item_count', 1)
|
||||
->assertJsonPath('items.0.platform', '抖音')
|
||||
->assertJsonPath('items.0.item', '商家货款入账')
|
||||
->assertJsonPath('items.0.source_rows', 7);
|
||||
}
|
||||
|
||||
public function test_coverage_endpoint_rejects_invalid_month(): void
|
||||
{
|
||||
$this->grantAdminPermission();
|
||||
$this->withExceptionHandling();
|
||||
|
||||
$this->loginAs()->getJson($this->actionUrl('coverage') . '?month=2026-13')
|
||||
->assertStatus(422)
|
||||
->assertJsonValidationErrors('month');
|
||||
}
|
||||
|
||||
public function test_can_create_update_and_delete_a_rule(): void
|
||||
{
|
||||
$this->grantAdminPermission();
|
||||
|
||||
@ -114,6 +114,12 @@ class BusinessMirrorScheduleTest extends TestCase
|
||||
$contents,
|
||||
$script,
|
||||
);
|
||||
$this->assertStringContainsString(
|
||||
'* * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-coverage.lock '
|
||||
. '/bin/sh /opt/caiwuxitong/run-finance-batch.sh account-mapping:refresh-coverage --pending --quiet',
|
||||
$contents,
|
||||
$script,
|
||||
);
|
||||
$this->assertStringContainsString(
|
||||
"40 6 * * 1 root /usr/bin/flock -w 3600 /run/caiwu-upstream-sync.lock /bin/sh -c '/usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-overlength --days=90 --quiet; /usr/bin/docker exec -u www-data caiwu_app php artisan courier-surcharge:pull-return --days=90 --quiet'",
|
||||
$contents,
|
||||
@ -209,6 +215,23 @@ class BusinessMirrorScheduleTest extends TestCase
|
||||
"pending_request=\"\$(find \"\$storage_root/app/ding-process-refresh\" -maxdepth 1 -type f -name '*.pending' -print -quit)\"",
|
||||
$contents,
|
||||
);
|
||||
$this->assertStringContainsString(
|
||||
"if [ \"\$1\" = 'account-mapping:refresh-coverage' ] && [ \"\${2:-}\" = '--pending' ]; then",
|
||||
$contents,
|
||||
);
|
||||
$this->assertStringContainsString(
|
||||
"find \"\$storage_root/app/account-mapping/coverage-requests\" -maxdepth 1 -type f -name '*.pending'",
|
||||
$contents,
|
||||
);
|
||||
$this->assertStringContainsString(
|
||||
"find \"\$storage_root/app/account-mapping/coverage-requests\" -maxdepth 1 -type f -name '*.running' -mmin +15",
|
||||
$contents,
|
||||
);
|
||||
$this->assertStringContainsString(
|
||||
'/usr/bin/timeout 1800 docker compose -f compose.jiangling.yml --profile batch run --rm -T --no-deps',
|
||||
$contents,
|
||||
);
|
||||
$this->assertStringContainsString('--name "$container_name" batch "$@"', $contents);
|
||||
}
|
||||
|
||||
public function test_release_scripts_install_supplier_statement_reminder_cron(): void
|
||||
|
||||
217
tests/Unit/EcommerceFinance/AccountMappingCoverageTest.php
Normal file
217
tests/Unit/EcommerceFinance/AccountMappingCoverageTest.php
Normal file
@ -0,0 +1,217 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\EcommerceFinance;
|
||||
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingCoverage;
|
||||
use Modules\EcommerceFinance\Services\AccountMappingStore;
|
||||
use Tests\TestCase;
|
||||
|
||||
class AccountMappingCoverageTest extends TestCase
|
||||
{
|
||||
private string $storageRoot = '';
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->storageRoot = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'account-mapping-coverage-' . uniqid();
|
||||
File::makeDirectory($this->storageRoot . '/app', 0777, true, true);
|
||||
$this->app->useStoragePath($this->storageRoot);
|
||||
|
||||
Cache::flush();
|
||||
$this->createBillMirrorSchema();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
if ($this->storageRoot !== '' && File::isDirectory($this->storageRoot)) {
|
||||
File::deleteDirectory($this->storageRoot);
|
||||
}
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
public function test_missing_items_follow_current_mapping_without_rescanning_source_rows(): void
|
||||
{
|
||||
$store = app(AccountMappingStore::class);
|
||||
$this->rule($store, '天猫', '交易收款');
|
||||
$this->rule($store, '天猫', '商户费');
|
||||
|
||||
$this->insertBill('taobao_alipay_bill_rows', 'occurred_at', [
|
||||
['store_name' => '天猫-测试店', 'bill_item' => '交易收款', 'day' => '2026-11-01 10:00:00'],
|
||||
['store_name' => '天猫-测试店', 'bill_item' => 'wx商户费', 'day' => '2026-11-01 10:01:00'],
|
||||
['store_name' => '天猫-测试店', 'bill_item' => '商家货款入账', 'day' => '2026-11-01 10:02:00'],
|
||||
['store_name' => '天猫-另一店', 'bill_item' => '商家货款入账', 'day' => '2026-11-02 10:02:00'],
|
||||
['store_name' => '天猫-测试店', 'bill_item' => '', 'day' => '2026-11-02 10:03:00'],
|
||||
['store_name' => '天猫-测试店', 'bill_item' => '上期项目', 'day' => '2026-10-31 23:59:59'],
|
||||
]);
|
||||
$this->insertBill('taobao_alipay_bill_rows', 'occurred_at', [
|
||||
['store_name' => '支付宝-测试店', 'bill_item' => '交易收款', 'day' => '2026-11-03 10:00:00'],
|
||||
['store_name' => '支付宝-测试店', 'bill_item' => '交易收款', 'day' => '2026-11-03 10:01:00'],
|
||||
['store_name' => '支付宝-测试店', 'bill_item' => '交易收款', 'day' => '2026-11-03 10:02:00'],
|
||||
]);
|
||||
|
||||
DB::connection('business_mirror')->table('jd_daily_bill_periods')->insert([
|
||||
'period_start' => '2026-11-01',
|
||||
'period_end' => '2026-11-30',
|
||||
'active_generation' => 'active-jd',
|
||||
'source_filename' => 'jd-2026-11.xlsx',
|
||||
'source_sha256' => str_repeat('a', 64),
|
||||
'row_count' => 2,
|
||||
'income' => 0,
|
||||
'expense' => 0,
|
||||
'imported_at' => '2026-12-01 10:00:00',
|
||||
]);
|
||||
$this->insertBill('jd_daily_bill_rows', 'occurred_at', [
|
||||
['store_name' => '京东-测试店', 'bill_item' => '未映射售后费', 'day' => '2026-11-04 10:00:00', 'generation' => 'active-jd'],
|
||||
['store_name' => '京东-测试店', 'bill_item' => '旧版本项目', 'day' => '2026-11-04 10:00:00', 'generation' => 'old-jd'],
|
||||
]);
|
||||
|
||||
$coverage = app(AccountMappingCoverage::class);
|
||||
$cold = $coverage->missingForMonth('2026-11');
|
||||
$this->assertSame('refreshing', $cold['status']);
|
||||
$this->assertSame(4, $cold['retry_after']);
|
||||
|
||||
$request = $coverage->claimPendingRefresh();
|
||||
$this->assertNotNull($request);
|
||||
$this->assertSame('2026-11', $request['month']);
|
||||
$this->assertFileExists($request['path']);
|
||||
$coverage->refreshForMonth($request['month']);
|
||||
$coverage->finishPendingRefresh($request['path'], true);
|
||||
$this->assertFileDoesNotExist($request['path']);
|
||||
$this->assertSame([], glob($coverage->requestDirectory() . '/*.pending') ?: []);
|
||||
$first = $coverage->missingForMonth('2026-11');
|
||||
|
||||
$this->assertSame('ready', $first['status']);
|
||||
$this->assertSame(9, $first['source_rows']);
|
||||
$this->assertSame(4, $first['missing_item_count']);
|
||||
$this->assertSame(7, $first['missing_row_count']);
|
||||
$this->assertSame([
|
||||
'交易收款|支付宝|3',
|
||||
'商家货款入账|天猫|2',
|
||||
'未映射售后费|京东|1',
|
||||
'(未填写账单项目)|天猫|1',
|
||||
], $this->missingSignature($first['items']));
|
||||
$this->assertNotContains('上期项目', array_column($first['items'], 'item'));
|
||||
$this->assertNotContains('wx商户费', array_column($first['items'], 'item'));
|
||||
|
||||
$this->rule($store, '天猫', '商家货款入账');
|
||||
$second = app(AccountMappingCoverage::class)->missingForMonth('2026-11');
|
||||
|
||||
$this->assertSame(3, $second['missing_item_count']);
|
||||
$this->assertSame(5, $second['missing_row_count']);
|
||||
$this->assertNotContains('商家货款入账', array_column($second['items'], 'item'));
|
||||
}
|
||||
|
||||
public function test_interrupted_refresh_request_is_recovered_after_stale_timeout(): void
|
||||
{
|
||||
$coverage = app(AccountMappingCoverage::class);
|
||||
$coverage->missingForMonth('2026-11');
|
||||
$claimed = $coverage->claimPendingRefresh();
|
||||
$this->assertNotNull($claimed);
|
||||
|
||||
touch($claimed['path'], now()->subMinutes(20)->getTimestamp());
|
||||
$recovered = $coverage->claimPendingRefresh();
|
||||
$this->assertNotNull($recovered);
|
||||
$this->assertSame('2026-11', $recovered['month']);
|
||||
$coverage->finishPendingRefresh($recovered['path'], true);
|
||||
}
|
||||
|
||||
private function rule(AccountMappingStore $store, string $platform, string $item): void
|
||||
{
|
||||
$store->create([
|
||||
'platform' => $platform,
|
||||
'item' => $item,
|
||||
'memo' => '',
|
||||
'goods' => '',
|
||||
'invoice' => '-',
|
||||
'category' => '收入',
|
||||
'dAcct' => '其他货币资金',
|
||||
'dSub' => '',
|
||||
'cAcct' => '主营业务收入',
|
||||
'cSub' => '',
|
||||
'basis' => '收入基准',
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $items @return list<string> */
|
||||
private function missingSignature(array $items): array
|
||||
{
|
||||
$rows = array_map(
|
||||
static fn (array $item): string => $item['item'] . '|' . $item['platform'] . '|' . $item['source_rows'],
|
||||
$items,
|
||||
);
|
||||
sort($rows);
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
private function insertBill(string $table, string $dateColumn, array $rows): void
|
||||
{
|
||||
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'];
|
||||
}
|
||||
DB::connection('business_mirror')->table($table)->insert($values);
|
||||
}
|
||||
}
|
||||
|
||||
private function createBillMirrorSchema(): void
|
||||
{
|
||||
$schema = Schema::connection('business_mirror');
|
||||
$sources = [
|
||||
'taobao_alipay_bill_rows' => ['date' => 'occurred_at', 'periods' => null],
|
||||
'taobao_wechat_bill_rows' => ['date' => 'occurred_at', 'periods' => null],
|
||||
'pdd_settlement_bill_rows' => ['date' => 'occurred_at', 'periods' => null],
|
||||
'jd_daily_bill_rows' => ['date' => 'occurred_at', 'periods' => 'jd_daily_bill_periods'],
|
||||
'jd_wallet_bill_rows' => ['date' => 'occurred_at', 'periods' => 'jd_wallet_bill_periods'],
|
||||
'douyin_authoritative_bills' => ['date' => 'occurred_at', 'periods' => 'douyin_authoritative_periods'],
|
||||
'dewu_settlement_bill_rows' => ['date' => 'bill_date', 'periods' => null],
|
||||
];
|
||||
|
||||
foreach ($sources as $table => $definition) {
|
||||
if (! $schema->hasTable($table)) {
|
||||
$schema->create($table, function ($blueprint) use ($definition): void {
|
||||
$blueprint->increments('id');
|
||||
$blueprint->string('store_name')->nullable();
|
||||
$blueprint->string('bill_item')->nullable();
|
||||
if ($definition['date'] === 'bill_date') {
|
||||
$blueprint->date($definition['date']);
|
||||
} else {
|
||||
$blueprint->dateTime($definition['date']);
|
||||
}
|
||||
if ($definition['periods'] !== null) {
|
||||
$blueprint->string('generation')->nullable();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$periods = $definition['periods'];
|
||||
if ($periods !== null && ! $schema->hasTable($periods)) {
|
||||
$schema->create($periods, function ($blueprint): void {
|
||||
$blueprint->increments('id');
|
||||
$blueprint->date('period_start');
|
||||
$blueprint->date('period_end');
|
||||
$blueprint->string('active_generation')->nullable();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user