Browse Source

Merge pull request #2504 from visuddhinanda/development

Development
visuddhinanda 4 ngày trước cách đây
mục cha
commit
50f3bc2b14

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 0 - 0
CLAUDE.md


+ 1 - 1
api-test/cases/16_terms.php

@@ -13,7 +13,7 @@ use \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest;
  */
  */
 
 
 test('GET /v3/terms?word= → 200;缺 word → 422', function () {
 test('GET /v3/terms?word= → 200;缺 word → 422', function () {
-    $res = request(fn () => api(TermsApi::class)->getApiV3TermsWithHttpInfo('dhamma', 5));
+    $res = request(fn () => api(TermsApi::class)->getApiV3TermsWithHttpInfo('dhamma', per_page: 5));
     assert_status(200, $res, 'terms lookup');
     assert_status(200, $res, 'terms lookup');
     assert_has_key('meta', $res['body'], 'terms lookup');
     assert_has_key('meta', $res['body'], 'terms lookup');
 
 

+ 16 - 1
api-test/cases/17_glossaries.php

@@ -17,14 +17,29 @@ test('GET /v3/glossaries/community?lang=zh-Hans → 200,整表带 meta', funct
     assert_eq(count($res['body']['data']), $res['body']['meta']['total'], '整表不分页:total 与条数相等');
     assert_eq(count($res['body']['data']), $res['body']['meta']['total'], '整表不分页:total 与条数相等');
     $first = $res['body']['data'][0] ?? null;
     $first = $res['body']['data'][0] ?? null;
     if ($first) {
     if ($first) {
-        assert_eq(['id', 'word', 'tag', 'meaning', 'other_meaning'], array_keys($first), '条目字段');
+        assert_eq(['word', 'tag', 'meaning', 'other_meaning'], array_keys($first), '条目字段(community 不给 id)');
     }
     }
 });
 });
 
 
+test('GET /v3/glossaries/community 带 If-None-Match(表没变)→ 304,无正文', function () {
+    $first = raw('GET', '/v3/glossaries/community', ['lang' => 'zh-Hans']);
+    assert_status(200, $first, 'community glossary');
+    $etag = $first['headers']['etag'][0] ?? null;
+    if ($etag === null) {
+        throw new Fail('community glossary 应带 ETag');
+    }
+    $again = raw('GET', '/v3/glossaries/community', ['lang' => 'zh-Hans'], null, null, ['If-None-Match' => $etag]);
+    assert_status(304, $again, '条件请求');
+});
+
 test('GET /v3/glossaries/grammar?lang=xx(没有这种语言的表)→ 200,回退到 en', function () {
 test('GET /v3/glossaries/grammar?lang=xx(没有这种语言的表)→ 200,回退到 en', function () {
     $res = raw('GET', '/v3/glossaries/grammar', ['lang' => 'xx']);
     $res = raw('GET', '/v3/glossaries/grammar', ['lang' => 'xx']);
     assert_status(200, $res, 'grammar glossary 回退');
     assert_status(200, $res, 'grammar glossary 回退');
     assert_eq('en', $res['body']['meta']['lang'] ?? null, '回退语言');
     assert_eq('en', $res['body']['meta']['lang'] ?? null, '回退语言');
+    $first = $res['body']['data'][0] ?? null;
+    if ($first) {
+        assert_has_key('id', $first, 'grammar 条目带 id(v6 凭它取术语正文)');
+    }
 });
 });
 
 
 test('GET /v3/glossaries/{非法 kind} → 404;lang 格式不对 → 422', function () {
 test('GET /v3/glossaries/{非法 kind} → 404;lang 格式不对 → 422', function () {

+ 1 - 1
api-test/client/lib/Model/GetApiV3GlossariesKind200ResponseDataInner.php

@@ -330,7 +330,7 @@ class GetApiV3GlossariesKind200ResponseDataInner implements ModelInterface, Arra
     /**
     /**
      * Sets id
      * Sets id
      *
      *
-     * @param string|null $id id
+     * @param string|null $id 仅在部分查询口径下返回。
      *
      *
      * @return self
      * @return self
      */
      */

+ 98 - 48
api-v13/app/Console/Commands/UpgradeCommunityTerm.php

@@ -2,10 +2,12 @@
 
 
 namespace App\Console\Commands;
 namespace App\Console\Commands;
 
 
-use App\Http\Api\ChannelApi;
+use App\Models\Channel;
 use App\Models\DhammaTerm;
 use App\Models\DhammaTerm;
 use App\Models\Sentence;
 use App\Models\Sentence;
 use App\Models\UserOperationDaily;
 use App\Models\UserOperationDaily;
+use App\Services\ChannelService;
+use App\Services\V3\GlossaryService;
 use App\Tools\Tools;
 use App\Tools\Tools;
 use Illuminate\Console\Command;
 use Illuminate\Console\Command;
 use Illuminate\Support\Str;
 use Illuminate\Support\Str;
@@ -24,64 +26,89 @@ class UpgradeCommunityTerm extends Command
      *
      *
      * @var string
      * @var string
      */
      */
-    protected $description = 'Command description';
-
-    /**
-     * Create a new command instance.
-     *
-     * @return void
-     */
-    public function __construct()
-    {
-        parent::__construct();
-    }
+    protected $description = '由各用户的术语生成社区术语表(_community_term_{lang}_):每个 word + tag 一条,取最常见的译名与得分最高的注释';
 
 
     /**
     /**
      * Execute the console command.
      * Execute the console command.
      *
      *
      * @return int
      * @return int
      */
      */
-    public function handle()
+    public function handle(ChannelService $channels, GlossaryService $glossaries)
     {
     {
         if (Tools::isStop()) {
         if (Tools::isStop()) {
             return 0;
             return 0;
         }
         }
         $lang = strtolower($this->argument('lang'));
         $lang = strtolower($this->argument('lang'));
         $langFamily = explode('-', $lang)[0];
         $langFamily = explode('-', $lang)[0];
-        $localTerm = ChannelApi::getSysChannel("_community_term_{$lang}_");
+        $localTerm = $channels->systemUid("_community_term_{$lang}_");
         if (! $localTerm) {
         if (! $localTerm) {
             return 1;
             return 1;
         }
         }
 
 
-        $channelId = ChannelApi::getSysChannel('_System_Pali_VRI_');
+        $channelId = $channels->systemUid('_System_Pali_VRI_');
         if ($channelId === false) {
         if ($channelId === false) {
             $this->error('no channel');
             $this->error('no channel');
 
 
             return 1;
             return 1;
         }
         }
-        $table = DhammaTerm::select(['word', 'tag'])
-            ->whereIn('language', [$this->argument('lang'), $lang, $langFamily])
-            ->groupBy(['word', 'tag']);
+        $langs = [$this->argument('lang'), $lang, $langFamily];
+        $wordArg = $this->argument('word');
+
+        // 来源:该语言的全部术语,但不含社区 channel 自己——
+        // 否则社区里的每一行都会作为来源把自己续命,坏行永远清不掉。
+        $sources = fn () => DhammaTerm::query()
+            ->whereIn('language', $langs)
+            ->where(fn ($q) => $q->whereNull('channal')->orWhere('channal', '<>', $localTerm));
 
 
-        if ($this->argument('word')) {
-            $table = $table->where('word', $this->argument('word'));
+        // 要生成的 (word, tag)。tag 的 NULL、''、纯空白都算「无 tag」,归成一组。
+        $pairs = $sources()
+            ->select(['word', 'tag'])
+            ->whereNotNull('word')
+            ->where('word', '<>', '')
+            ->distinct()
+            ->when($wordArg, fn ($q) => $q->where('word', $wordArg))
+            ->get()
+            ->map(fn ($row) => (object) ['word' => $row->word, 'tag' => self::normalizeTag($row->tag)])
+            ->unique(fn ($row) => self::pairKey($row->word, $row->tag))
+            ->values();
+
+        if ($pairs->isEmpty()) {
+            // 来源查空了多半是出了问题,不要据此清空整个社区 channel
+            $this->error('no source terms');
+
+            return 1;
         }
         }
-        $words = $table->get();
-        $bar = $this->output->createProgressBar(count($words));
-        foreach ($words as $key => $word) {
+
+        // 社区 channel 里现有的行,按同样的口径分组;处理一组就取走一组,最后剩下的都是该删的
+        $existing = DhammaTerm::where('channal', $localTerm)
+            ->when($wordArg, fn ($q) => $q->where('word', $wordArg))
+            ->orderBy('create_time')
+            ->orderBy('guid')
+            ->get()
+            ->groupBy(fn ($row) => self::pairKey($row->word, self::normalizeTag($row->tag)));
+
+        $aiChannels = Channel::where('source_type', 'ai')->pluck('uid')->flip();
+
+        $total = $pairs->count();
+        foreach ($pairs as $index => $word) {
             /**
             /**
              * 最优算法
              * 最优算法
              * 1. 找到最常见的意思
              * 1. 找到最常见的意思
              * 2. 找到分数最高的
              * 2. 找到分数最高的
              */
              */
             $bestNote = '';
             $bestNote = '';
-            $allTerm = DhammaTerm::where('word', $word->word)
-                ->where('tag', $word->tag)
-                ->whereIn('language', [$this->argument('lang'), $lang, $langFamily])
-                ->get();
+            $allTerm = $sources()
+                ->where('word', $word->word)
+                ->get()
+                ->filter(fn ($term) => self::normalizeTag($term->tag) === $word->tag)
+                ->values();
             $score = [];
             $score = [];
             // $term_exp = [];
             // $term_exp = [];
             foreach ($allTerm as $key => $term) {
             foreach ($allTerm as $key => $term) {
+                // AI 生成的 channel(source_type=ai)里的注释不参与评选;译名统计仍算它们
+                if ($term->channal !== null && isset($aiChannels[$term->channal])) {
+                    continue;
+                }
                 // 获取经验值
                 // 获取经验值
                 $exp = UserOperationDaily::where('user_id', $term->editor_id)
                 $exp = UserOperationDaily::where('user_id', $term->editor_id)
                     ->where('date_int', '<=', date_timestamp_get(date_create($term->updated_at)) * 1000)
                     ->where('date_int', '<=', date_timestamp_get(date_create($term->updated_at)) * 1000)
@@ -133,9 +160,10 @@ class UpgradeCommunityTerm extends Command
             }
             }
 
 
             // 需要过滤掉system_term的数量,把count(*)替换为经验值加合作为基础得分,(基础经验得分之和转化为标准活动周,再加上最近的更新时间,为最终得分)
             // 需要过滤掉system_term的数量,把count(*)替换为经验值加合作为基础得分,(基础经验得分之和转化为标准活动周,再加上最近的更新时间,为最终得分)
-            $hotMeaning = DhammaTerm::selectRaw('meaning,count(*) as co')
+            // FIXME: 只按 word 统计、不看 tag,同词不同义项会被写成同一个译名
+            $hotMeaning = $sources()
+                ->selectRaw('meaning,count(*) as co')
                 ->where('word', $word->word)
                 ->where('word', $word->word)
-                ->whereIn('language', [$this->argument('lang'), $lang, $langFamily])
                 ->groupBy('meaning')
                 ->groupBy('meaning')
                 ->orderBy('co', 'desc')
                 ->orderBy('co', 'desc')
                 ->first();
                 ->first();
@@ -146,33 +174,55 @@ class UpgradeCommunityTerm extends Command
                     $bestNote = $allTerm[(int) key($score)]->note;
                     $bestNote = $allTerm[(int) key($score)]->note;
                 }
                 }
 
 
-                $term = DhammaTerm::where('channal', $localTerm)->firstOrNew(
-                    [
-                        'word' => $word->word,
-                        'tag' => $word->tag,
-                        'channal' => $localTerm,
-                    ],
-                    [
-                        'id' => app('snowflake')->id(),
-                        'guid' => Str::uuid(),
-                        'word_en' => Tools::getWordEn($word->word),
-                        'meaning' => '',
-                        'language' => $this->argument('lang'),
-                        'owner' => config('mint.admin.root_uuid'),
-                        'editor_id' => 0,
-                        'create_time' => time() * 1000,
-                    ]
-                );
+                // 同一组若有多行(历史上 NULL / '' / 空白 tag 各建了一行),留最早建的那行,其余删掉
+                $rows = $existing->pull(self::pairKey($word->word, $word->tag)) ?? collect();
+                $term = $rows->shift() ?? new DhammaTerm([
+                    'id' => app('snowflake')->id(),
+                    'guid' => Str::uuid(),
+                    'word' => $word->word,
+                    'word_en' => Tools::getWordEn($word->word),
+                    'meaning' => '',
+                    'channal' => $localTerm,
+                    'language' => $this->argument('lang'),
+                    'owner' => config('mint.admin.root_uuid'),
+                    'editor_id' => 0,
+                    'create_time' => time() * 1000,
+                ]);
+                $rows->each->delete();
+
                 $term->tag = $word->tag;
                 $term->tag = $word->tag;
                 $term->meaning = $hotMeaning->meaning;
                 $term->meaning = $hotMeaning->meaning;
                 $term->note = $bestNote;
                 $term->note = $bestNote;
                 $term->modify_time = time() * 1000;
                 $term->modify_time = time() * 1000;
                 $term->save();
                 $term->save();
             }
             }
-            $bar->advance();
+            $done = $index + 1;
+            if ($done % 100 === 0 || $done === $total) {
+                $this->info("{$done}/{$total}");
+            }
         }
         }
-        $bar->finish();
+
+        // 没有来源支撑的行(来源术语已删,或历史重复行):这个 channel 只由本任务维护,一并删除(软删)
+        $stale = $existing->flatten();
+        $stale->each->delete();
+        $this->info("done: {$total} terms, {$stale->count()} stale rows removed");
+
+        // 表可能变了:换 ETag,客户端(/v3/glossaries/community)下次请求拿新数据
+        $glossaries->rotateEtag($localTerm);
 
 
         return 0;
         return 0;
     }
     }
+
+    /** tag 的 NULL、''、纯空白都当作「无 tag」(null) */
+    private static function normalizeTag(?string $tag): ?string
+    {
+        $tag = trim((string) $tag);
+
+        return $tag === '' ? null : $tag;
+    }
+
+    private static function pairKey(?string $word, ?string $tag): string
+    {
+        return ($word ?? '')."\0".($tag ?? '');
+    }
 }
 }

