Преглед на файлове

🐛 (term): channal 为空串的 studio 级术语按 studio 级处理

2022 年以前 v2 写入的 studio 级术语 channal 是空串(库里 1073 条,NULL 只有 252 条),
v3 只认 NULL:GET /v3/terms/{id} 把它当成属于不存在的 channel 而 403(workspace 悬停术语
弹「没有权限」),预加载 channel 拿空串比 uuid 列 500,按词查、general、重名检查也漏掉。

DhammaTerm 加 channelUid() 与 studioLevel(),v3 术语一律走它们;channel 只给真属于
channel 的术语预加载。数据不动,v2 本来用 empty() 判。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda преди 19 часа
родител
ревизия
4f9514d8c0

+ 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
     {

+ 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}");

+ 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');