Browse Source

Merge pull request #2508 from visuddhinanda/development

Development
visuddhinanda 22 hours ago
parent
commit
458327e597

+ 1 - 1
api-v13/app/Http/Resources/V3/TermResource.php

@@ -68,7 +68,7 @@ class TermResource extends BaseResource
             'meaning' => (string) $this->meaning,
             'other_meaning' => $this->other_meaning,
             'language' => (string) $this->language,
-            'channel_id' => $this->channal,
+            'channel_id' => $this->channelUid(),
             'channel' => $this->channel ? ['id' => (string) $this->channel->uid, 'name' => (string) $this->channel->name] : null,
             'owner_id' => (string) $this->owner,
             'quality' => $this->quality,

+ 22 - 0
api-v13/app/Models/DhammaTerm.php

@@ -2,6 +2,7 @@
 
 namespace App\Models;
 
+use Illuminate\Contracts\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Factories\HasFactory;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -52,6 +53,27 @@ class DhammaTerm extends Model
         return $this->belongsTo(Channel::class, 'channal', 'uid');
     }
 
+    /**
+     * 所属 channel 的 uid;studio 级术语给 null。
+     *
+     * studio 级术语的 channal 有两种写法:NULL,以及 2022 年以前 v2 写入的空串(库里一千多条),
+     * 判断「是不是 studio 级」一律走这里,不要直接比 `channal !== null`。
+     */
+    public function channelUid(): ?string
+    {
+        return $this->channal === null || $this->channal === '' ? null : (string) $this->channal;
+    }
+
+    /**
+     * 只要 studio 级术语(channal 为 NULL 或空串,见 {@see self::channelUid()})。
+     *
+     * @param  Builder<DhammaTerm>  $query
+     */
+    public function scopeStudioLevel(Builder $query): void
+    {
+        $query->where(fn (Builder $q) => $q->whereNull('channal')->orWhere('channal', ''));
+    }
+
     /** 编辑者(人类用户)。editor_uid 对 user_infos.userid */
     public function user(): BelongsTo
     {

+ 6 - 1
api-v13/app/Services/Markup/Templates/TermTemplate.php

@@ -122,7 +122,12 @@ final class TermTemplate extends Template
     public function html(Call $call, RenderContext $ctx): string
     {
         $props = $this->props($call, $ctx);
-        $class = isset($props['id']) ? 'term-ref' : 'term-ref term_invalid';
+        // 与 v6 术语组件的三种状态对应:没找到(红)、取自社区术语(绿)、找到(蓝)
+        $class = match (true) {
+            ! isset($props['id']) => 'term-ref term_invalid',
+            ! empty($props['isCommunity']) => 'term-ref term_community',
+            default => 'term-ref',
+        };
 
         return '<span class="'.$class.'" data-id="'.e($props['id'] ?? '').'" data-term="'.e($props['word']).'">'
             .e($props['meaning'] ?? $props['word']).'</span>';

+ 1 - 1
api-v13/app/Services/V3/TermExchangeService.php

@@ -136,7 +136,7 @@ class TermExchangeService
                 }
 
                 return [
-                    'scope' => DhammaTerm::query()->where('owner', $studioUid)->whereNull('channal')->where('language', $language),
+                    'scope' => DhammaTerm::query()->where('owner', $studioUid)->studioLevel()->where('language', $language),
                     'target' => ['channel' => null, 'owner' => $studioUid, 'language' => $language],
                     'language_editable' => true,
                 ];

+ 33 - 13
api-v13/app/Services/V3/TermService.php

@@ -17,6 +17,7 @@ use App\Tools\Tools;
 use Illuminate\Auth\Access\AuthorizationException;
 use Illuminate\Contracts\Pagination\LengthAwarePaginator;
 use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Eloquent\Collection as EloquentCollection;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
@@ -80,7 +81,7 @@ class TermService
         if (! $abilities['read']) {
             throw new AuthorizationException(__('messages.term_forbidden'));
         }
-        $term->load($this->relations());
+        $this->loadRelations(new EloquentCollection([$term]));
         $this->decorate(collect([$term]), $viewerUid, withBody: true, render: [
             'channels' => $this->readableChannels($render['channels'] ?? [], $viewerUid),
             'mode' => $render['mode'] ?? 'read',
@@ -164,7 +165,7 @@ class TermService
         }
         $query = DhammaTerm::query()->where('owner', $studioUid);
         if (! empty($filters['general'])) {
-            $query->whereNull('channal');
+            $query->studioLevel();
         }
 
         return $query;
@@ -207,7 +208,7 @@ class TermService
         }
         // 看得见的:studio 级术语,或所在 channel 会被列出给查看者
         $query->where(function (Builder $q) use ($viewerUid) {
-            $q->whereNull('channal')->orWhereIn('channal', function ($sub) use ($viewerUid) {
+            $q->studioLevel()->orWhereIn('channal', function ($sub) use ($viewerUid) {
                 $sub->selectRaw('uid::text')->from('channels')->whereNull('deleted_at');
                 $this->channels->scopeListable($sub, $viewerUid);
             });
@@ -257,7 +258,7 @@ class TermService
             throw new AuthorizationException(__('messages.term_forbidden'));
         }
         $this->guardUnique(
-            DhammaTerm::query()->where('owner', $studioUid)->whereNull('channal')->where('language', $data['language']),
+            DhammaTerm::query()->where('owner', $studioUid)->studioLevel()->where('language', $data['language']),
             $data,
         );
 
@@ -276,13 +277,13 @@ class TermService
      */
     public function update(DhammaTerm $term, array $actor, array $data, ?string $ifMatch): DhammaTerm
     {
-        if (! $this->agents->covers($actor['scope'], $term->channal, null) || ! $this->can($term, $actor['editor'], 'update')) {
+        if (! $this->agents->covers($actor['scope'], $term->channelUid(), null) || ! $this->can($term, $actor['editor'], 'update')) {
             throw new AuthorizationException(__('messages.term_forbidden'));
         }
         if ($ifMatch === null || $ifMatch === '') {
             throw new BusinessException(__('messages.term_if_match_required'), 428, 'precondition-required', [], 'Precondition Required');
         }
-        if ($term->channal !== null && array_key_exists('language', $data)) {
+        if ($term->channelUid() !== null && array_key_exists('language', $data)) {
             throw ValidationException::withMessages(['language' => __('messages.term_language_follows_channel')]);
         }
         $this->guardRedirect($term->word, $term->tag, $data);
@@ -363,7 +364,7 @@ class TermService
             Log::warning('Failed to remove deleted term from index', ['guid' => $term->guid, 'error' => $e->getMessage()]);
         }
 
-        $term->load($this->relations());
+        $this->loadRelations(new EloquentCollection([$term]));
         $this->decorate(collect([$term]), $actorUid, withBody: false);
 
         return $term;
@@ -387,8 +388,8 @@ class TermService
 
         $result = [];
         foreach ($terms as $term) {
-            if ($term->channal !== null) {
-                $ch = $channelAbilities[$term->channal] ?? ['read' => false, 'write' => false];
+            if ($term->channelUid() !== null) {
+                $ch = $channelAbilities[$term->channelUid()] ?? ['read' => false, 'write' => false];
                 $read = $ch['read'];
                 $update = $userUid !== null && $ch['write'];
             } else {
@@ -426,10 +427,11 @@ class TermService
         $order = $filters['order'] ?? 'updated_at';
         $dir = $filters['dir'] ?? ($order === 'word' ? 'asc' : 'desc');
 
-        $page = $query->with($this->relations())
+        $page = $query
             ->orderBy($order, $dir)
             ->orderBy('guid')
             ->paginate($perPage);
+        $this->loadRelations($page->getCollection());
         $this->decorate($page->getCollection(), $viewerUid, withBody: $withBody);
 
         return $page;
@@ -469,10 +471,28 @@ class TermService
             UserService::eagerLoadAssistant('coEditor'),
             // 只取分类名(与外键、排序);term_categories.id 不对外,也用不到
             'categories:term_guid,category,position',
-            'channel:uid,name',
         ];
     }
 
+    /**
+     * 预加载 {@see self::relations()} 与所属 channel。
+     *
+     * channel 只给真属于某个 channel 的加载:studio 级的老数据 channal 是空串,
+     * 统一 `with('channel')` 会拿空串去比 uuid 列,PostgreSQL 直接报错。
+     *
+     * @param  EloquentCollection<int, DhammaTerm>  $terms
+     */
+    private function loadRelations(EloquentCollection $terms): void
+    {
+        $terms->load($this->relations());
+        $terms->filter(fn (DhammaTerm $term) => $term->channelUid() !== null)->load('channel:uid,name');
+        $terms->each(function (DhammaTerm $term) {
+            if ($term->channelUid() === null) {
+                $term->setRelation('channel', null);
+            }
+        });
+    }
+
     /**
      * 挂上 abilities、摘要纯文本,详情另挂渲染后的正文。整批渲染一次。
      *
@@ -708,8 +728,8 @@ class TermService
      */
     private function forgetCache(DhammaTerm $term): void
     {
-        $channels = $term->channal !== null
-            ? [$term->channal]
+        $channels = $term->channelUid() !== null
+            ? [$term->channelUid()]
             : Channel::where('owner_uid', $term->owner)->pluck('uid')->all();
         foreach ($channels as $uid) {
             RedisCache::forget("/term/{$uid}/{$term->word}");

+ 40 - 8
api-v13/app/Services/WikiService.php

@@ -9,7 +9,9 @@ use App\Services\Markup\Format;
 use App\Services\Markup\MarkupService;
 use App\Services\Markup\RenderOptions;
 use App\Services\V3\ChannelAbilityService;
+use Illuminate\Auth\Access\AuthorizationException;
 use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Database\Eloquent\ModelNotFoundException;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Str;
@@ -20,8 +22,9 @@ use Illuminate\Support\Str;
  * 直接查库,不经 OpenSearch:质量取 dhamma_terms.quality,分类取 term_categories(v3 写入时从正文
  * `{{category|…}}` 抽出),摘要取 summary 或正文第一段。正文用新渲染器({@see MarkupService})出 HTML。
  *
- * 只列公开的:所在 channel 会被列出(status 30 或系统 channel,{@see ChannelAbilityService::scopeListable()}),
- * 或 studio 级术语(不属于任何 channel)。
+ * 列表、相关词条、其它版本只列公开的:所在 channel 会被列出(status 30 或系统 channel,
+ * {@see ChannelAbilityService::scopeListable()}),或 studio 级术语(不属于任何 channel)。
+ * 按 guid 打开的词条页按「能访问」判(公开不列出的也能看,私有 403)。
  */
 class WikiService
 {
@@ -71,13 +74,15 @@ class WikiService
     /**
      * 按 guid 或词找要显示的词条。
      *
-     * - guid:这一条(要公开)
+     * - guid:这一条,拿到链接就能看(公开不列出的也行),私有 channel 的 403
      * - 词:先找该语言社区 channel(`_community_translation_{lang}_`)里的,没有就取公开词条里质量最高、最近更新的
+     *
+     * @throws AuthorizationException guid 指向私有 channel 的术语
      */
     public function find(string $lang, string $wordOrId): ?DhammaTerm
     {
         if (Str::isUuid($wordOrId)) {
-            return $this->publicTerms(null)->where('guid', $wordOrId)->first();
+            return $this->accessibleTerm($wordOrId);
         }
 
         $community = Channel::where('name', '_community_translation_'.strtolower($lang).'_')
@@ -97,6 +102,33 @@ class WikiService
             ->first();
     }
 
+    /**
+     * 按 guid 取一条:拿到链接就能看,与「会不会被列出」无关。
+     *
+     * channel 是公开(30)或公开不列出(20)、系统 channel、或 studio 级术语都能看;
+     * library 没有登录态,私有 channel 的一律 403({@see ChannelAbilityService::assertReadable()}),
+     * 术语或它所在的 channel 不存在(含软删)返回 null(404)。
+     *
+     * @throws AuthorizationException
+     */
+    private function accessibleTerm(string $guid): ?DhammaTerm
+    {
+        $term = DhammaTerm::where('guid', $guid)->first();
+        if ($term === null) {
+            return null;
+        }
+        $channelUid = $term->channelUid();
+        if ($channelUid !== null) {
+            try {
+                $this->channels->assertReadable($channelUid, null);
+            } catch (ModelNotFoundException) {
+                return null;
+            }
+        }
+
+        return $term;
+    }
+
     /**
      * 重定向的目标(`word` 或 `word@tag`):先在同一 channel(studio 级的在同一 owner 的 studio 级术语)里找,
      * 找不到返回 null(读者停在原词条上)。
@@ -112,9 +144,9 @@ class WikiService
         $tag === ''
             ? $query->where(fn (Builder $q) => $q->whereNull('tag')->orWhere('tag', ''))
             : $query->where('tag', $tag);
-        $term->channal !== null
-            ? $query->where('channal', $term->channal)
-            : $query->whereNull('channal')->where('owner', $term->owner);
+        $term->channelUid() !== null
+            ? $query->where('channal', $term->channelUid())
+            : $query->studioLevel()->where('owner', $term->owner);
 
         $target = $query->first();
 
@@ -220,7 +252,7 @@ class WikiService
     private function publicTerms(?string $lang): Builder
     {
         $query = DhammaTerm::query()->where(function (Builder $q) {
-            $q->whereNull('channal')->orWhereIn('channal', function ($sub) {
+            $q->studioLevel()->orWhereIn('channal', function ($sub) {
                 $sub->selectRaw('uid::text')->from('channels')->whereNull('deleted_at');
                 $this->channels->scopeListable($sub, null);
             });

+ 10 - 2
api-v13/resources/css/modules/wiki.css

@@ -231,13 +231,21 @@
    五、term-ref 行内术语标记
    ══════════════════════════════════════════ */
 
+/* 颜色与 v6 术语组件一致:找到蓝(主色)、社区术语绿、没找到红;不斜体 */
 .term-ref {
-    font-style: italic;
     color: var(--tblr-primary);
-    border-bottom: 1px dotted var(--tblr-primary);
+    border-bottom: 1px dotted currentColor;
     cursor: pointer;
 }
 
+.term-ref.term_community {
+    color: green;
+}
+
+.term-ref.term_invalid {
+    color: var(--tblr-danger);
+}
+
 /* ══════════════════════════════════════════
    六、Term Popover(桌面)
    ══════════════════════════════════════════ */

+ 3 - 0
api-v13/tests/Feature/MarkupTemplateDataTest.php

@@ -91,6 +91,9 @@ describe('term', function () {
 
         $props = markupDataTree('{{term|kusala}}', ['channels' => [$this->channel]])[0]['props'];
         expect($props)->toMatchArray(['meaning' => '善', 'isCommunity' => true]);
+        // HTML 带上社区标记,library 百科页据此着绿色(与 v6 术语组件一致)
+        expect(markupDataRender('{{term|kusala}}', Format::Html, ['channels' => [$this->channel]]))
+            ->toContain('class="term-ref term_community"');
     });
 
     it('filters by tag with word@tag and overrides the label with word#text', function () {

+ 18 - 0
api-v13/tests/Feature/TermV3Test.php

@@ -162,6 +162,24 @@ it('shows a term with ETag, and hides terms of private channels', function () {
     $this->getJson('/api/v3/terms/'.Str::uuid())->assertNotFound();
 });
 
+it('treats legacy studio-level terms with an empty-string channal like null ones', function () {
+    [$team, $users] = makeTeam();
+    $created = $this->postJson("/api/v3/studios/{$team}/terms", ['word' => 'legacy', 'meaning' => '老', 'language' => 'zh-Hans'], authHeader($users['owner']))
+        ->assertCreated()->json('data');
+    newTerm(makeChannel($team), $users['owner'], ['word' => 'in-channel']);
+    DhammaTerm::where('guid', $created['id'])->update(['channal' => '']);
+
+    $this->getJson("/api/v3/terms/{$created['id']}")
+        ->assertOk()->assertJsonPath('data.channel_id', null)->assertJsonPath('data.channel', null);
+    $this->getJson("/api/v3/studios/{$team}/terms?order=word", authHeader($users['reader']))
+        ->assertOk()->assertJsonPath('data.*.word', ['in-channel', 'legacy']);
+    $this->getJson("/api/v3/studios/{$team}/terms?general=true", authHeader($users['reader']))
+        ->assertJsonPath('data.*.word', ['legacy']);
+    $this->getJson('/api/v3/terms?word=legacy')->assertOk()->assertJsonPath('data.*.id', [$created['id']]);
+    $this->postJson("/api/v3/studios/{$team}/terms", ['word' => 'legacy', 'meaning' => '重', 'language' => 'zh-Hans'], authHeader($users['owner']))
+        ->assertConflict();
+});
+
 it('renders the body against the requested channels, ignoring those the viewer cannot see', function () {
     $owner = makeStudio('owner');
     $home = makeChannel($owner, 'home');

+ 23 - 2
api-v13/tests/Feature/WikiPageTest.php

@@ -119,13 +119,34 @@ it('follows a redirect to the target term in the same channel', function () {
     $this->get('/library/wiki/zh-Hans/nirv%C4%81%E1%B9%87a')->assertRedirect(route('library.wiki.show', ['zh-Hans', $target]));
 });
 
-it('hides terms of private channels and unknown words', function () {
+it('forbids terms of private channels by id, and hides them and unknown words by word', function () {
     $owner = makeStudio('owner');
     $private = makeChannel($owner);
     Channel::where('uid', $private)->update(['status' => Channel::STATUS_PRIVATE]);
     $guid = wikiTerm($private, 'secret');
 
-    $this->get("/library/wiki/zh-Hans/{$guid}")->assertNotFound();
+    $this->get("/library/wiki/zh-Hans/{$guid}")->assertForbidden();
+    $this->get('/library/wiki/zh-Hans/'.Str::uuid())->assertNotFound();
     $this->get('/library/wiki/zh-Hans/secret')->assertNotFound();
     $this->get('/library/wiki/zh-Hans/no-such-word')->assertNotFound();
 });
+
+it('shows a term of an unlisted channel by id, but never lists it', function () {
+    $owner = makeStudio('owner');
+    $unlisted = makeChannel($owner);
+    Channel::where('uid', $unlisted)->update(['status' => Channel::STATUS_UNLISTED]);
+    $guid = wikiTerm($unlisted, 'zzunlisted', ['quality' => 'featured', 'note' => '不列出的正文。'], ['学处']);
+
+    expect($this->get("/library/wiki/zh-Hans/{$guid}")->assertOk()->getContent())->toContain('不列出的正文。');
+    $this->get('/library/wiki/zh-Hans/zzunlisted')->assertNotFound();
+    expect($this->get('/library/wiki/zh-Hans?category=vinaya&quality=pending')->assertOk()->getContent())
+        ->not->toContain('zzunlisted');
+});
+
+it('treats an empty-string channal as a studio-level term', function () {
+    $owner = makeStudio('owner');
+    $guid = wikiTerm(makeChannel($owner), 'legacy', ['note' => '老数据正文。']);
+    DhammaTerm::where('guid', $guid)->update(['channal' => '']);
+
+    expect($this->get("/library/wiki/zh-Hans/{$guid}")->assertOk()->getContent())->toContain('老数据正文。');
+});

+ 10 - 1
dashboard-v6/src/components/term/TermCtl.tsx

@@ -56,7 +56,10 @@ interface ITermState {
 }
 
 type TermAction =
+  // 本人在自己 studio 里新建 / 修改了同一个词:换成本人的版本,不再是社区术语
   | { type: "UPDATE_TERM"; payload: Term }
+  // 悬停时取到这条术语的详情:还是同一条,社区状态不变
+  | { type: "LOADED_TERM"; payload: Term }
   | { type: "SET_TERM_DATA"; payload: ITerm };
 
 function termReducer(state: ITermState, action: TermAction): ITermState {
@@ -67,6 +70,12 @@ function termReducer(state: ITermState, action: TermAction): ITermState {
         isInit: false,
         community: false,
       };
+    case "LOADED_TERM":
+      return {
+        ...state,
+        termData: dataMap(action.payload),
+        isInit: false,
+      };
     case "SET_TERM_DATA":
       return {
         ...state,
@@ -176,7 +185,7 @@ export const TermCtl = ({
         fetchTerm(id)
           .then((data) => {
             if (data) {
-              dispatch({ type: "UPDATE_TERM", payload: data });
+              dispatch({ type: "LOADED_TERM", payload: data });
               store.dispatch(upgrade(data));
             }
           })