+ 21 - 4
api-v13/app/Http/Controllers/V3/GlossaryController.php

@@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
 use App\Http\Requests\V3\IndexGlossaryRequest;
 use App\Http\Requests\V3\IndexGlossaryRequest;
 use App\Http\Resources\V3\GlossaryEntryResource;
 use App\Http\Resources\V3\GlossaryEntryResource;
 use App\Services\V3\GlossaryService;
 use App\Services\V3\GlossaryService;
+use Illuminate\Http\Response;
 
 
 /**
 /**
  * 术语词汇表:语法术语表 / 社区译名表(只读)。
  * 术语词汇表:语法术语表 / 社区译名表(只读)。
@@ -21,7 +22,7 @@ class GlossaryController extends Controller
      * 术语词汇表
      * 术语词汇表
      *
      *
      * 整表返回、不分页(客户端启动时拉一次,本地查词)。`meta.lang` 是实际用到的语言:
      * 整表返回、不分页(客户端启动时拉一次,本地查词)。`meta.lang` 是实际用到的语言:
-     * 该语言没有这张表时回退到英文。
+     * 该语言没有这张表时回退到英文。条目的 `id`(术语 guid)只有 grammar 表给,community 表不给(省流量)。
      *
      *
      * @unauthenticated
      * @unauthenticated
      *
      *
@@ -31,16 +32,32 @@ class GlossaryController extends Controller
      *
      *
      * @meta kind string 哪张表
      * @meta kind string 哪张表
      * @meta lang string 实际用到的语言(没有该语言的表时是 en)
      * @meta lang string 实际用到的语言(没有该语言的表时是 en)
+     * community 表带 `ETag`(`Cache-Control: public, no-cache`):浏览器下次自动带 `If-None-Match`,
+     * 表没变就回 304、不带正文。ETag 在社区术语任务每次跑完时更换。grammar 表暂不带。
      * @meta total integer 条数
      * @meta total integer 条数
      */
      */
     public function __invoke(IndexGlossaryRequest $request, string $kind)
     public function __invoke(IndexGlossaryRequest $request, string $kind)
     {
     {
-        $result = $this->glossaries->entries($kind, $request->validated('lang') ?? app()->getLocale());
+        $lang = $request->validated('lang') ?? app()->getLocale();
+        $etag = $this->glossaries->etag($kind, $lang);
+        $withEtag = fn ($response) => $etag === null ? $response : $response
+            ->setEtag($etag)
+            ->header('Cache-Control', 'public, no-cache');
 
 
-        return GlossaryEntryResource::collection($result['items'])->additional(['meta' => [
+        // 表没变:在查整表之前就回 304(isNotModified 按 RFC 9110 弱比较,nginx 压缩后的 W/"…" 也认)
+        if ($etag !== null) {
+            $probe = $withEtag(new Response);
+            if ($probe->isNotModified($request)) {
+                return $probe;
+            }
+        }
+
+        $result = $this->glossaries->entries($kind, $lang);
+
+        return $withEtag(GlossaryEntryResource::collection($result['items'])->additional(['meta' => [
             'kind' => $kind,
             'kind' => $kind,
             'lang' => $result['lang'],
             'lang' => $result['lang'],
             'total' => $result['items']->count(),
             'total' => $result['items']->count(),
-        ]]);
+        ]])->response());
     }
     }
 }
 }

