connection = $databases->connection( (string) config('upstream_mirrors.connection', 'business_mirror'), ); } /** * @param list|null $storeNames * @return array{ * checked:int,resolved:int,pending:int,alerted:int,dry_run:bool, * months:list,issues:list * } */ public function resolve(?array $storeNames = null, bool $dryRun = false): array { if (! $this->openingBalances->available()) { return $this->result(0, 0, 0, 0, $dryRun, [], []); } $normalizedNames = $storeNames === null ? null : array_values(array_unique(array_filter(array_map( static fn (mixed $name): string => JushuitanShopBalanceRepository::normalizeStoreName( trim((string) $name), ), $storeNames, )))); if ($normalizedNames === []) { return $this->result(0, 0, 0, 0, $dryRun, [], []); } $query = $this->connection->table(PinduoduoOpeningBalanceService::TASK_TABLE) ->where('status', 'pending') ->orderBy('first_bill_month') ->orderBy('store_name'); if ($normalizedNames !== null) { $query->whereIn('normalized_store_name', $normalizedNames); } $tasks = $query->get() ->keyBy('normalized_store_name'); if ($tasks->isEmpty()) { return $this->result(0, 0, 0, 0, $dryRun, [], []); } $issues = []; $alertIssues = []; $resolvedNames = []; $attemptRows = []; $months = $tasks ->groupBy(static fn (object $task): string => substr((string) $task->first_bill_month, 0, 7)) ->sortKeys(); foreach ($months as $period => $monthTasks) { try { $sourceRows = $this->source->fetchMonth((string) $period); $sourceError = null; } catch (Throwable $exception) { $sourceRows = []; $sourceError = $exception->getMessage(); } $rowsByStore = []; foreach ($sourceRows as $row) { $normalized = JushuitanShopBalanceRepository::normalizeStoreName( (string) ($row['shopName'] ?? ''), ); if ($normalized !== '') { $rowsByStore[$normalized][] = $row; } } foreach ($monthTasks as $task) { $normalized = (string) $task->normalized_store_name; $matches = $rowsByStore[$normalized] ?? []; if ($sourceError !== null) { $reason = '聚水潭平台资金账户余额读取失败:' . mb_substr($sourceError, 0, 300); } elseif ($matches === []) { $reason = '聚水潭没有该店铺当月平台资金账户余额。'; } elseif (count($matches) !== 1) { $reason = '聚水潭匹配到多个同名店铺,不能自动写入。'; } else { $sourceRow = $matches[0]; $reason = $this->validateSourceRow($sourceRow); } if ($reason === null) { $resolvedNames[] = (string) $task->store_name; $attemptRows[] = [ 'task' => $task, 'period' => (string) $period, 'source' => $matches[0], 'status' => 'resolved', 'message' => null, ]; continue; } $attemptRows[] = [ 'task' => $task, 'period' => (string) $period, 'source' => null, 'status' => 'pending', 'message' => $reason, 'signature' => hash('sha256', $reason), 'needs_alert' => ! hash_equals( (string) ($task->alert_signature ?? ''), hash('sha256', $reason), ), ]; $issues[] = [ 'store_name' => (string) $task->store_name, 'month' => (string) $period, 'reason' => $reason, ]; if ($attemptRows[array_key_last($attemptRows)]['needs_alert']) { $alertIssues[] = end($issues); } } } $resolved = count($resolvedNames); $pending = count($issues); $alerted = 0; if (! $dryRun && $attemptRows !== []) { $now = now(); $this->connection->transaction(function () use ($attemptRows, $now): void { foreach ($attemptRows as $attempt) { if ($attempt['status'] === 'resolved') { $this->writeResolved((string) $attempt['period'], $attempt['source'], $now); } $this->connection->table(PinduoduoOpeningBalanceService::TASK_TABLE) ->where('id', $attempt['task']->id) ->update([ 'resolution_status' => $attempt['status'] === 'resolved' ? 'resolved' : 'failed', 'resolution_message' => $attempt['message'], 'resolution_checked_at' => $now, 'alert_signature' => $attempt['status'] === 'resolved' ? null : (string) $attempt['task']->alert_signature, 'alerted_at' => $attempt['status'] === 'resolved' ? null : $attempt['task']->alerted_at, 'updated_at' => $now, ]); } }); if ($alertIssues !== []) { try { $alerted = $this->alerts->send($alertIssues); } catch (Throwable $exception) { report($exception); } if ($alerted > 0) { $now = now(); foreach ($attemptRows as $attempt) { if ($attempt['status'] !== 'pending' || ! $attempt['needs_alert']) { continue; } $this->connection->table(PinduoduoOpeningBalanceService::TASK_TABLE) ->where('id', $attempt['task']->id) ->update([ 'alert_signature' => $attempt['signature'], 'alerted_at' => $now, 'updated_at' => $now, ]); } } } $this->openingBalances->syncPendingStores(array_map( static fn (array $attempt): string => (string) $attempt['task']->store_name, $attemptRows, )); $this->openingBalances->invalidateBalanceCache(); } return $this->result( $tasks->count(), $resolved, $pending, $alerted, $dryRun, array_keys($months->all()), $issues, ); } /** @param array $row */ private function validateSourceRow(array $row): ?string { if (($row['haveOpeningBalance'] ?? false) !== true) { return '聚水潭平台资金账户余额没有可用的期初余额。'; } if (($row['haveEndingBalanceRpa'] ?? false) !== true) { return '聚水潭平台资金账户余额没有可用的平台实际期末余额。'; } foreach (['openingBalance', 'currentIncome', 'currentExpenditure', 'endingBalanceRpa'] as $field) { if (! is_numeric($row[$field] ?? null)) { return '聚水潭平台资金账户余额金额字段无效。'; } } $openingCents = $this->cents($row['openingBalance']); $incomeCents = $this->cents($row['currentIncome']); $expenseCents = $this->cents($row['currentExpenditure']); $actualEndingCents = $this->cents($row['endingBalanceRpa']); if ($openingCents + $incomeCents - $expenseCents !== $actualEndingCents) { return sprintf( '余额校验不一致:期初 %.2f + 本期收入 %.2f - 本期支出 %.2f 不等于平台实际期末 %.2f。', $openingCents / 100, $incomeCents / 100, $expenseCents / 100, $actualEndingCents / 100, ); } return null; } /** @param array $row */ private function writeResolved(string $period, array $row, mixed $now): void { $storeName = trim((string) $row['shopName']); $normalized = JushuitanShopBalanceRepository::normalizeStoreName($storeName); $periodEnd = CarbonImmutable::createFromFormat('!Y-m-d', $period . '-01') ->endOfMonth() ->format('Y-m-d'); $openingMonth = $period . '-01'; $sourceName = '聚水潭平台资金账户余额自动读取_' . $period; $sourceHash = hash('sha256', json_encode($row, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)); $opening = number_format((float) $row['openingBalance'], 6, '.', ''); $ending = number_format((float) $row['endingBalanceRpa'], 6, '.', ''); $this->connection->table(PinduoduoPlatformBalanceImporter::TABLE)->upsert([[ 'store_name' => $storeName, 'normalized_store_name' => $normalized, 'account_name' => mb_substr(trim((string) ($row['groupName'] ?? '拼多多货款账户')), 0, 255), 'balance' => $ending, 'period_end' => $periodEnd, 'source_filename' => $sourceName, 'source_sha256' => $sourceHash, 'imported_at' => $now, 'created_at' => $now, 'updated_at' => $now, ]], ['period_end', 'normalized_store_name'], [ 'store_name', 'account_name', 'balance', 'source_filename', 'source_sha256', 'imported_at', 'updated_at', ]); $this->connection->table(PinduoduoOpeningBalanceService::OPENING_TABLE)->upsert([[ 'opening_month' => $openingMonth, 'store_name' => $storeName, 'normalized_store_name' => $normalized, 'opening_balance' => $opening, 'source_type' => 'jushuitan_platform_balance', 'source_filename' => $sourceName, 'source_sha256' => $sourceHash, 'imported_at' => $now, 'created_at' => $now, 'updated_at' => $now, ]], ['opening_month', 'normalized_store_name'], [ 'store_name', 'opening_balance', 'source_type', 'source_filename', 'source_sha256', 'imported_at', 'updated_at', ]); } private function cents(mixed $value): int { return (int) round((float) $value * 100); } /** * @param list $months * @param list $issues * @return array{checked:int,resolved:int,pending:int,alerted:int,dry_run:bool,months:list,issues:list} */ private function result( int $checked, int $resolved, int $pending, int $alerted, bool $dryRun, array $months, array $issues, ): array { return compact('checked', 'resolved', 'pending', 'alerted', 'months', 'issues') + [ 'dry_run' => $dryRun, ]; } }