diff --git a/app/Console/Commands/RefreshAccountMappingCoverage.php b/app/Console/Commands/RefreshAccountMappingCoverage.php new file mode 100644 index 000000000..6a962f539 --- /dev/null +++ b/app/Console/Commands/RefreshAccountMappingCoverage.php @@ -0,0 +1,73 @@ +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; + } + } +} diff --git a/app/Http/Controllers/Business/AccountMappingActions.php b/app/Http/Controllers/Business/AccountMappingActions.php index e30914462..425b713e5 100644 --- a/app/Http/Controllers/Business/AccountMappingActions.php +++ b/app/Http/Controllers/Business/AccountMappingActions.php @@ -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); diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index b2218f4ea..6be7d2e0f 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -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 天,避免三天前的数据长期未刷新。 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index 4b380ebb4..70c3dd9ba 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -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 天,避免三天前的数据长期未刷新。 diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index d2b81db3c..f13d5a3b5 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -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 "$@" diff --git a/modules/EcommerceFinance/Services/AccountMappingCoverage.php b/modules/EcommerceFinance/Services/AccountMappingCoverage.php new file mode 100644 index 000000000..6e341e5ef --- /dev/null +++ b/modules/EcommerceFinance/Services/AccountMappingCoverage.php @@ -0,0 +1,603 @@ + ['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> */ + 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 */ + 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, + * items:list>, + * months:list + * } + */ + 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,pairs:list>} + */ + 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,pairs:list>} $raw + * @return array + */ + 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 */ + 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, + * pairs:list> + * } + */ + 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 */ + 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 */ + 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; + } + } +} diff --git a/resources/views/business/pages/financial-rules/account-mapping.blade.php b/resources/views/business/pages/financial-rules/account-mapping.blade.php index 6dffa282c..44d0f209d 100644 --- a/resources/views/business/pages/financial-rules/account-mapping.blade.php +++ b/resources/views/business/pages/financial-rules/account-mapping.blade.php @@ -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 @@
· 同一个账单项目在业务上不是同一件事时,用财务备注/商品名称关键词区分:财务备注匹配账单的二次备注、账务备注等(202607订单 这类月份式备注不参与匹配),商品名称按包含匹配;两个都填最优先,其次商品名称,再次财务备注,都不填就是兜底规则。
- 点行展开看两种收支下的最终分录与校验结果;点「编辑」可直接改这一行;有新增账单项目时用「导入」追加。 + 点行展开看两种收支下的最终分录与校验结果;点「编辑」可直接改这一行。新增账单项目先去「未映射账单项目」核对,再点「补映射」填写规则。 @if ($amError)
读取映射表失败:{{ $amError }}
@endif + + + + +