+ 6 - 3
api-v13/app/Http/Resources/V3/GlossaryEntryResource.php

@@ -6,7 +6,10 @@ use App\Models\DhammaTerm;
 use Illuminate\Http\Request;
 use Illuminate\Http\Request;
 
 
 /**
 /**
- * 词汇表的一条(`dhamma_terms` 表里系统 channel 的术语)。只给客户端本地查词要用的字段;`id` 是术语 guid。
+ * 词汇表的一条(`dhamma_terms` 表里系统 channel 的术语)。只给客户端本地查词要用的字段。
+ *
+ * `id`(术语 guid)只在语法术语表(grammar)里给:v6 悬停 / 语法手册凭它取 `/v3/terms/{id}`。
+ * 社区译名表(community)没有任何客户端用 id,而上万个 uuid 是整张表里最大、最压不动的一块,所以不给。
  *
  *
  * @mixin DhammaTerm
  * @mixin DhammaTerm
  */
  */
@@ -14,7 +17,7 @@ class GlossaryEntryResource extends BaseResource
 {
 {
     /**
     /**
      * @return array{
      * @return array{
-     *     id: string,
+     *     id?: string,
      *     word: string,
      *     word: string,
      *     tag: string|null,
      *     tag: string|null,
      *     meaning: string,
      *     meaning: string,
@@ -27,7 +30,7 @@ class GlossaryEntryResource extends BaseResource
         $other = trim((string) $this->other_meaning);
         $other = trim((string) $this->other_meaning);
 
 
         return [
         return [
-            'id' => (string) $this->guid,
+            'id' => $this->when($request->route('kind') === 'grammar', fn () => (string) $this->guid),
             'word' => (string) $this->word,
             'word' => (string) $this->word,
             'tag' => $tag === '' ? null : $tag,
             'tag' => $tag === '' ? null : $tag,
             'meaning' => (string) $this->meaning,
             'meaning' => (string) $this->meaning,

+ 63 - 7
api-v13/app/Services/V3/GlossaryService.php

@@ -2,9 +2,12 @@
 
 
 namespace App\Services\V3;
 namespace App\Services\V3;
 
 
+use App\Facades\RedisCache;
+use App\Http\Resources\V3\GlossaryEntryResource;
 use App\Models\DhammaTerm;
 use App\Models\DhammaTerm;
 use App\Services\ChannelService as ChannelLookup;
 use App\Services\ChannelService as ChannelLookup;
 use Illuminate\Support\Collection;
 use Illuminate\Support\Collection;
+use Illuminate\Support\Str;
 
 
 /**
 /**
  * 术语词汇表(只读):语法术语表与社区译名表,客户端启动时整表拉取后本地查。
  * 术语词汇表(只读):语法术语表与社区译名表,客户端启动时整表拉取后本地查。
@@ -25,6 +28,15 @@ class GlossaryService
 
 
     private const FALLBACK_LANG = 'en';
     private const FALLBACK_LANG = 'en';
 
 
+    /**
+     * 响应结构的版本,拼进 ETag。{@see GlossaryEntryResource} 的字段一改就加 1,
+     * 否则浏览器带着旧 ETag 来会拿到 304、继续用旧结构的缓存。
+     */
+    private const SCHEMA_VERSION = 2;
+
+    /** ETag 在 Redis 里的存活时间;本任务每天都会换新,过期了也只是让客户端多拉一次 */
+    private const ETAG_TTL = 30 * 24 * 60 * 60;
+
     public function __construct(private readonly ChannelLookup $channels) {}
     public function __construct(private readonly ChannelLookup $channels) {}
 
 
     /**
     /**
@@ -34,13 +46,7 @@ class GlossaryService
      */
      */
     public function entries(string $kind, string $lang): array
     public function entries(string $kind, string $lang): array
     {
     {
-        $prefix = self::CHANNEL_PREFIX[$kind];
-        $served = $lang;
-        $channel = $this->channels->systemUid($prefix.strtolower($lang).'_');
-        if ($channel === false) {
-            $served = self::FALLBACK_LANG;
-            $channel = $this->channels->systemUid($prefix.self::FALLBACK_LANG.'_');
-        }
+        [$channel, $served] = $this->channelOf($kind, $lang);
 
 
         $items = $channel === false
         $items = $channel === false
             ? collect()
             ? collect()
@@ -54,4 +60,54 @@ class GlossaryService
 
 
         return ['items' => $items, 'lang' => $served];
         return ['items' => $items, 'lang' => $served];
     }
     }
+
+    /**
+     * 某种词汇表当前的 ETag;没有 ETag 的表(grammar)或表不存在时返回 null。
+     *
+     * 只有 community 有:它的 channel 只由 `upgrade:community.term` 维护,任务跑完调
+     * {@see rotateEtag()} 换一个新 uuid,所以不用查整表、不用算 hash。有人绕过任务手工改了这个
+     * channel,ETag 不会变,客户端要等下次任务跑完才看得到。grammar 是人工编辑的,暂不支持。
+     */
+    public function etag(string $kind, string $lang): ?string
+    {
+        if ($kind !== 'community') {
+            return null;
+        }
+        [$channel] = $this->channelOf($kind, $lang);
+        if ($channel === false) {
+            return null;
+        }
+
+        // key 不存在(刚部署、Redis 清过、过期)就现生成一个
+        $token = RedisCache::remember(self::etagKey($channel), self::ETAG_TTL, fn () => (string) Str::uuid());
+
+        return $token.'.'.self::SCHEMA_VERSION;
+    }
+
+    /** 词汇表 channel 的内容变了:换一个新 ETag,客户端下次请求会拿到 200 与新数据 */
+    public function rotateEtag(string $channel): void
+    {
+        RedisCache::put(self::etagKey($channel), (string) Str::uuid(), self::ETAG_TTL);
+    }
+
+    private static function etagKey(string $channel): string
+    {
+        return "/glossary/{$channel}/etag";
+    }
+
+    /**
+     * 实际要读的 channel 与语言:该语言没有这张表时回退到英文(与 v2 相同)。
+     *
+     * @return array{0: string|false, 1: string}
+     */
+    private function channelOf(string $kind, string $lang): array
+    {
+        $prefix = self::CHANNEL_PREFIX[$kind];
+        $channel = $this->channels->systemUid($prefix.strtolower($lang).'_');
+        if ($channel !== false) {
+            return [$channel, $lang];
+        }
+
+        return [$this->channels->systemUid($prefix.self::FALLBACK_LANG.'_'), self::FALLBACK_LANG];
+    }
 }
 }

