You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/UserCopy/UserCopyWorkspaceReader.php

386 lines
14 KiB
PHP

<?php
namespace App\Services\UserCopy;
use Illuminate\Database\ConnectionInterface;
/**
* Read model for user-copy authoring workspaces and publication history.
*
* The interface stays small while database hydration, authoring projection,
* coverage and final DTO assembly remain local to this module.
*/
final class UserCopyWorkspaceReader
{
private readonly UserCopyAuthoringProjection $authoringProjection;
public function __construct(
private readonly ConnectionInterface $database,
array $manifest,
private readonly UserCopyPublicationStore $store,
private readonly UserCopyManifestProjectionGuard $projectionGuard
) {
$this->authoringProjection = new UserCopyAuthoringProjection($manifest);
}
/**
* @param array<string,mixed> $query
* @return array<string,mixed>
*/
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'];
$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;
}
$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,
];
}
}
}
}
$entries = [];
$coverage = [
'total' => count($entryRows),
'published' => 0,
'draft' => 0,
'missing' => 0,
'percent' => 0,
];
$term = isset($query['q']) && is_string($query['q'])
? mb_strtolower(trim($query['q'])) : '';
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]++;
if ($term !== ''
&& !str_contains(mb_strtolower($copyKey), $term)
&& !str_contains(
mb_strtolower((string) $entry->source_text_zh),
$term
)) {
continue;
}
$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');
$entries[] = [
'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
);
}
$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,
'entries' => $entries,
'current_generation' => $currentGeneration,
'write_ready' => $writeReady,
'write_block_reason' => $writeBlockReason,
];
}
/** @return array<string,mixed> */
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
{
$locale = str_replace('_', '-', trim($locale));
if (preg_match(
'/\A[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*\z/D',
$locale
) !== 1) {
throw new UserCopyAdminException('语言代码无效。', 400);
}
$parts = explode('-', $locale);
$parts[0] = strtolower($parts[0]);
for ($index = 1; $index < count($parts); $index++) {
$parts[$index] = strlen($parts[$index]) === 2
? strtoupper($parts[$index]) : $parts[$index];
}
return implode('-', $parts);
}
/** @return array<string,mixed> */
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<string,mixed> */
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 : [],
];
}
}