authoringProjection = new UserCopyAuthoringProjection($manifest); } /** * @param array $query * @return array */ public function workspace(array $query = []): array { $allEntryRows = $this->database->table('ui_copy_entries') ->where('state', 'active') ->orderBy('copy_key') ->get() ->all(); $authoring = $this->authoringProjection->project( $query, $allEntryRows ); $pages = $authoring['pages']; $groups = $authoring['groups']; $selectedPage = $authoring['selected_page']; $channel = $authoring['channel']; $selectedGroup = $authoring['selected_group']; $entryRows = $authoring['entry_rows']; $manifestByKey = $authoring['metadata_by_key']; $catalogQuery = $this->catalogQuery($query); $localeRows = $this->database->table('ui_copy_locales') ->whereNull('source_claim') ->orderByDesc('enabled') ->orderBy('locale') ->get() ->all(); $locales = array_map( fn ($row): array => $this->localeDto($row), $localeRows ); $selectedLocale = isset($query['locale']) && is_string($query['locale']) && trim($query['locale']) !== '' ? $this->normalizeLocale($query['locale']) : (string) ($locales[0]['locale'] ?? ''); $selectedLocaleRow = null; foreach ($localeRows as $row) { if ((string) $row->locale === $selectedLocale) { $selectedLocaleRow = $row; break; } } $allEntries = []; foreach ($allEntryRows as $entry) { $allEntries[(string) $entry->copy_key] = $entry; } $projectionReady = true; try { $this->projectionGuard->assertReady($allEntries); } catch (UserCopyAdminException) { $projectionReady = false; } $publicationReadiness = $this->publicationReadiness( $selectedLocaleRow, $projectionReady ); $entriesByKey = []; foreach ($entryRows as $entry) { $entriesByKey[(string) $entry->copy_key] = $entry; } $drafts = []; $publishedItems = []; $currentGeneration = null; $entryIds = array_map( static fn ($entry): int => (int) $entry->id, $entryRows ); if ($selectedLocaleRow !== null) { if ($entryIds !== []) { foreach ($this->database->table('ui_copy_drafts') ->where('locale_id', (int) $selectedLocaleRow->id) ->whereIn('entry_id', $entryIds) ->get()->all() as $draft) { $drafts[(int) $draft->entry_id] = $draft; } } $current = $this->store->current(); $candidate = $current['locales'][$selectedLocale]['generation'] ?? null; if (is_string($candidate)) { $currentGeneration = $candidate; $publication = $this->database->table('ui_copy_publications') ->where('locale_id', (int) $selectedLocaleRow->id) ->where('catalog_generation', $candidate) ->where('state', 'ready') ->first(); if ($publication !== null && $entryIds !== []) { foreach ($this->database->table('ui_copy_revision_items') ->where('publication_id', (int) $publication->id) ->whereIn('entry_id', $entryIds) ->get()->all() as $item) { $publishedItems[(int) $item->entry_id] = [ 'text' => (string) $item->published_text, 'visibility' => (string) $item->visibility, 'version' => (int) $publication->revision, 'publication_key' => (string) $publication->publication_key, 'translated' => $item->draft_version !== null, ]; } } } } $catalogEntries = []; $coverage = [ 'total' => count($entryRows), 'published' => 0, 'draft' => 0, 'missing' => 0, 'percent' => 0, ]; foreach ($entriesByKey as $copyKey => $entry) { $draft = $drafts[(int) $entry->id] ?? null; $published = $publishedItems[(int) $entry->id] ?? null; $isPublished = is_array($published) && ($published['translated'] ?? false) === true; $state = $isPublished ? 'published' : ($draft !== null ? 'draft' : 'untranslated'); $coverage[$state === 'untranslated' ? 'missing' : $state]++; $contract = json_decode( (string) $entry->placeholder_contract_json, true ); $draftDto = $draft === null ? null : $this->draftDto($draft); $manifestEntry = $manifestByKey[$copyKey] ?? []; $hidden = $draft !== null ? (string) $draft->visibility === 'hidden' : (($published['visibility'] ?? 'visible') === 'hidden'); $catalogEntries[] = [ 'key' => $copyKey, 'scope' => (string) $entry->scope, 'page' => (string) $entry->page_key, 'kind' => (string) $entry->kind, 'format' => (string) $entry->format, 'criticality' => (string) $entry->criticality, 'required' => (bool) $entry->required, 'allow_hide' => (bool) $entry->allow_hide, 'max_length' => (int) $entry->max_length, 'source' => (string) $entry->source_text_zh, 'parameters' => is_array($contract) ? array_keys($contract) : [], 'severity' => is_string($manifestEntry['toast_tone'] ?? null) ? $manifestEntry['toast_tone'] : 'info', 'editor_surface' => is_string( $manifestEntry['editor_surface'] ?? null ) ? $manifestEntry['editor_surface'] : null, 'editor_group' => is_string( $manifestEntry['editor_group'] ?? null ) ? $manifestEntry['editor_group'] : null, 'state' => $state, 'hidden' => $hidden, 'draft_version' => $draftDto['version'] ?? 0, 'draft' => $draftDto, 'published' => $published, ]; } if ($coverage['total'] > 0) { $coverage['percent'] = round( ($coverage['published'] / $coverage['total']) * 100, 2 ); } $filteredEntries = array_values(array_filter( $catalogEntries, static function (array $entry) use ($catalogQuery): bool { if ($catalogQuery['surface'] !== '' && $entry['editor_surface'] !== $catalogQuery['surface']) { return false; } $effectiveState = $entry['hidden'] === true ? 'hidden' : $entry['state']; if ($catalogQuery['state'] !== '' && $effectiveState !== $catalogQuery['state']) { return false; } if ($catalogQuery['term'] === '') { return true; } return str_contains( mb_strtolower((string) $entry['key']), $catalogQuery['term'] ) || str_contains( mb_strtolower((string) $entry['source']), $catalogQuery['term'] ); } )); usort( $filteredEntries, static fn (array $left, array $right): int => strcmp( (string) $left['key'], (string) $right['key'] ) ); $filteredTotal = count($filteredEntries); $totalPages = max( 1, (int) ceil($filteredTotal / $catalogQuery['per_page']) ); $entries = array_slice( $filteredEntries, ($catalogQuery['page'] - 1) * $catalogQuery['per_page'], $catalogQuery['per_page'] ); $pagination = [ 'page' => $catalogQuery['page'], 'per_page' => $catalogQuery['per_page'], 'total' => $filteredTotal, 'total_pages' => $totalPages, 'has_more' => $catalogQuery['page'] < $totalPages, ]; $writeReady = $projectionReady && $selectedLocaleRow !== null && (int) $selectedLocaleRow->enabled === 1; $writeBlockReason = ''; if (!$projectionReady) { $writeBlockReason = 'Manifest 尚未同步,当前仅可查看。'; } elseif ($selectedLocaleRow === null) { $writeBlockReason = '目标语言尚未登记。'; } elseif ((int) $selectedLocaleRow->enabled !== 1) { $writeBlockReason = '目标语言已停用。'; } return [ 'schema' => 1, 'pages' => $pages, 'groups' => $groups, 'locales' => array_map(static fn (array $locale): array => [ 'id' => $locale['locale'], 'label' => $locale['display_name'], 'enabled' => $locale['enabled'], ], $locales), 'selected' => [ 'page' => $selectedPage, 'locale' => $selectedLocale, ], 'authoring' => [ 'channel' => $channel, 'group' => $selectedGroup, ], 'coverage' => $coverage, 'publication_readiness' => $publicationReadiness, 'entries' => $entries, 'pagination' => $pagination, 'current_generation' => $currentGeneration, 'write_ready' => $writeReady, 'write_block_reason' => $writeBlockReason, ]; } /** * @param array $query * @return array{ * page:int, * per_page:int, * term:string, * surface:string, * state:string * } */ private function catalogQuery(array $query): array { $page = $this->positiveQueryInteger($query, 'catalog_page', 1); $perPage = $this->positiveQueryInteger($query, 'per_page', 50); if ($perPage > 100) { throw new UserCopyAdminException('per_page 参数无效。'); } $term = ''; if (array_key_exists('q', $query)) { if (!is_string($query['q'])) { throw new UserCopyAdminException('文案搜索条件无效。'); } $term = mb_strtolower(trim($query['q'])); } return [ 'page' => $page, 'per_page' => $perPage, 'term' => $term, 'surface' => $this->enumQuery( $query, 'surface', ['page', 'shared', 'admin', 'dialog', 'feedback', 'task', 'accessibility'], '文案类型无效。' ), 'state' => $this->enumQuery( $query, 'state', ['published', 'draft', 'untranslated', 'hidden'], '文案状态无效。' ), ]; } /** @param array $query */ private function positiveQueryInteger( array $query, string $name, int $default ): int { if (!array_key_exists($name, $query) || $query[$name] === '') { return $default; } $value = $query[$name]; if ((!is_int($value) && !is_string($value)) || preg_match('/\A[1-9][0-9]{0,8}\z/D', (string) $value) !== 1) { throw new UserCopyAdminException($name . ' 参数无效。'); } return (int) $value; } /** * @param array $query * @param list $allowed */ private function enumQuery( array $query, string $name, array $allowed, string $message ): string { if (!array_key_exists($name, $query) || $query[$name] === '') { return ''; } if (!is_string($query[$name])) { throw new UserCopyAdminException($message); } $value = trim($query[$name]); if ($value === '') { return ''; } if (!in_array($value, $allowed, true)) { throw new UserCopyAdminException($message); } return $value; } /** * Publication readiness is locale-wide and deliberately independent of * the currently selected authoring channel, group and search term. * Missing drafts fall back to source copy at publish time and do not * block publication. * * @return array{ * ready:bool, * projection_ready:bool, * locale_enabled:bool, * blocking_draft_count:int, * invalid_draft_count:int, * stale_draft_count:int, * pending_draft_count:int, * first_errors:list * }> * } */ private function publicationReadiness( ?object $localeRow, bool $projectionReady ): array { $localeEnabled = $localeRow !== null && (int) $localeRow->enabled === 1; $counts = [ 'invalid' => 0, 'stale' => 0, 'pending' => 0, ]; $firstErrors = []; if ($localeRow !== null) { $draftRows = $this->database->table('ui_copy_drafts as draft') ->join( 'ui_copy_entries as entry', 'entry.id', '=', 'draft.entry_id' ) ->where('draft.locale_id', (int) $localeRow->id) ->where('entry.state', 'active') ->orderBy('entry.copy_key') ->get([ 'entry.copy_key', 'entry.source_hash_zh', 'entry.placeholder_hash', 'draft.validation_state', 'draft.validation_errors_json', 'draft.translated_source_hash_zh', 'draft.translated_placeholder_hash', ])->all(); foreach ($draftRows as $draft) { $contractCurrent = hash_equals( (string) $draft->source_hash_zh, (string) $draft->translated_source_hash_zh ) && hash_equals( (string) $draft->placeholder_hash, (string) $draft->translated_placeholder_hash ); $validationState = (string) $draft->validation_state; $errors = $this->readinessErrors( (string) $draft->validation_errors_json ); if (!$contractCurrent) { $validationState = 'stale'; $errors = ['source_contract_changed']; } elseif ($validationState === 'valid') { continue; } elseif (!isset($counts[$validationState])) { $validationState = 'invalid'; $errors = ['validation_state_unknown']; } $counts[$validationState]++; if (count($firstErrors) < 5) { $firstErrors[] = [ 'key' => (string) $draft->copy_key, 'validation_state' => $validationState, 'errors' => $errors, ]; } } } $blockingDraftCount = $counts['invalid'] + $counts['stale'] + $counts['pending']; return [ 'ready' => $projectionReady && $localeEnabled && $blockingDraftCount === 0, 'projection_ready' => $projectionReady, 'locale_enabled' => $localeEnabled, 'blocking_draft_count' => $blockingDraftCount, 'invalid_draft_count' => $counts['invalid'], 'stale_draft_count' => $counts['stale'], 'pending_draft_count' => $counts['pending'], 'first_errors' => $firstErrors, ]; } /** @return list */ private function readinessErrors(string $encoded): array { try { $errors = json_decode( $encoded, true, 32, JSON_THROW_ON_ERROR ); } catch (\JsonException) { return ['validation_result_corrupt']; } if (!is_array($errors)) { return ['validation_result_corrupt']; } return array_values(array_filter( $errors, static fn ($error): bool => is_string($error) )); } /** @return array */ public function history( string $localeOrCopyKey, ?string $legacyLocale = null ): array { $copyKey = $legacyLocale === null ? null : $localeOrCopyKey; $locale = $legacyLocale ?? $localeOrCopyKey; $locale = $this->normalizeLocale($locale); $localeRow = $this->database->table('ui_copy_locales') ->where('locale', $locale) ->whereNull('source_claim') ->first(); if ($localeRow === null) { return [ 'locale' => $locale, 'revisions' => [], ]; } if ($copyKey === null) { $rows = $this->database->table('ui_copy_publications') ->where('locale_id', (int) $localeRow->id) ->where('state', 'ready') ->orderByDesc('revision') ->get()->all(); $revisions = array_map(static fn ($row): array => [ 'id' => (string) $row->publication_key, 'publication_key' => (string) $row->publication_key, 'version' => (int) $row->revision, 'generation' => (string) $row->catalog_generation, 'entry_count' => (int) $row->entry_count, 'published_at' => (int) $row->published_at > 0 ? gmdate('c', (int) $row->published_at) : null, ], $rows); return [ 'locale' => $locale, 'revisions' => $revisions, ]; } $entry = $this->database->table('ui_copy_entries') ->where('copy_key', $copyKey) ->first(); if ($entry === null) { return [ 'key' => $copyKey, 'locale' => $locale, 'revisions' => [], ]; } $rows = $this->database->table('ui_copy_revision_items as item') ->join('ui_copy_publications as publication', 'publication.id', '=', 'item.publication_id') ->where('item.entry_id', (int) $entry->id) ->where('publication.locale_id', (int) $localeRow->id) ->where('publication.state', 'ready') ->orderByDesc('publication.revision') ->get([ 'publication.publication_key', 'publication.revision', 'publication.published_at', 'item.published_text', 'item.visibility', 'item.draft_version', ])->all(); $revisions = array_map(static fn ($row): array => [ 'id' => (string) $row->publication_key, 'publication_key' => (string) $row->publication_key, 'version' => (int) $row->revision, 'published_at' => (int) $row->published_at > 0 ? gmdate('c', (int) $row->published_at) : null, 'text' => (string) $row->published_text, 'hidden' => (string) $row->visibility === 'hidden', 'draft_version' => $row->draft_version === null ? null : (int) $row->draft_version, ], $rows); return [ 'key' => $copyKey, 'locale' => $locale, 'revisions' => $revisions, ]; } private function normalizeLocale(string $locale): string { $normalized = LocaleCode::canonicalize($locale); if ($normalized === null) { throw new UserCopyAdminException('语言代码无效。', 400); } return $normalized; } /** @return array */ private function localeDto(?object $row): array { if ($row === null) { throw new UserCopyAdminException('语言保存结果不存在。', 500); } return [ 'id' => (int) $row->id, 'locale' => (string) $row->locale, 'display_name' => (string) $row->display_name, 'enabled' => (bool) $row->enabled, 'source' => $row->source_claim !== null, ]; } /** @return array */ private function draftDto(?object $row): array { if ($row === null) { throw new UserCopyAdminException('草稿保存结果不存在。', 500); } try { $errors = json_decode( (string) $row->validation_errors_json, true, 32, JSON_THROW_ON_ERROR ); } catch (\JsonException) { $errors = ['validation_result_corrupt']; } return [ 'id' => (int) $row->id, 'entry_id' => (int) $row->entry_id, 'locale_id' => (int) $row->locale_id, 'text' => (string) $row->draft_text, 'visibility' => (string) $row->visibility, 'version' => (int) $row->draft_version, 'validation_state' => (string) $row->validation_state, 'validation_errors' => is_array($errors) ? $errors : [], ]; } }