+ 1 - 1
api-v13/documents/tasks.md

@@ -53,7 +53,7 @@ start at: 16:00 UTC
 # 更新单词首选意思
 # 更新单词首选意思
 php artisan upgrade:dict.default.meaning
 php artisan upgrade:dict.default.meaning
 
 
-# 社区术语表
+# 社区术语表(这个 channel 只由本任务维护;跑完会换 /v3/glossaries/community 的 ETag)
 php artisan upgrade:community.term zh-Hans
 php artisan upgrade:community.term zh-Hans
 
 
 # 导出离线数据
 # 导出离线数据

+ 49 - 6
api-v13/tests/Feature/GlossaryV3Test.php

@@ -1,7 +1,9 @@
 <?php
 <?php
 
 
 use App\Models\DhammaTerm;
 use App\Models\DhammaTerm;
+use App\Services\V3\GlossaryService;
 use Illuminate\Foundation\Testing\RefreshDatabase;
 use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Str;
 use Illuminate\Support\Str;
 
 
 uses(RefreshDatabase::class);
 uses(RefreshDatabase::class);
@@ -78,12 +80,53 @@ it('rejects an unknown kind or a malformed language', function () {
         ->assertUnprocessable()->assertJsonValidationErrors('lang');
         ->assertUnprocessable()->assertJsonValidationErrors('lang');
 });
 });
 
 
-it('never exposes the auto-increment id of the terms', function () {
-    $zh = makeChannel(config('mint.admin.root_uuid'), '_community_term_zh-hans_');
-    $term = glossaryTerm($zh, 'dhamma');
+it('gives the term guid only in the grammar glossary, and never the auto-increment id', function () {
+    $root = config('mint.admin.root_uuid');
+    $grammar = glossaryTerm(makeChannel($root, '_System_Grammar_Term_zh-hans_'), 'vibhatti');
+    $community = glossaryTerm(makeChannel($root, '_community_term_zh-hans_'), 'dhamma');
 
 
-    $row = $this->getJson('/api/v3/glossaries/community?lang=zh-Hans')->json('data.0');
+    $row = $this->getJson('/api/v3/glossaries/grammar?lang=zh-Hans')->json('data.0');
     expect(array_keys($row))->toBe(['id', 'word', 'tag', 'meaning', 'other_meaning'])
     expect(array_keys($row))->toBe(['id', 'word', 'tag', 'meaning', 'other_meaning'])
-        ->and($row['id'])->toBe($term->guid)
-        ->and(json_encode($row))->not->toContain((string) $term->id);
+        ->and($row['id'])->toBe($grammar->guid)
+        ->and(json_encode($row))->not->toContain((string) $grammar->id);
+
+    $row = $this->getJson('/api/v3/glossaries/community?lang=zh-Hans')->json('data.0');
+    expect(array_keys($row))->toBe(['word', 'tag', 'meaning', 'other_meaning'])
+        ->and(json_encode($row))->not->toContain($community->guid)
+        ->and(json_encode($row))->not->toContain((string) $community->id);
+});
+
+it('answers 304 for an unchanged community glossary without loading it, and 200 after the task rotates the ETag', function () {
+    $zh = makeChannel(config('mint.admin.root_uuid'), '_community_term_zh-hans_');
+    glossaryTerm($zh, 'dhamma');
+
+    $first = $this->getJson('/api/v3/glossaries/community?lang=zh-Hans')->assertOk();
+    $etag = $first->headers->get('ETag');
+    expect($etag)->not->toBeEmpty()
+        ->and($first->headers->get('Cache-Control'))->toContain('no-cache')->toContain('public')
+        ->and($first->headers->get('Vary'))->toContain('Accept-Language');
+
+    DB::enableQueryLog();
+    $this->getJson('/api/v3/glossaries/community?lang=zh-Hans', ['If-None-Match' => $etag])
+        ->assertStatus(304)
+        ->assertHeader('ETag', $etag)
+        ->assertContent('');
+    // nginx gzip 会把 ETag 改成弱校验 W/"…",浏览器带回来的也是它
+    $this->getJson('/api/v3/glossaries/community?lang=zh-Hans', ['If-None-Match' => 'W/'.$etag])->assertStatus(304);
+    $loaded = collect(DB::getQueryLog())->contains(fn ($q) => str_contains($q['query'], 'dhamma_terms'));
+    expect($loaded)->toBeFalse();
+
+    app(GlossaryService::class)->rotateEtag($zh);
+
+    $fresh = $this->getJson('/api/v3/glossaries/community?lang=zh-Hans', ['If-None-Match' => $etag])->assertOk();
+    expect($fresh->headers->get('ETag'))->not->toBe($etag)
+        ->and($fresh->json('data.*.word'))->toBe(['dhamma']);
+});
+
+it('gives no ETag for the grammar glossary or a missing table', function () {
+    $grammar = makeChannel(config('mint.admin.root_uuid'), '_System_Grammar_Term_zh-hans_');
+    glossaryTerm($grammar, 'vibhatti');
+
+    expect($this->getJson('/api/v3/glossaries/grammar?lang=zh-Hans')->assertOk()->headers->has('ETag'))->toBeFalse()
+        ->and($this->getJson('/api/v3/glossaries/community?lang=zh-Hans')->assertOk()->headers->has('ETag'))->toBeFalse();
 });
 });

+ 130 - 0
api-v13/tests/Feature/UpgradeCommunityTermTest.php

@@ -0,0 +1,130 @@
+<?php
+
+use App\Models\Channel;
+use App\Models\DhammaTerm;
+use App\Services\V3\GlossaryService;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/*
+ * upgrade:community.term:社区术语表(_community_term_{lang}_)只由这个任务维护。
+ * 历史上 tag 的 NULL / '' / 空白各建了一行,导致同一个词重复;跑一次之后应恢复成每个 word + tag 一行。
+ */
+
+function communityTerm(string $channel, string $word, ?string $tag, array $attrs = []): DhammaTerm
+{
+    $term = new DhammaTerm;
+    $term->forceFill($attrs + [
+        'id' => random_int(1, PHP_INT_MAX),
+        'guid' => (string) Str::uuid(),
+        'word' => $word,
+        'word_en' => $word,
+        'tag' => $tag,
+        'meaning' => "{$word}-义",
+        'channal' => $channel,
+        'language' => 'zh-Hans',
+        'owner' => config('mint.admin.root_uuid'),
+        'editor_id' => 0,
+        'create_time' => time() * 1000,
+        'modify_time' => time() * 1000,
+    ])->save();
+
+    return $term;
+}
+
+beforeEach(function () {
+    $root = config('mint.admin.root_uuid');
+    makeChannel($root, '_System_Pali_VRI_');
+    $this->community = makeChannel($root, '_community_term_zh-hans_');
+    $this->user = makeChannel($root, 'user channel');
+});
+
+function communityRows(string $channel): array
+{
+    return DhammaTerm::where('channal', $channel)->orderBy('word')->orderBy('tag')->get()
+        ->map(fn ($t) => [$t->word, $t->tag, $t->meaning])->all();
+}
+
+it('merges NULL, empty and blank tags into one row per word', function () {
+    communityTerm($this->user, 'dhamma', null, ['meaning' => '法']);
+    communityTerm($this->user, 'dhamma', '', ['meaning' => '法']);
+    communityTerm($this->user, 'dhamma', '  ', ['meaning' => '法']);
+    communityTerm($this->user, 'dhamma', 'ārammaṇa', ['meaning' => '法']);
+
+    $this->artisan('upgrade:community.term', ['lang' => 'zh-Hans'])->assertSuccessful();
+
+    expect(communityRows($this->community))->toBe([
+        ['dhamma', 'ārammaṇa', '法'],
+        ['dhamma', null, '法'],
+    ]);
+});
+
+it('heals existing duplicates, keeping the oldest row, and is stable on rerun', function () {
+    communityTerm($this->user, 'sīla', '', ['meaning' => '戒']);
+    $oldest = communityTerm($this->community, 'sīla', null, ['create_time' => 1000]);
+    $dupA = communityTerm($this->community, 'sīla', '', ['create_time' => 2000]);
+    $dupB = communityTerm($this->community, 'sīla', ' ', ['create_time' => 3000]);
+
+    $this->artisan('upgrade:community.term', ['lang' => 'zh-Hans'])->assertSuccessful();
+    $this->artisan('upgrade:community.term', ['lang' => 'zh-Hans'])->assertSuccessful();
+
+    expect(communityRows($this->community))->toBe([['sīla', null, '戒']])
+        ->and(DhammaTerm::where('channal', $this->community)->value('guid'))->toBe($oldest->guid)
+        ->and(DhammaTerm::onlyTrashed()->whereIn('guid', [$dupA->guid, $dupB->guid])->count())->toBe(2);
+});
+
+it('does not count its own rows as sources: rows without user terms are removed', function () {
+    communityTerm($this->user, 'dhamma', null, ['meaning' => '法']);
+    // 社区里自己的一票不该影响译名,也不该让没有来源的行继续存在
+    communityTerm($this->community, 'dhamma', null, ['meaning' => '旧译名']);
+    communityTerm($this->community, 'orphan', null);
+
+    $this->artisan('upgrade:community.term', ['lang' => 'zh-Hans'])->assertSuccessful();
+
+    expect(communityRows($this->community))->toBe([['dhamma', null, '法']]);
+});
+
+it('never takes the note from an AI-generated channel, but still counts its meaning', function () {
+    $ai = makeChannel(config('mint.admin.root_uuid'), 'ai channel');
+    Channel::where('uid', $ai)->update(['source_type' => 'ai']);
+    communityTerm($ai, 'dhamma', null, ['meaning' => '法', 'note' => 'AI 写的注释']);
+    communityTerm($ai, 'dhamma', null, ['meaning' => '法']);
+    communityTerm($this->user, 'dhamma', null, ['meaning' => '达摩']);
+
+    $this->artisan('upgrade:community.term', ['lang' => 'zh-Hans'])->assertSuccessful();
+
+    $term = DhammaTerm::where('channal', $this->community)->sole();
+    expect($term->meaning)->toBe('法')
+        ->and((string) $term->note)->toBe('');
+});
+
+it('rotates the community glossary ETag after each run', function () {
+    communityTerm($this->user, 'dhamma', null);
+    $glossaries = app(GlossaryService::class);
+    $before = $glossaries->etag('community', 'zh-Hans');
+
+    $this->artisan('upgrade:community.term', ['lang' => 'zh-Hans'])->assertSuccessful();
+
+    expect($glossaries->etag('community', 'zh-Hans'))->not->toBe($before);
+});
+
+it('only touches the given word when one is passed', function () {
+    communityTerm($this->user, 'dhamma', null);
+    communityTerm($this->user, 'sīla', null);
+    communityTerm($this->community, 'sīla', '');
+    communityTerm($this->community, 'sīla', null);
+
+    $this->artisan('upgrade:community.term', ['lang' => 'zh-Hans', 'word' => 'dhamma'])->assertSuccessful();
+
+    expect(communityRows($this->community))->toHaveCount(3);
+});
+
+it('refuses to wipe the channel when no source terms are found', function () {
+    communityTerm($this->community, 'dhamma', null);
+
+    $this->artisan('upgrade:community.term', ['lang' => 'zh-Hans'])->assertFailed();
+
+    expect(communityRows($this->community))->toHaveCount(1);
+});

+ 4 - 1
dashboard-v6/src/api/schema.d.ts

@@ -8564,7 +8564,9 @@ export interface paths {
         /**
         /**
          * 术语词汇表
          * 术语词汇表
          * @description 整表返回、不分页(客户端启动时拉一次,本地查词)。`meta.lang` 是实际用到的语言:
          * @description 整表返回、不分页(客户端启动时拉一次,本地查词)。`meta.lang` 是实际用到的语言:
-         *     该语言没有这张表时回退到英文。
+         *     该语言没有这张表时回退到英文。条目的 `id`(术语 guid)只有 grammar 表给,community 表不给(省流量)。
+         *     community 表带 `ETag`(`Cache-Control: public, no-cache`):浏览器下次自动带 `If-None-Match`,
+         *     表没变就回 304、不带正文。ETag 在社区术语任务每次跑完时更换。grammar 表暂不带。
          *
          *
          *     实现:`V3\GlossaryController@__invoke`
          *     实现:`V3\GlossaryController@__invoke`
          */
          */
@@ -39162,6 +39164,7 @@ export interface operations {
                 content: {
                 content: {
                     "application/json": {
                     "application/json": {
                         data?: {
                         data?: {
+                            /** @description 仅在部分查询口径下返回。 */
                             id?: string;
                             id?: string;
                             word?: string;
                             word?: string;
                             tag?: string | null;
                             tag?: string | null;

+ 4 - 1
openapi/public/assets/protocol/resources/auto/v3-glossaries-kind.yaml

@@ -6,7 +6,9 @@ get:
   operationId: get_api_v3_glossaries_kind_
   operationId: get_api_v3_glossaries_kind_
   description: |-
   description: |-
     整表返回、不分页(客户端启动时拉一次,本地查词)。`meta.lang` 是实际用到的语言:
     整表返回、不分页(客户端启动时拉一次,本地查词)。`meta.lang` 是实际用到的语言:
-    该语言没有这张表时回退到英文。
+    该语言没有这张表时回退到英文。条目的 `id`(术语 guid)只有 grammar 表给,community 表不给(省流量)。
+    community 表带 `ETag`(`Cache-Control: public, no-cache`):浏览器下次自动带 `If-None-Match`,
+    表没变就回 304、不带正文。ETag 在社区术语任务每次跑完时更换。grammar 表暂不带。
 
 
     实现:`V3\GlossaryController@__invoke`
     实现:`V3\GlossaryController@__invoke`
   security:
   security:
@@ -45,6 +47,7 @@ get:
                   properties:
                   properties:
                     id:
                     id:
                       type: string
                       type: string
+                      description: 仅在部分查询口径下返回。
                     word:
                     word:
                       type: string
                       type: string
                     tag:
                     tag:

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác