Przeglądaj źródła

✨ 术语迁 v3:terms、glossaries、导入导出、语法说明,团队空间开放术语

- terms(v2 terms 各 view、单条、增改删)→ /v3/terms、channels/{c}/terms、studios/{s}/terms:
  新增列 co_editor_uid / quality / summary / content_type / version 与 term_categories 表;
  分类从正文 {{category|…}} 抽取、不限取值;word + tag 建立后不可改,改拼写走 redirect;
  乐观锁(ETag = version.modify_time,If-Match 缺 428、过期 412);软删除;
  支持 agent 代写(X-Agent-Grant);正文用新渲染器 App\Services\Markup
- term-vocabulary → /v3/glossaries/{grammar|community},回退 en
- terms-export / terms-import → 列表接口 Accept: xlsx 导出、…/terms/imports 导入:
  部分成功、有 etag 列就校验、不支持 agent;生成器支持 @bodyParam x file(multipart)
- grammar-guide 不设新端点:v6 GrammarPop 改走 glossaries/grammar + terms/{id},查不到退回按词查
- library 百科页不再依赖 OpenSearch,TermIndexService 改用新渲染器;二维码改用本地 qrcode 包
- v6、dashboard-test、api-test 跟着切;v2 端点在规格上标 deprecated,CLAUDE.md 对照表加行
- 团队空间开放术语模块(scope.ts 的 NOT_YET_SUPPORTED 去掉 workspace.term)

需要部署时跑 php artisan migrate。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 5 godzin temu
rodzic
commit
39c3b15ee6
100 zmienionych plików z 18804 dodań i 1360 usunięć
  1. 0 0
      CLAUDE.md
  2. 85 0
      api-test/cases/16_terms.php
  3. 35 0
      api-test/cases/17_glossaries.php
  4. 65 0
      api-test/cases/18_term_exchange.php
  5. 48 0
      api-test/client/.openapi-generator/FILES
  6. 1225 165
      api-test/client/lib/Api/ChannelsApi.php
  7. 502 0
      api-test/client/lib/Api/GlossariesApi.php
  8. 1223 67
      api-test/client/lib/Api/StudiosApi.php
  9. 1617 0
      api-test/client/lib/Api/TermsApi.php
  10. 443 0
      api-test/client/lib/Model/GetApiV3ChannelsChannelTerms200Response.php
  11. 1302 0
      api-test/client/lib/Model/GetApiV3ChannelsChannelTerms200ResponseDataInner.php
  12. 443 0
      api-test/client/lib/Model/GetApiV3ChannelsChannelTerms200ResponseDataInnerAbilities.php
  13. 443 0
      api-test/client/lib/Model/GetApiV3ChannelsChannelTerms200ResponseDataInnerChannel.php
  14. 443 0
      api-test/client/lib/Model/GetApiV3GlossariesKind200Response.php
  15. 559 0
      api-test/client/lib/Model/GetApiV3GlossariesKind200ResponseDataInner.php
  16. 477 0
      api-test/client/lib/Model/GetApiV3GlossariesKind200ResponseMeta.php
  17. 754 0
      api-test/client/lib/Model/PatchApiV3TermsTermRequest.php
  18. 409 0
      api-test/client/lib/Model/PostApiV3ChannelsChannelTerms200Response.php
  19. 409 0
      api-test/client/lib/Model/PostApiV3ChannelsChannelTermsImports200Response.php
  20. 545 0
      api-test/client/lib/Model/PostApiV3ChannelsChannelTermsImports200ResponseData.php
  21. 443 0
      api-test/client/lib/Model/PostApiV3ChannelsChannelTermsImports200ResponseDataErrorsInner.php
  22. 801 0
      api-test/client/lib/Model/PostApiV3ChannelsChannelTermsRequest.php
  23. 838 0
      api-test/client/lib/Model/PostApiV3StudiosStudioTermsRequest.php
  24. 38 177
      api-v13/app/Http/Controllers/Library/WikiController.php
  25. 102 0
      api-v13/app/Http/Controllers/V3/ChannelTermController.php
  26. 45 0
      api-v13/app/Http/Controllers/V3/ChannelTermImportController.php
  27. 46 0
      api-v13/app/Http/Controllers/V3/GlossaryController.php
  28. 100 0
      api-v13/app/Http/Controllers/V3/StudioTermController.php
  29. 43 0
      api-v13/app/Http/Controllers/V3/StudioTermImportController.php
  30. 127 0
      api-v13/app/Http/Controllers/V3/TermController.php
  31. 26 0
      api-v13/app/Http/Requests/V3/ImportTermsRequest.php
  32. 26 0
      api-v13/app/Http/Requests/V3/IndexGlossaryRequest.php
  33. 37 0
      api-v13/app/Http/Requests/V3/IndexTermRequest.php
  34. 37 0
      api-v13/app/Http/Requests/V3/LookupTermRequest.php
  35. 41 0
      api-v13/app/Http/Requests/V3/ShowTermRequest.php
  36. 41 0
      api-v13/app/Http/Requests/V3/StoreTermRequest.php
  37. 49 0
      api-v13/app/Http/Requests/V3/UpdateTermRequest.php
  38. 37 0
      api-v13/app/Http/Resources/V3/GlossaryEntryResource.php
  39. 33 0
      api-v13/app/Http/Resources/V3/TermImportResource.php
  40. 103 0
      api-v13/app/Http/Resources/V3/TermResource.php
  41. 69 0
      api-v13/app/Models/DhammaTerm.php
  42. 25 0
      api-v13/app/Models/TermCategory.php
  43. 11 0
      api-v13/app/Services/Markup/Templates/CategoryTemplate.php
  44. 21 0
      api-v13/app/Services/Markup/Templates/ReferenceTemplate.php
  45. 74 25
      api-v13/app/Services/TermIndexService.php
  46. 57 0
      api-v13/app/Services/V3/GlossaryService.php
  47. 355 0
      api-v13/app/Services/V3/TermExchangeService.php
  48. 8 0
      api-v13/app/Services/V3/TermImportRowError.php
  49. 718 0
      api-v13/app/Services/V3/TermService.php
  50. 282 0
      api-v13/app/Services/WikiService.php
  51. 34 0
      api-v13/database/migrations/2026_11_17_075645_add_v3_columns_to_dhamma_terms.php
  52. 30 0
      api-v13/database/migrations/2026_11_17_075645_create_term_categories_table.php
  53. 19 0
      api-v13/resources/css/modules/wiki.css
  54. 51 7
      api-v13/resources/js/modules/term-tooltip.js
  55. 56 0
      api-v13/resources/js/modules/wiki-share.js
  56. 17 0
      api-v13/resources/lang/en/messages.php
  57. 17 0
      api-v13/resources/lang/zh-Hans/messages.php
  58. 1 47
      api-v13/resources/views/components/wiki/entry-actions.blade.php
  59. 1 8
      api-v13/resources/views/library/wiki/show.blade.php
  60. 1 0
      api-v13/routes/api.php
  61. 47 0
      api-v13/routes/v3/term.php
  62. 89 0
      api-v13/tests/Feature/GlossaryV3Test.php
  63. 191 0
      api-v13/tests/Feature/TermExchangeV3Test.php
  64. 69 0
      api-v13/tests/Feature/TermIndexServiceTest.php
  65. 380 0
      api-v13/tests/Feature/TermV3Test.php
  66. 131 0
      api-v13/tests/Feature/WikiPageTest.php
  67. 1 0
      api-v13/vite.config.ts
  68. 2 1
      dashboard-test/src/lib/api.ts
  69. 25 0
      dashboard-test/src/tests/glossary.spec.ts
  70. 37 0
      dashboard-test/src/tests/grammar-pop.spec.ts
  71. 13 3
      dashboard-test/src/tests/teamspace.spec.ts
  72. 189 0
      dashboard-test/src/tests/term.spec.ts
  73. 0 5
      dashboard-v6/src/api/Guide.ts
  74. 191 93
      dashboard-v6/src/api/Term.ts
  75. 34 0
      dashboard-v6/src/api/glossary.ts
  76. 736 167
      dashboard-v6/src/api/schema.d.ts
  77. 48 8
      dashboard-v6/src/components/article/TypeTerm.tsx
  78. 4 0
      dashboard-v6/src/components/article/components/ArticleLayout.tsx
  79. 14 36
      dashboard-v6/src/components/article/hooks/useTerm.ts
  80. 79 27
      dashboard-v6/src/components/dict/GrammarPop.tsx
  81. 2 1
      dashboard-v6/src/components/markup/MarkupTemplate.tsx
  82. 4 2
      dashboard-v6/src/components/template/Quality.tsx
  83. 8 18
      dashboard-v6/src/components/term/TermCommunity.tsx
  84. 24 34
      dashboard-v6/src/components/term/TermCtl.tsx
  85. 266 251
      dashboard-v6/src/components/term/TermEdit.tsx
  86. 21 47
      dashboard-v6/src/components/term/TermExport.tsx
  87. 100 0
      dashboard-v6/src/components/term/TermImport.tsx
  88. 11 12
      dashboard-v6/src/components/term/TermItem.tsx
  89. 68 77
      dashboard-v6/src/components/term/TermList.tsx
  90. 3 3
      dashboard-v6/src/components/term/TermModal.tsx
  91. 15 23
      dashboard-v6/src/components/term/TermSearch.tsx
  92. 16 17
      dashboard-v6/src/components/term/TermTest.tsx
  93. 2 0
      dashboard-v6/src/features/editor/Term.tsx
  94. 0 1
      dashboard-v6/src/features/teamspace/scope.ts
  95. 12 32
      dashboard-v6/src/load.ts
  96. 26 1
      dashboard-v6/src/locales/en-US/label.ts
  97. 23 1
      dashboard-v6/src/locales/zh-Hans/label.ts
  98. 23 1
      dashboard-v6/src/locales/zh-Hant/label.ts
  99. 2 2
      dashboard-v6/src/pages/workspace/term/list.tsx
  100. 11 1
      dashboard-v6/src/pages/workspace/term/show.tsx

Plik diff jest za duży
+ 0 - 0
CLAUDE.md


+ 85 - 0
api-test/cases/16_terms.php

@@ -0,0 +1,85 @@
+<?php
+
+use \WikipaliApi\Api\ChannelsApi;
+use \WikipaliApi\Api\StudiosApi;
+use \WikipaliApi\Api\TermsApi;
+use \WikipaliApi\Model\PostApiV3ChannelsChannelTermsRequest;
+use \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest;
+
+/*
+ * v3 术语:/v3/terms、/v3/channels/{c}/terms、/v3/studios/{s}/terms。
+ * 写操作用临时 channel(e2e-tmp-terms-*):建 → 读(ETag)→ 改(If-Match,412 / 428)→ 删(软删),最后删掉 channel。
+ * 权限矩阵(团队角色、AI 代写)、分类抽取、N+1 由 api-v13 的 TermV3Test 覆盖。
+ */
+
+test('GET /v3/terms?word= → 200;缺 word → 422', function () {
+    $res = request(fn () => api(TermsApi::class)->getApiV3TermsWithHttpInfo('dhamma', 5));
+    assert_status(200, $res, 'terms lookup');
+    assert_has_key('meta', $res['body'], 'terms lookup');
+
+    $bad = raw('GET', '/v3/terms');
+    assert_status(422, $bad, 'terms 缺 word');
+    assert_field_error('word', $bad, 'terms 缺 word');
+});
+
+test('GET /v3/channels/{channel}/terms → 200;GET /v3/terms/{不存在} → 404', function () {
+    $res = request(fn () => api(ChannelsApi::class)->getApiV3ChannelsChannelTermsWithHttpInfo(fixtures()['channel'], 5));
+    assert_status(200, $res, 'channel terms');
+    assert_has_key('meta', $res['body'], 'channel terms');
+
+    assert_status(404, raw('GET', '/v3/terms/11111111-1111-4111-8111-111111111111'), '术语不存在');
+});
+
+test('写术语(无 token)→ 401', function () {
+    $res = raw('POST', '/v3/channels/'.fixtures()['channel'].'/terms', null, ['word' => 'x', 'meaning' => 'y']);
+    assert_status(401, $res, 'terms 无 token');
+    assert_problem($res, 'terms 无 token');
+});
+
+test('terms 一轮:建 201 → 读带 ETag → 不带 If-Match 428 → 旧 etag 412 → 改 200 → 删 200(软删)→ 再看 404', function () {
+    $token = required_token();
+    $me = raw('GET', '/v3/me', null, null, $token);
+    assert_status(200, $me, 'me');
+    $body = new PostApiV3StudiosStudioChannelsRequest();
+    $body->setName('e2e-tmp-terms-'.time());
+    $body->setType('translation');
+    $body->setLang('zh-Hans');
+    $channel = request(fn () => api(StudiosApi::class, $token)->postApiV3StudiosStudioChannelsWithHttpInfo($me['body']['data']['id'], $body));
+    assert_status(201, $channel, '建临时 channel');
+    $channelId = $channel['body']['data']['id'];
+
+    $termBody = new PostApiV3ChannelsChannelTermsRequest();
+    $termBody->setWord('apitest');
+    $termBody->setMeaning('接口测试');
+    $termBody->setNote("第一段。\n\n{{category|api-test}}");
+    $termBody->setQuality('draft');
+    $create = request(fn () => api(ChannelsApi::class, $token)->postApiV3ChannelsChannelTermsWithHttpInfo($channelId, $termBody));
+    assert_status(201, $create, '建术语');
+    $term = $create['body']['data'];
+    assert_eq('markdown-e2', $term['content_type'] ?? null, '新建默认 markdown-e2');
+    assert_eq(['api-test'], $term['categories'] ?? null, '分类从正文抽出');
+
+    $dup = raw('POST', "/v3/channels/{$channelId}/terms", null, ['word' => 'apitest', 'meaning' => '重复'], $token);
+    assert_status(409, $dup, '同一 word@tag 重复');
+
+    $show = raw('GET', "/v3/terms/{$term['id']}", null, null, $token);
+    assert_status(200, $show, '读术语');
+    assert_eq($term['etag'], $show['headers']['etag'][0] ?? null, 'ETag 头与 etag 字段一致');
+    assert_has_key('body', $show['body']['data'], '单条带渲染后的正文');
+
+    assert_status(428, raw('PATCH', "/v3/terms/{$term['id']}", null, ['meaning' => '改'], $token), '不带 If-Match');
+    assert_status(412, raw('PATCH', "/v3/terms/{$term['id']}", null, ['meaning' => '改'], $token, ['If-Match' => '"0.0"']), '旧 etag');
+    $word = raw('PATCH', "/v3/terms/{$term['id']}", null, ['word' => 'other'], $token, ['If-Match' => $term['etag']]);
+    assert_status(422, $word, '词头不能改');
+    assert_field_error('word', $word, '词头不能改');
+
+    $update = raw('PATCH', "/v3/terms/{$term['id']}", null, ['meaning' => '改过的'], $token, ['If-Match' => $term['etag']]);
+    assert_status(200, $update, '改术语');
+    assert_eq('改过的', $update['body']['data']['meaning'] ?? null, '改后的释义');
+
+    $delete = request(fn () => api(TermsApi::class, $token)->deleteApiV3TermsTermWithHttpInfo($term['id']));
+    assert_status(200, $delete, '删术语');
+    assert_status(404, raw('GET', "/v3/terms/{$term['id']}", null, null, $token), '删后再看');
+
+    assert_status(200, request(fn () => api(ChannelsApi::class, $token)->deleteApiV3ChannelsChannelWithHttpInfo($channelId)), '删临时 channel');
+});

+ 35 - 0
api-test/cases/17_glossaries.php

@@ -0,0 +1,35 @@
+<?php
+
+use \WikipaliApi\Api\GlossariesApi;
+
+/*
+ * 术语词汇表:GET /v3/glossaries/{grammar|community}(取代 v2 term-vocabulary)。只读、整表、公开。
+ * 各服务器的数据量不同,只核对形状与回退规则;排序、已删条目、不暴露自增 id 由 api-v13 的 GlossaryV3Test 覆盖。
+ */
+
+test('GET /v3/glossaries/community?lang=zh-Hans → 200,整表带 meta', function () {
+    $res = request(fn () => api(GlossariesApi::class)->getApiV3GlossariesKindWithHttpInfo('community', 'zh-Hans'));
+    assert_status(200, $res, 'community glossary');
+    foreach (['kind', 'lang', 'total'] as $key) {
+        assert_has_key($key, $res['body']['meta'], 'glossary meta');
+    }
+    assert_eq('community', $res['body']['meta']['kind'], 'meta.kind');
+    assert_eq(count($res['body']['data']), $res['body']['meta']['total'], '整表不分页:total 与条数相等');
+    $first = $res['body']['data'][0] ?? null;
+    if ($first) {
+        assert_eq(['id', 'word', 'tag', 'meaning', 'other_meaning'], array_keys($first), '条目字段');
+    }
+});
+
+test('GET /v3/glossaries/grammar?lang=xx(没有这种语言的表)→ 200,回退到 en', function () {
+    $res = raw('GET', '/v3/glossaries/grammar', ['lang' => 'xx']);
+    assert_status(200, $res, 'grammar glossary 回退');
+    assert_eq('en', $res['body']['meta']['lang'] ?? null, '回退语言');
+});
+
+test('GET /v3/glossaries/{非法 kind} → 404;lang 格式不对 → 422', function () {
+    assert_status(404, raw('GET', '/v3/glossaries/other'), '非法 kind');
+    $bad = raw('GET', '/v3/glossaries/community', ['lang' => '../x']);
+    assert_status(422, $bad, 'lang 格式不对');
+    assert_field_error('lang', $bad, 'lang 格式不对');
+});

+ 65 - 0
api-test/cases/18_term_exchange.php

@@ -0,0 +1,65 @@
+<?php
+
+use \WikipaliApi\Api\ChannelsApi;
+use \WikipaliApi\Api\StudiosApi;
+use \WikipaliApi\Model\PostApiV3ChannelsChannelTermsRequest;
+use \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest;
+use GuzzleHttp\Client;
+
+/*
+ * 术语导入 / 导出(xlsx,取代 v2 terms-export / terms-import):
+ * 导出 = 列表接口带 Accept: xlsx;导入 = POST /v3/channels/{c}/terms/imports(multipart,部分成功)。
+ * 用临时 channel(e2e-tmp-exchange-*):建一条术语 → 导出 → 原样导入(全部「未变」)→ 删 channel。
+ * 逐行规则(etag、word 不可改、studio 的 channel_id / language)由 api-v13 的 TermExchangeV3Test 覆盖。
+ */
+
+const TERM_XLSX = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
+
+test('POST /v3/channels/{channel}/terms/imports(无 token)→ 401', function () {
+    $res = raw('POST', '/v3/channels/'.fixtures()['channel'].'/terms/imports', null, []);
+    assert_status(401, $res, 'imports 无 token');
+});
+
+test('术语导出 → 原样导入一轮:xlsx 200 → 导入 200(未变 1)→ 坏文件 422', function () {
+    $token = required_token();
+    $me = raw('GET', '/v3/me', null, null, $token);
+    $body = new PostApiV3StudiosStudioChannelsRequest();
+    $body->setName('e2e-tmp-exchange-'.time());
+    $body->setType('translation');
+    $body->setLang('zh-Hans');
+    $channel = request(fn () => api(StudiosApi::class, $token)->postApiV3StudiosStudioChannelsWithHttpInfo($me['body']['data']['id'], $body));
+    assert_status(201, $channel, '建临时 channel');
+    $channelId = $channel['body']['data']['id'];
+
+    $term = new PostApiV3ChannelsChannelTermsRequest();
+    $term->setWord('apiexchange');
+    $term->setMeaning('导入导出测试');
+    $created = request(fn () => api(ChannelsApi::class, $token)->postApiV3ChannelsChannelTermsWithHttpInfo($channelId, $term));
+    assert_status(201, $created, '建术语');
+
+    // 导出:生成客户端只认 JSON,这里直接拿二进制
+    $http = new Client(['timeout' => config()['timeout'], 'http_errors' => false]);
+    $export = $http->get(config()['base_url']."/v3/channels/{$channelId}/terms", [
+        'headers' => ['Accept' => TERM_XLSX, 'Authorization' => "Bearer {$token}"],
+    ]);
+    assert_eq(200, $export->getStatusCode(), '导出状态码');
+    assert_eq(TERM_XLSX, $export->getHeaderLine('Content-Type'), '导出的 Content-Type');
+    $content = (string) $export->getBody();
+    assert_eq('PK', substr($content, 0, 2), '导出的是 xlsx(zip)');
+
+    $path = sys_get_temp_dir().'/api-test-terms-'.time().'.xlsx';
+    file_put_contents($path, $content);
+    $import = request(fn () => api(ChannelsApi::class, $token)->postApiV3ChannelsChannelTermsImportsWithHttpInfo($channelId, new \SplFileObject($path)));
+    assert_status(200, $import, '原样导入');
+    assert_eq(['created' => 0, 'updated' => 0, 'unchanged' => 1], array_intersect_key($import['body']['data'], ['created' => 0, 'updated' => 0, 'unchanged' => 0]), '原样导入全部未变');
+    assert_eq([], $import['body']['data']['errors'], '没有跳过的行');
+
+    file_put_contents($path, 'not a spreadsheet');
+    $bad = request(fn () => api(ChannelsApi::class, $token)->postApiV3ChannelsChannelTermsImportsWithHttpInfo($channelId, new \SplFileObject($path)));
+    assert_status(422, $bad, '坏文件');
+    unlink($path);
+
+    // channel 里有术语不能删:先删术语
+    assert_status(200, raw('DELETE', '/v3/terms/'.$created['body']['data']['id'], null, null, $token), '删术语');
+    assert_status(200, request(fn () => api(ChannelsApi::class, $token)->deleteApiV3ChannelsChannelWithHttpInfo($channelId)), '删临时 channel');
+});

+ 48 - 0
api-test/client/.openapi-generator/FILES

@@ -16,6 +16,7 @@ docs/Api/ChannelsApi.md
 docs/Api/CreditPolicyApi.md
 docs/Api/CreditPolicyApi.md
 docs/Api/DiscussionsApi.md
 docs/Api/DiscussionsApi.md
 docs/Api/EmailCertificationsApi.md
 docs/Api/EmailCertificationsApi.md
+docs/Api/GlossariesApi.md
 docs/Api/GroupsApi.md
 docs/Api/GroupsApi.md
 docs/Api/HeartbeatApi.md
 docs/Api/HeartbeatApi.md
 docs/Api/InvitesApi.md
 docs/Api/InvitesApi.md
@@ -28,6 +29,7 @@ docs/Api/SearchApi.md
 docs/Api/SearchSuggestApi.md
 docs/Api/SearchSuggestApi.md
 docs/Api/SessionsApi.md
 docs/Api/SessionsApi.md
 docs/Api/StudiosApi.md
 docs/Api/StudiosApi.md
+docs/Api/TermsApi.md
 docs/Api/TipitakaChannelsApi.md
 docs/Api/TipitakaChannelsApi.md
 docs/Api/TipitakaChapterChannelsApi.md
 docs/Api/TipitakaChapterChannelsApi.md
 docs/Api/TipitakaChaptersApi.md
 docs/Api/TipitakaChaptersApi.md
@@ -78,6 +80,10 @@ docs/Model/GetApiV3ChannelsChannelLinks200Response.md
 docs/Model/GetApiV3ChannelsChannelLinks200ResponseData.md
 docs/Model/GetApiV3ChannelsChannelLinks200ResponseData.md
 docs/Model/GetApiV3ChannelsChannelLinks200ResponseDataDerivedFrom.md
 docs/Model/GetApiV3ChannelsChannelLinks200ResponseDataDerivedFrom.md
 docs/Model/GetApiV3ChannelsChannelLinks200ResponseDataFallbackInner.md
 docs/Model/GetApiV3ChannelsChannelLinks200ResponseDataFallbackInner.md
+docs/Model/GetApiV3ChannelsChannelTerms200Response.md
+docs/Model/GetApiV3ChannelsChannelTerms200ResponseDataInner.md
+docs/Model/GetApiV3ChannelsChannelTerms200ResponseDataInnerAbilities.md
+docs/Model/GetApiV3ChannelsChannelTerms200ResponseDataInnerChannel.md
 docs/Model/GetApiV3CreditPolicy200Response.md
 docs/Model/GetApiV3CreditPolicy200Response.md
 docs/Model/GetApiV3CreditPolicy200ResponseData.md
 docs/Model/GetApiV3CreditPolicy200ResponseData.md
 docs/Model/GetApiV3CreditPolicy200ResponseDataDailyFree.md
 docs/Model/GetApiV3CreditPolicy200ResponseDataDailyFree.md
@@ -90,6 +96,9 @@ docs/Model/GetApiV3Discussions200ResponseDataInnerSentence.md
 docs/Model/GetApiV3DiscussionsSummary200Response.md
 docs/Model/GetApiV3DiscussionsSummary200Response.md
 docs/Model/GetApiV3DiscussionsSummary200ResponseData.md
 docs/Model/GetApiV3DiscussionsSummary200ResponseData.md
 docs/Model/GetApiV3DiscussionsSummary200ResponseDataStatusCounts.md
 docs/Model/GetApiV3DiscussionsSummary200ResponseDataStatusCounts.md
+docs/Model/GetApiV3GlossariesKind200Response.md
+docs/Model/GetApiV3GlossariesKind200ResponseDataInner.md
+docs/Model/GetApiV3GlossariesKind200ResponseMeta.md
 docs/Model/GetApiV3Groups200Response.md
 docs/Model/GetApiV3Groups200Response.md
 docs/Model/GetApiV3Groups200ResponseDataInner.md
 docs/Model/GetApiV3Groups200ResponseDataInner.md
 docs/Model/GetApiV3GroupsGroupMembers200Response.md
 docs/Model/GetApiV3GroupsGroupMembers200Response.md
@@ -150,6 +159,7 @@ docs/Model/PatchApiV3GroupsGroupMembersMemberRequest.md
 docs/Model/PatchApiV3GroupsGroupRequest.md
 docs/Model/PatchApiV3GroupsGroupRequest.md
 docs/Model/PatchApiV3MeAgentThreadsThreadRequest.md
 docs/Model/PatchApiV3MeAgentThreadsThreadRequest.md
 docs/Model/PatchApiV3PasswordResetsTokenRequest.md
 docs/Model/PatchApiV3PasswordResetsTokenRequest.md
+docs/Model/PatchApiV3TermsTermRequest.md
 docs/Model/PostApiV3AgentCharges200Response.md
 docs/Model/PostApiV3AgentCharges200Response.md
 docs/Model/PostApiV3AgentCharges200ResponseData.md
 docs/Model/PostApiV3AgentCharges200ResponseData.md
 docs/Model/PostApiV3AgentChargesRequest.md
 docs/Model/PostApiV3AgentChargesRequest.md
@@ -168,6 +178,11 @@ docs/Model/PostApiV3AgentTracesRequest.md
 docs/Model/PostApiV3ChannelsBatchProgress200Response.md
 docs/Model/PostApiV3ChannelsBatchProgress200Response.md
 docs/Model/PostApiV3ChannelsBatchProgress200ResponseDataInner.md
 docs/Model/PostApiV3ChannelsBatchProgress200ResponseDataInner.md
 docs/Model/PostApiV3ChannelsBatchProgressRequest.md
 docs/Model/PostApiV3ChannelsBatchProgressRequest.md
+docs/Model/PostApiV3ChannelsChannelTerms200Response.md
+docs/Model/PostApiV3ChannelsChannelTermsImports200Response.md
+docs/Model/PostApiV3ChannelsChannelTermsImports200ResponseData.md
+docs/Model/PostApiV3ChannelsChannelTermsImports200ResponseDataErrorsInner.md
+docs/Model/PostApiV3ChannelsChannelTermsRequest.md
 docs/Model/PostApiV3Discussions200Response.md
 docs/Model/PostApiV3Discussions200Response.md
 docs/Model/PostApiV3DiscussionsBatchCount200Response.md
 docs/Model/PostApiV3DiscussionsBatchCount200Response.md
 docs/Model/PostApiV3DiscussionsBatchCount200ResponseDataInner.md
 docs/Model/PostApiV3DiscussionsBatchCount200ResponseDataInner.md
@@ -194,6 +209,7 @@ docs/Model/PostApiV3Sessions200Response.md
 docs/Model/PostApiV3Sessions200ResponseData.md
 docs/Model/PostApiV3Sessions200ResponseData.md
 docs/Model/PostApiV3SessionsRequest.md
 docs/Model/PostApiV3SessionsRequest.md
 docs/Model/PostApiV3StudiosStudioChannelsRequest.md
 docs/Model/PostApiV3StudiosStudioChannelsRequest.md
+docs/Model/PostApiV3StudiosStudioTermsRequest.md
 docs/Model/PostApiV3Users200Response.md
 docs/Model/PostApiV3Users200Response.md
 docs/Model/PostApiV3Users200ResponseData.md
 docs/Model/PostApiV3Users200ResponseData.md
 docs/Model/PostApiV3UsersRequest.md
 docs/Model/PostApiV3UsersRequest.md
@@ -211,6 +227,7 @@ lib/Api/ChannelsApi.php
 lib/Api/CreditPolicyApi.php
 lib/Api/CreditPolicyApi.php
 lib/Api/DiscussionsApi.php
 lib/Api/DiscussionsApi.php
 lib/Api/EmailCertificationsApi.php
 lib/Api/EmailCertificationsApi.php
+lib/Api/GlossariesApi.php
 lib/Api/GroupsApi.php
 lib/Api/GroupsApi.php
 lib/Api/HeartbeatApi.php
 lib/Api/HeartbeatApi.php
 lib/Api/InvitesApi.php
 lib/Api/InvitesApi.php
@@ -223,6 +240,7 @@ lib/Api/SearchApi.php
 lib/Api/SearchSuggestApi.php
 lib/Api/SearchSuggestApi.php
 lib/Api/SessionsApi.php
 lib/Api/SessionsApi.php
 lib/Api/StudiosApi.php
 lib/Api/StudiosApi.php
+lib/Api/TermsApi.php
 lib/Api/TipitakaChannelsApi.php
 lib/Api/TipitakaChannelsApi.php
 lib/Api/TipitakaChapterChannelsApi.php
 lib/Api/TipitakaChapterChannelsApi.php
 lib/Api/TipitakaChaptersApi.php
 lib/Api/TipitakaChaptersApi.php
@@ -277,6 +295,10 @@ lib/Model/GetApiV3ChannelsChannelLinks200Response.php
 lib/Model/GetApiV3ChannelsChannelLinks200ResponseData.php
 lib/Model/GetApiV3ChannelsChannelLinks200ResponseData.php
 lib/Model/GetApiV3ChannelsChannelLinks200ResponseDataDerivedFrom.php
 lib/Model/GetApiV3ChannelsChannelLinks200ResponseDataDerivedFrom.php
 lib/Model/GetApiV3ChannelsChannelLinks200ResponseDataFallbackInner.php
 lib/Model/GetApiV3ChannelsChannelLinks200ResponseDataFallbackInner.php
+lib/Model/GetApiV3ChannelsChannelTerms200Response.php
+lib/Model/GetApiV3ChannelsChannelTerms200ResponseDataInner.php
+lib/Model/GetApiV3ChannelsChannelTerms200ResponseDataInnerAbilities.php
+lib/Model/GetApiV3ChannelsChannelTerms200ResponseDataInnerChannel.php
 lib/Model/GetApiV3CreditPolicy200Response.php
 lib/Model/GetApiV3CreditPolicy200Response.php
 lib/Model/GetApiV3CreditPolicy200ResponseData.php
 lib/Model/GetApiV3CreditPolicy200ResponseData.php
 lib/Model/GetApiV3CreditPolicy200ResponseDataDailyFree.php
 lib/Model/GetApiV3CreditPolicy200ResponseDataDailyFree.php
@@ -289,6 +311,9 @@ lib/Model/GetApiV3Discussions200ResponseDataInnerSentence.php
 lib/Model/GetApiV3DiscussionsSummary200Response.php
 lib/Model/GetApiV3DiscussionsSummary200Response.php
 lib/Model/GetApiV3DiscussionsSummary200ResponseData.php
 lib/Model/GetApiV3DiscussionsSummary200ResponseData.php
 lib/Model/GetApiV3DiscussionsSummary200ResponseDataStatusCounts.php
 lib/Model/GetApiV3DiscussionsSummary200ResponseDataStatusCounts.php
+lib/Model/GetApiV3GlossariesKind200Response.php
+lib/Model/GetApiV3GlossariesKind200ResponseDataInner.php
+lib/Model/GetApiV3GlossariesKind200ResponseMeta.php
 lib/Model/GetApiV3Groups200Response.php
 lib/Model/GetApiV3Groups200Response.php
 lib/Model/GetApiV3Groups200ResponseDataInner.php
 lib/Model/GetApiV3Groups200ResponseDataInner.php
 lib/Model/GetApiV3GroupsGroupMembers200Response.php
 lib/Model/GetApiV3GroupsGroupMembers200Response.php
@@ -350,6 +375,7 @@ lib/Model/PatchApiV3GroupsGroupMembersMemberRequest.php
 lib/Model/PatchApiV3GroupsGroupRequest.php
 lib/Model/PatchApiV3GroupsGroupRequest.php
 lib/Model/PatchApiV3MeAgentThreadsThreadRequest.php
 lib/Model/PatchApiV3MeAgentThreadsThreadRequest.php
 lib/Model/PatchApiV3PasswordResetsTokenRequest.php
 lib/Model/PatchApiV3PasswordResetsTokenRequest.php
+lib/Model/PatchApiV3TermsTermRequest.php
 lib/Model/PostApiV3AgentCharges200Response.php
 lib/Model/PostApiV3AgentCharges200Response.php
 lib/Model/PostApiV3AgentCharges200ResponseData.php
 lib/Model/PostApiV3AgentCharges200ResponseData.php
 lib/Model/PostApiV3AgentChargesRequest.php
 lib/Model/PostApiV3AgentChargesRequest.php
@@ -368,6 +394,11 @@ lib/Model/PostApiV3AgentTracesRequest.php
 lib/Model/PostApiV3ChannelsBatchProgress200Response.php
 lib/Model/PostApiV3ChannelsBatchProgress200Response.php
 lib/Model/PostApiV3ChannelsBatchProgress200ResponseDataInner.php
 lib/Model/PostApiV3ChannelsBatchProgress200ResponseDataInner.php
 lib/Model/PostApiV3ChannelsBatchProgressRequest.php
 lib/Model/PostApiV3ChannelsBatchProgressRequest.php
+lib/Model/PostApiV3ChannelsChannelTerms200Response.php
+lib/Model/PostApiV3ChannelsChannelTermsImports200Response.php
+lib/Model/PostApiV3ChannelsChannelTermsImports200ResponseData.php
+lib/Model/PostApiV3ChannelsChannelTermsImports200ResponseDataErrorsInner.php
+lib/Model/PostApiV3ChannelsChannelTermsRequest.php
 lib/Model/PostApiV3Discussions200Response.php
 lib/Model/PostApiV3Discussions200Response.php
 lib/Model/PostApiV3DiscussionsBatchCount200Response.php
 lib/Model/PostApiV3DiscussionsBatchCount200Response.php
 lib/Model/PostApiV3DiscussionsBatchCount200ResponseDataInner.php
 lib/Model/PostApiV3DiscussionsBatchCount200ResponseDataInner.php
@@ -394,6 +425,7 @@ lib/Model/PostApiV3Sessions200Response.php
 lib/Model/PostApiV3Sessions200ResponseData.php
 lib/Model/PostApiV3Sessions200ResponseData.php
 lib/Model/PostApiV3SessionsRequest.php
 lib/Model/PostApiV3SessionsRequest.php
 lib/Model/PostApiV3StudiosStudioChannelsRequest.php
 lib/Model/PostApiV3StudiosStudioChannelsRequest.php
+lib/Model/PostApiV3StudiosStudioTermsRequest.php
 lib/Model/PostApiV3Users200Response.php
 lib/Model/PostApiV3Users200Response.php
 lib/Model/PostApiV3Users200ResponseData.php
 lib/Model/PostApiV3Users200ResponseData.php
 lib/Model/PostApiV3UsersRequest.php
 lib/Model/PostApiV3UsersRequest.php
@@ -412,6 +444,7 @@ test/Api/ChannelsApiTest.php
 test/Api/CreditPolicyApiTest.php
 test/Api/CreditPolicyApiTest.php
 test/Api/DiscussionsApiTest.php
 test/Api/DiscussionsApiTest.php
 test/Api/EmailCertificationsApiTest.php
 test/Api/EmailCertificationsApiTest.php
+test/Api/GlossariesApiTest.php
 test/Api/GroupsApiTest.php
 test/Api/GroupsApiTest.php
 test/Api/HeartbeatApiTest.php
 test/Api/HeartbeatApiTest.php
 test/Api/InvitesApiTest.php
 test/Api/InvitesApiTest.php
@@ -424,6 +457,7 @@ test/Api/SearchApiTest.php
 test/Api/SearchSuggestApiTest.php
 test/Api/SearchSuggestApiTest.php
 test/Api/SessionsApiTest.php
 test/Api/SessionsApiTest.php
 test/Api/StudiosApiTest.php
 test/Api/StudiosApiTest.php
+test/Api/TermsApiTest.php
 test/Api/TipitakaChannelsApiTest.php
 test/Api/TipitakaChannelsApiTest.php
 test/Api/TipitakaChapterChannelsApiTest.php
 test/Api/TipitakaChapterChannelsApiTest.php
 test/Api/TipitakaChaptersApiTest.php
 test/Api/TipitakaChaptersApiTest.php
@@ -474,6 +508,10 @@ test/Model/GetApiV3ChannelsChannelLinks200ResponseDataDerivedFromTest.php
 test/Model/GetApiV3ChannelsChannelLinks200ResponseDataFallbackInnerTest.php
 test/Model/GetApiV3ChannelsChannelLinks200ResponseDataFallbackInnerTest.php
 test/Model/GetApiV3ChannelsChannelLinks200ResponseDataTest.php
 test/Model/GetApiV3ChannelsChannelLinks200ResponseDataTest.php
 test/Model/GetApiV3ChannelsChannelLinks200ResponseTest.php
 test/Model/GetApiV3ChannelsChannelLinks200ResponseTest.php
+test/Model/GetApiV3ChannelsChannelTerms200ResponseDataInnerAbilitiesTest.php
+test/Model/GetApiV3ChannelsChannelTerms200ResponseDataInnerChannelTest.php
+test/Model/GetApiV3ChannelsChannelTerms200ResponseDataInnerTest.php
+test/Model/GetApiV3ChannelsChannelTerms200ResponseTest.php
 test/Model/GetApiV3CreditPolicy200ResponseDataDailyFreeTest.php
 test/Model/GetApiV3CreditPolicy200ResponseDataDailyFreeTest.php
 test/Model/GetApiV3CreditPolicy200ResponseDataEarnReadingTest.php
 test/Model/GetApiV3CreditPolicy200ResponseDataEarnReadingTest.php
 test/Model/GetApiV3CreditPolicy200ResponseDataEarnTest.php
 test/Model/GetApiV3CreditPolicy200ResponseDataEarnTest.php
@@ -486,6 +524,9 @@ test/Model/GetApiV3Discussions200ResponseTest.php
 test/Model/GetApiV3DiscussionsSummary200ResponseDataStatusCountsTest.php
 test/Model/GetApiV3DiscussionsSummary200ResponseDataStatusCountsTest.php
 test/Model/GetApiV3DiscussionsSummary200ResponseDataTest.php
 test/Model/GetApiV3DiscussionsSummary200ResponseDataTest.php
 test/Model/GetApiV3DiscussionsSummary200ResponseTest.php
 test/Model/GetApiV3DiscussionsSummary200ResponseTest.php
+test/Model/GetApiV3GlossariesKind200ResponseDataInnerTest.php
+test/Model/GetApiV3GlossariesKind200ResponseMetaTest.php
+test/Model/GetApiV3GlossariesKind200ResponseTest.php
 test/Model/GetApiV3Groups200ResponseDataInnerTest.php
 test/Model/GetApiV3Groups200ResponseDataInnerTest.php
 test/Model/GetApiV3Groups200ResponseTest.php
 test/Model/GetApiV3Groups200ResponseTest.php
 test/Model/GetApiV3GroupsGroupMembers200ResponseDataInnerTest.php
 test/Model/GetApiV3GroupsGroupMembers200ResponseDataInnerTest.php
@@ -546,6 +587,7 @@ test/Model/PatchApiV3GroupsGroupMembersMemberRequestTest.php
 test/Model/PatchApiV3GroupsGroupRequestTest.php
 test/Model/PatchApiV3GroupsGroupRequestTest.php
 test/Model/PatchApiV3MeAgentThreadsThreadRequestTest.php
 test/Model/PatchApiV3MeAgentThreadsThreadRequestTest.php
 test/Model/PatchApiV3PasswordResetsTokenRequestTest.php
 test/Model/PatchApiV3PasswordResetsTokenRequestTest.php
+test/Model/PatchApiV3TermsTermRequestTest.php
 test/Model/PostApiV3AgentCharges200ResponseDataTest.php
 test/Model/PostApiV3AgentCharges200ResponseDataTest.php
 test/Model/PostApiV3AgentCharges200ResponseTest.php
 test/Model/PostApiV3AgentCharges200ResponseTest.php
 test/Model/PostApiV3AgentChargesRequestTest.php
 test/Model/PostApiV3AgentChargesRequestTest.php
@@ -564,6 +606,11 @@ test/Model/PostApiV3AgentTracesRequestTest.php
 test/Model/PostApiV3ChannelsBatchProgress200ResponseDataInnerTest.php
 test/Model/PostApiV3ChannelsBatchProgress200ResponseDataInnerTest.php
 test/Model/PostApiV3ChannelsBatchProgress200ResponseTest.php
 test/Model/PostApiV3ChannelsBatchProgress200ResponseTest.php
 test/Model/PostApiV3ChannelsBatchProgressRequestTest.php
 test/Model/PostApiV3ChannelsBatchProgressRequestTest.php
+test/Model/PostApiV3ChannelsChannelTerms200ResponseTest.php
+test/Model/PostApiV3ChannelsChannelTermsImports200ResponseDataErrorsInnerTest.php
+test/Model/PostApiV3ChannelsChannelTermsImports200ResponseDataTest.php
+test/Model/PostApiV3ChannelsChannelTermsImports200ResponseTest.php
+test/Model/PostApiV3ChannelsChannelTermsRequestTest.php
 test/Model/PostApiV3Discussions200ResponseTest.php
 test/Model/PostApiV3Discussions200ResponseTest.php
 test/Model/PostApiV3DiscussionsBatchCount200ResponseDataInnerTest.php
 test/Model/PostApiV3DiscussionsBatchCount200ResponseDataInnerTest.php
 test/Model/PostApiV3DiscussionsBatchCount200ResponseTest.php
 test/Model/PostApiV3DiscussionsBatchCount200ResponseTest.php
@@ -590,6 +637,7 @@ test/Model/PostApiV3Sessions200ResponseDataTest.php
 test/Model/PostApiV3Sessions200ResponseTest.php
 test/Model/PostApiV3Sessions200ResponseTest.php
 test/Model/PostApiV3SessionsRequestTest.php
 test/Model/PostApiV3SessionsRequestTest.php
 test/Model/PostApiV3StudiosStudioChannelsRequestTest.php
 test/Model/PostApiV3StudiosStudioChannelsRequestTest.php
+test/Model/PostApiV3StudiosStudioTermsRequestTest.php
 test/Model/PostApiV3Users200ResponseDataTest.php
 test/Model/PostApiV3Users200ResponseDataTest.php
 test/Model/PostApiV3Users200ResponseTest.php
 test/Model/PostApiV3Users200ResponseTest.php
 test/Model/PostApiV3UsersRequestTest.php
 test/Model/PostApiV3UsersRequestTest.php

Plik diff jest za duży
+ 1225 - 165
api-test/client/lib/Api/ChannelsApi.php


+ 502 - 0
api-test/client/lib/Api/GlossariesApi.php

@@ -0,0 +1,502 @@
+<?php
+/**
+ * GlossariesApi
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Api;
+
+use GuzzleHttp\Client;
+use GuzzleHttp\ClientInterface;
+use GuzzleHttp\Exception\ConnectException;
+use GuzzleHttp\Exception\RequestException;
+use GuzzleHttp\Psr7\MultipartStream;
+use GuzzleHttp\Psr7\Request;
+use GuzzleHttp\RequestOptions;
+use Psr\Http\Message\RequestInterface;
+use Psr\Http\Message\ResponseInterface;
+use WikipaliApi\ApiException;
+use WikipaliApi\Configuration;
+use WikipaliApi\FormDataProcessor;
+use WikipaliApi\HeaderSelector;
+use WikipaliApi\ObjectSerializer;
+
+/**
+ * GlossariesApi Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+class GlossariesApi
+{
+    /**
+     * @var ClientInterface
+     */
+    protected $client;
+
+    /**
+     * @var Configuration
+     */
+    protected $config;
+
+    /**
+     * @var HeaderSelector
+     */
+    protected $headerSelector;
+
+    /**
+     * @var int Host index
+     */
+    protected $hostIndex;
+
+    /** @var string[] $contentTypes **/
+    public const contentTypes = [
+        'getApiV3GlossariesKind' => [
+            'application/json',
+        ],
+    ];
+
+    /**
+     * @param ClientInterface $client
+     * @param Configuration   $config
+     * @param HeaderSelector  $selector
+     * @param int             $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec
+     */
+    public function __construct(
+        ?ClientInterface $client = null,
+        ?Configuration $config = null,
+        ?HeaderSelector $selector = null,
+        int $hostIndex = 0
+    ) {
+        $this->client = $client ?: new Client();
+        $this->config = $config ?: Configuration::getDefaultConfiguration();
+        $this->headerSelector = $selector ?: new HeaderSelector();
+        $this->hostIndex = $hostIndex;
+    }
+
+    /**
+     * Set the host index
+     *
+     * @param int $hostIndex Host index (required)
+     */
+    public function setHostIndex($hostIndex): void
+    {
+        $this->hostIndex = $hostIndex;
+    }
+
+    /**
+     * Get the host index
+     *
+     * @return int Host index
+     */
+    public function getHostIndex()
+    {
+        return $this->hostIndex;
+    }
+
+    /**
+     * @return Configuration
+     */
+    public function getConfig()
+    {
+        return $this->config;
+    }
+
+    /**
+     * Operation getApiV3GlossariesKind
+     *
+     * 术语词汇表
+     *
+     * @param  string $kind 哪张表:grammar 语法术语,community 社区译名 (required)
+     * @param  string|null $lang 语言,如 zh-Hans。缺省用界面语言(Accept-Language 协商的结果) (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3GlossariesKind'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return \WikipaliApi\Model\GetApiV3GlossariesKind200Response|\WikipaliApi\Model\ProblemDetails
+     */
+    public function getApiV3GlossariesKind($kind, $lang = null, string $contentType = self::contentTypes['getApiV3GlossariesKind'][0])
+    {
+        list($response) = $this->getApiV3GlossariesKindWithHttpInfo($kind, $lang, $contentType);
+        return $response;
+    }
+
+    /**
+     * Operation getApiV3GlossariesKindWithHttpInfo
+     *
+     * 术语词汇表
+     *
+     * @param  string $kind 哪张表:grammar 语法术语,community 社区译名 (required)
+     * @param  string|null $lang 语言,如 zh-Hans。缺省用界面语言(Accept-Language 协商的结果) (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3GlossariesKind'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return array of \WikipaliApi\Model\GetApiV3GlossariesKind200Response|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     */
+    public function getApiV3GlossariesKindWithHttpInfo($kind, $lang = null, string $contentType = self::contentTypes['getApiV3GlossariesKind'][0])
+    {
+        $request = $this->getApiV3GlossariesKindRequest($kind, $lang, $contentType);
+
+        try {
+            $options = $this->createHttpClientOption();
+            try {
+                $response = $this->client->send($request, $options);
+            } catch (RequestException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
+                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
+                );
+            } catch (ConnectException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    null,
+                    null
+                );
+            }
+
+            $statusCode = $response->getStatusCode();
+
+
+            switch($statusCode) {
+                case 200:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\GetApiV3GlossariesKind200Response',
+                        $request,
+                        $response,
+                    );
+                case 422:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+            }
+
+            
+
+            if ($statusCode < 200 || $statusCode > 299) {
+                throw new ApiException(
+                    sprintf(
+                        '[%d] Error connecting to the API (%s)',
+                        $statusCode,
+                        (string) $request->getUri()
+                    ),
+                    $statusCode,
+                    $response->getHeaders(),
+                    (string) $response->getBody()
+                );
+            }
+
+            return $this->handleResponseWithDataType(
+                '\WikipaliApi\Model\GetApiV3GlossariesKind200Response',
+                $request,
+                $response,
+            );
+        } catch (ApiException $e) {
+            switch ($e->getCode()) {
+                case 200:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\GetApiV3GlossariesKind200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 422:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+            }
+        
+
+            throw $e;
+        }
+    }
+
+    /**
+     * Operation getApiV3GlossariesKindAsync
+     *
+     * 术语词汇表
+     *
+     * @param  string $kind 哪张表:grammar 语法术语,community 社区译名 (required)
+     * @param  string|null $lang 语言,如 zh-Hans。缺省用界面语言(Accept-Language 协商的结果) (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3GlossariesKind'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function getApiV3GlossariesKindAsync($kind, $lang = null, string $contentType = self::contentTypes['getApiV3GlossariesKind'][0])
+    {
+        return $this->getApiV3GlossariesKindAsyncWithHttpInfo($kind, $lang, $contentType)
+            ->then(
+                function ($response) {
+                    return $response[0];
+                }
+            );
+    }
+
+    /**
+     * Operation getApiV3GlossariesKindAsyncWithHttpInfo
+     *
+     * 术语词汇表
+     *
+     * @param  string $kind 哪张表:grammar 语法术语,community 社区译名 (required)
+     * @param  string|null $lang 语言,如 zh-Hans。缺省用界面语言(Accept-Language 协商的结果) (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3GlossariesKind'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function getApiV3GlossariesKindAsyncWithHttpInfo($kind, $lang = null, string $contentType = self::contentTypes['getApiV3GlossariesKind'][0])
+    {
+        $returnType = '\WikipaliApi\Model\GetApiV3GlossariesKind200Response';
+        $request = $this->getApiV3GlossariesKindRequest($kind, $lang, $contentType);
+
+        return $this->client
+            ->sendAsync($request, $this->createHttpClientOption())
+            ->then(
+                function ($response) use ($returnType) {
+                    if ($returnType === '\SplFileObject') {
+                        $content = $response->getBody(); //stream goes to serializer
+                    } else {
+                        $content = (string) $response->getBody();
+                        if ($returnType !== 'string') {
+                            $content = json_decode($content);
+                        }
+                    }
+
+                    return [
+                        ObjectSerializer::deserialize($content, $returnType, []),
+                        $response->getStatusCode(),
+                        $response->getHeaders()
+                    ];
+                },
+                function ($exception) {
+                    $response = $exception->getResponse();
+                    $statusCode = $response->getStatusCode();
+                    throw new ApiException(
+                        sprintf(
+                            '[%d] Error connecting to the API (%s)',
+                            $statusCode,
+                            $exception->getRequest()->getUri()
+                        ),
+                        $statusCode,
+                        $response->getHeaders(),
+                        (string) $response->getBody()
+                    );
+                }
+            );
+    }
+
+    /**
+     * Create request for operation 'getApiV3GlossariesKind'
+     *
+     * @param  string $kind 哪张表:grammar 语法术语,community 社区译名 (required)
+     * @param  string|null $lang 语言,如 zh-Hans。缺省用界面语言(Accept-Language 协商的结果) (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3GlossariesKind'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Psr7\Request
+     */
+    public function getApiV3GlossariesKindRequest($kind, $lang = null, string $contentType = self::contentTypes['getApiV3GlossariesKind'][0])
+    {
+
+        // verify the required parameter 'kind' is set
+        if ($kind === null || (is_array($kind) && count($kind) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $kind when calling getApiV3GlossariesKind'
+            );
+        }
+
+
+
+        $resourcePath = '/v3/glossaries/{kind}';
+        $formParams = [];
+        $queryParams = [];
+        $headerParams = [];
+        $httpBody = '';
+        $multipart = false;
+
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $lang,
+            'lang', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+
+
+        // path params
+        if ($kind !== null) {
+            $resourcePath = str_replace(
+                '{kind}',
+                ObjectSerializer::toPathValue($kind),
+                $resourcePath
+            );
+        }
+
+
+        $headers = $this->headerSelector->selectHeaders(
+            ['application/json', 'application/problem+json', ],
+            $contentType,
+            $multipart
+        );
+
+        // for model (json/xml)
+        if (count($formParams) > 0) {
+            if ($multipart) {
+                $multipartContents = [];
+                foreach ($formParams as $formParamName => $formParamValue) {
+                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
+                    foreach ($formParamValueItems as $formParamValueItem) {
+                        $multipartContents[] = [
+                            'name' => $formParamName,
+                            'contents' => $formParamValueItem
+                        ];
+                    }
+                }
+                // for HTTP post (form)
+                $httpBody = new MultipartStream($multipartContents);
+
+            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the form parameters
+                try {
+                    $httpBody = json_encode($formParams, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                // for HTTP post (form)
+                $httpBody = ObjectSerializer::buildQuery($formParams);
+            }
+        }
+
+        // this endpoint requires Bearer authentication (access token)
+        if (!empty($this->config->getAccessToken())) {
+            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
+        }
+
+        $defaultHeaders = [];
+        if ($this->config->getUserAgent()) {
+            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
+        }
+
+        $headers = array_merge(
+            $defaultHeaders,
+            $headerParams,
+            $headers
+        );
+
+        $operationHost = $this->config->getHost();
+        $query = ObjectSerializer::buildQuery($queryParams);
+        return new Request(
+            'GET',
+            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
+            $headers,
+            $httpBody
+        );
+    }
+
+    /**
+     * Create http client option
+     *
+     * @throws \RuntimeException on file opening failure
+     * @return array of http client options
+     */
+    protected function createHttpClientOption()
+    {
+        $options = [];
+        if ($this->config->getDebug()) {
+            $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
+            if (!$options[RequestOptions::DEBUG]) {
+                throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());
+            }
+        }
+
+        if ($this->config->getCertFile()) {
+            $options[RequestOptions::CERT] = $this->config->getCertFile();
+        }
+
+        if ($this->config->getKeyFile()) {
+            $options[RequestOptions::SSL_KEY] = $this->config->getKeyFile();
+        }
+
+        return $options;
+    }
+
+    private function handleResponseWithDataType(
+        string $dataType,
+        RequestInterface $request,
+        ResponseInterface $response
+    ): array {
+        if ($dataType === '\SplFileObject') {
+            $content = $response->getBody(); //stream goes to serializer
+        } else {
+            $content = (string) $response->getBody();
+            if ($dataType !== 'string') {
+                try {
+                    $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $exception) {
+                    throw new ApiException(
+                        sprintf(
+                            'Error JSON decoding server response (%s)',
+                            $request->getUri()
+                        ),
+                        $response->getStatusCode(),
+                        $response->getHeaders(),
+                        $content
+                    );
+                }
+            }
+        }
+
+        return [
+            ObjectSerializer::deserialize($content, $dataType, []),
+            $response->getStatusCode(),
+            $response->getHeaders()
+        ];
+    }
+
+    private function responseWithinRangeCode(
+        string $rangeCode,
+        int $statusCode
+    ): bool {
+        $left = (int) ($rangeCode[0].'00');
+        $right = (int) ($rangeCode[0].'99');
+
+        return $statusCode >= $left && $statusCode <= $right;
+    }
+}

+ 1223 - 67
api-test/client/lib/Api/StudiosApi.php

@@ -77,9 +77,18 @@ class StudiosApi
         'getApiV3StudiosStudioChannels' => [
         'getApiV3StudiosStudioChannels' => [
             'application/json',
             'application/json',
         ],
         ],
+        'getApiV3StudiosStudioTerms' => [
+            'application/json',
+        ],
         'postApiV3StudiosStudioChannels' => [
         'postApiV3StudiosStudioChannels' => [
             'application/json',
             'application/json',
         ],
         ],
+        'postApiV3StudiosStudioTerms' => [
+            'application/json',
+        ],
+        'postApiV3StudiosStudioTermsImports' => [
+            'multipart/form-data',
+        ],
     ];
     ];
 
 
     /**
     /**
@@ -612,40 +621,54 @@ class StudiosApi
     }
     }
 
 
     /**
     /**
-     * Operation postApiV3StudiosStudioChannels
+     * Operation getApiV3StudiosStudioTerms
      *
      *
-     * 在 studio 名下建 channel
+     * studio 的术语列表
      *
      *
-     * @param  string $studio 用户 uuid 或团队 uuid (required)
-     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest $post_api_v3_studios_studio_channels_request post_api_v3_studios_studio_channels_request (required)
-     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioChannels'] to see the possible values for this operation
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  int|null $per_page 每页条数,最大 200 (optional, default to 20)
+     * @param  string|null $search 按词、释义搜索 (optional)
+     * @param  string|null $quality 质量;pending 含未评级的 (optional)
+     * @param  string|null $category 百科分类 (optional)
+     * @param  bool|null $general 只要 studio 级术语(不属于任何 channel) (optional)
+     * @param  string|null $order 排序字段 (optional, default to 'updated_at')
+     * @param  string|null $dir 排序方向 (optional)
+     * @param  int|null $page 页码 (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3StudiosStudioTerms'] to see the possible values for this operation
      *
      *
      * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
      * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
      * @throws \InvalidArgumentException
      * @throws \InvalidArgumentException
-     * @return \WikipaliApi\Model\GetApiV3ChannelsChannel200Response|\WikipaliApi\Model\GetApiV3ChannelsChannel200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails
+     * @return \WikipaliApi\Model\GetApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails
      */
      */
-    public function postApiV3StudiosStudioChannels($studio, $post_api_v3_studios_studio_channels_request, string $contentType = self::contentTypes['postApiV3StudiosStudioChannels'][0])
+    public function getApiV3StudiosStudioTerms($studio, $per_page = 20, $search = null, $quality = null, $category = null, $general = null, $order = 'updated_at', $dir = null, $page = null, string $contentType = self::contentTypes['getApiV3StudiosStudioTerms'][0])
     {
     {
-        list($response) = $this->postApiV3StudiosStudioChannelsWithHttpInfo($studio, $post_api_v3_studios_studio_channels_request, $contentType);
+        list($response) = $this->getApiV3StudiosStudioTermsWithHttpInfo($studio, $per_page, $search, $quality, $category, $general, $order, $dir, $page, $contentType);
         return $response;
         return $response;
     }
     }
 
 
     /**
     /**
-     * Operation postApiV3StudiosStudioChannelsWithHttpInfo
+     * Operation getApiV3StudiosStudioTermsWithHttpInfo
      *
      *
-     * 在 studio 名下建 channel
+     * studio 的术语列表
      *
      *
-     * @param  string $studio 用户 uuid 或团队 uuid (required)
-     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest $post_api_v3_studios_studio_channels_request (required)
-     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioChannels'] to see the possible values for this operation
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  int|null $per_page 每页条数,最大 200 (optional, default to 20)
+     * @param  string|null $search 按词、释义搜索 (optional)
+     * @param  string|null $quality 质量;pending 含未评级的 (optional)
+     * @param  string|null $category 百科分类 (optional)
+     * @param  bool|null $general 只要 studio 级术语(不属于任何 channel) (optional)
+     * @param  string|null $order 排序字段 (optional, default to 'updated_at')
+     * @param  string|null $dir 排序方向 (optional)
+     * @param  int|null $page 页码 (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3StudiosStudioTerms'] to see the possible values for this operation
      *
      *
      * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
      * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
      * @throws \InvalidArgumentException
      * @throws \InvalidArgumentException
-     * @return array of \WikipaliApi\Model\GetApiV3ChannelsChannel200Response|\WikipaliApi\Model\GetApiV3ChannelsChannel200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     * @return array of \WikipaliApi\Model\GetApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
      */
      */
-    public function postApiV3StudiosStudioChannelsWithHttpInfo($studio, $post_api_v3_studios_studio_channels_request, string $contentType = self::contentTypes['postApiV3StudiosStudioChannels'][0])
+    public function getApiV3StudiosStudioTermsWithHttpInfo($studio, $per_page = 20, $search = null, $quality = null, $category = null, $general = null, $order = 'updated_at', $dir = null, $page = null, string $contentType = self::contentTypes['getApiV3StudiosStudioTerms'][0])
     {
     {
-        $request = $this->postApiV3StudiosStudioChannelsRequest($studio, $post_api_v3_studios_studio_channels_request, $contentType);
+        $request = $this->getApiV3StudiosStudioTermsRequest($studio, $per_page, $search, $quality, $category, $general, $order, $dir, $page, $contentType);
 
 
         try {
         try {
             $options = $this->createHttpClientOption();
             $options = $this->createHttpClientOption();
@@ -673,13 +696,7 @@ class StudiosApi
             switch($statusCode) {
             switch($statusCode) {
                 case 200:
                 case 200:
                     return $this->handleResponseWithDataType(
                     return $this->handleResponseWithDataType(
-                        '\WikipaliApi\Model\GetApiV3ChannelsChannel200Response',
-                        $request,
-                        $response,
-                    );
-                case 201:
-                    return $this->handleResponseWithDataType(
-                        '\WikipaliApi\Model\GetApiV3ChannelsChannel200Response',
+                        '\WikipaliApi\Model\GetApiV3ChannelsChannelTerms200Response',
                         $request,
                         $request,
                         $response,
                         $response,
                     );
                     );
@@ -719,7 +736,7 @@ class StudiosApi
             }
             }
 
 
             return $this->handleResponseWithDataType(
             return $this->handleResponseWithDataType(
-                '\WikipaliApi\Model\GetApiV3ChannelsChannel200Response',
+                '\WikipaliApi\Model\GetApiV3ChannelsChannelTerms200Response',
                 $request,
                 $request,
                 $response,
                 $response,
             );
             );
@@ -728,15 +745,7 @@ class StudiosApi
                 case 200:
                 case 200:
                     $data = ObjectSerializer::deserialize(
                     $data = ObjectSerializer::deserialize(
                         $e->getResponseBody(),
                         $e->getResponseBody(),
-                        '\WikipaliApi\Model\GetApiV3ChannelsChannel200Response',
-                        $e->getResponseHeaders()
-                    );
-                    $e->setResponseObject($data);
-                    throw $e;
-                case 201:
-                    $data = ObjectSerializer::deserialize(
-                        $e->getResponseBody(),
-                        '\WikipaliApi\Model\GetApiV3ChannelsChannel200Response',
+                        '\WikipaliApi\Model\GetApiV3ChannelsChannelTerms200Response',
                         $e->getResponseHeaders()
                         $e->getResponseHeaders()
                     );
                     );
                     $e->setResponseObject($data);
                     $e->setResponseObject($data);
@@ -773,20 +782,27 @@ class StudiosApi
     }
     }
 
 
     /**
     /**
-     * Operation postApiV3StudiosStudioChannelsAsync
+     * Operation getApiV3StudiosStudioTermsAsync
      *
      *
-     * 在 studio 名下建 channel
+     * studio 的术语列表
      *
      *
-     * @param  string $studio 用户 uuid 或团队 uuid (required)
-     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest $post_api_v3_studios_studio_channels_request (required)
-     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioChannels'] to see the possible values for this operation
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  int|null $per_page 每页条数,最大 200 (optional, default to 20)
+     * @param  string|null $search 按词、释义搜索 (optional)
+     * @param  string|null $quality 质量;pending 含未评级的 (optional)
+     * @param  string|null $category 百科分类 (optional)
+     * @param  bool|null $general 只要 studio 级术语(不属于任何 channel) (optional)
+     * @param  string|null $order 排序字段 (optional, default to 'updated_at')
+     * @param  string|null $dir 排序方向 (optional)
+     * @param  int|null $page 页码 (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3StudiosStudioTerms'] to see the possible values for this operation
      *
      *
      * @throws \InvalidArgumentException
      * @throws \InvalidArgumentException
      * @return \GuzzleHttp\Promise\PromiseInterface
      * @return \GuzzleHttp\Promise\PromiseInterface
      */
      */
-    public function postApiV3StudiosStudioChannelsAsync($studio, $post_api_v3_studios_studio_channels_request, string $contentType = self::contentTypes['postApiV3StudiosStudioChannels'][0])
+    public function getApiV3StudiosStudioTermsAsync($studio, $per_page = 20, $search = null, $quality = null, $category = null, $general = null, $order = 'updated_at', $dir = null, $page = null, string $contentType = self::contentTypes['getApiV3StudiosStudioTerms'][0])
     {
     {
-        return $this->postApiV3StudiosStudioChannelsAsyncWithHttpInfo($studio, $post_api_v3_studios_studio_channels_request, $contentType)
+        return $this->getApiV3StudiosStudioTermsAsyncWithHttpInfo($studio, $per_page, $search, $quality, $category, $general, $order, $dir, $page, $contentType)
             ->then(
             ->then(
                 function ($response) {
                 function ($response) {
                     return $response[0];
                     return $response[0];
@@ -795,21 +811,28 @@ class StudiosApi
     }
     }
 
 
     /**
     /**
-     * Operation postApiV3StudiosStudioChannelsAsyncWithHttpInfo
+     * Operation getApiV3StudiosStudioTermsAsyncWithHttpInfo
      *
      *
-     * 在 studio 名下建 channel
+     * studio 的术语列表
      *
      *
-     * @param  string $studio 用户 uuid 或团队 uuid (required)
-     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest $post_api_v3_studios_studio_channels_request (required)
-     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioChannels'] to see the possible values for this operation
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  int|null $per_page 每页条数,最大 200 (optional, default to 20)
+     * @param  string|null $search 按词、释义搜索 (optional)
+     * @param  string|null $quality 质量;pending 含未评级的 (optional)
+     * @param  string|null $category 百科分类 (optional)
+     * @param  bool|null $general 只要 studio 级术语(不属于任何 channel) (optional)
+     * @param  string|null $order 排序字段 (optional, default to 'updated_at')
+     * @param  string|null $dir 排序方向 (optional)
+     * @param  int|null $page 页码 (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3StudiosStudioTerms'] to see the possible values for this operation
      *
      *
      * @throws \InvalidArgumentException
      * @throws \InvalidArgumentException
      * @return \GuzzleHttp\Promise\PromiseInterface
      * @return \GuzzleHttp\Promise\PromiseInterface
      */
      */
-    public function postApiV3StudiosStudioChannelsAsyncWithHttpInfo($studio, $post_api_v3_studios_studio_channels_request, string $contentType = self::contentTypes['postApiV3StudiosStudioChannels'][0])
+    public function getApiV3StudiosStudioTermsAsyncWithHttpInfo($studio, $per_page = 20, $search = null, $quality = null, $category = null, $general = null, $order = 'updated_at', $dir = null, $page = null, string $contentType = self::contentTypes['getApiV3StudiosStudioTerms'][0])
     {
     {
-        $returnType = '\WikipaliApi\Model\GetApiV3ChannelsChannel200Response';
-        $request = $this->postApiV3StudiosStudioChannelsRequest($studio, $post_api_v3_studios_studio_channels_request, $contentType);
+        $returnType = '\WikipaliApi\Model\GetApiV3ChannelsChannelTerms200Response';
+        $request = $this->getApiV3StudiosStudioTermsRequest($studio, $per_page, $search, $quality, $category, $general, $order, $dir, $page, $contentType);
 
 
         return $this->client
         return $this->client
             ->sendAsync($request, $this->createHttpClientOption())
             ->sendAsync($request, $this->createHttpClientOption())
@@ -848,40 +871,120 @@ class StudiosApi
     }
     }
 
 
     /**
     /**
-     * Create request for operation 'postApiV3StudiosStudioChannels'
+     * Create request for operation 'getApiV3StudiosStudioTerms'
      *
      *
-     * @param  string $studio 用户 uuid 或团队 uuid (required)
-     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest $post_api_v3_studios_studio_channels_request (required)
-     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioChannels'] to see the possible values for this operation
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  int|null $per_page 每页条数,最大 200 (optional, default to 20)
+     * @param  string|null $search 按词、释义搜索 (optional)
+     * @param  string|null $quality 质量;pending 含未评级的 (optional)
+     * @param  string|null $category 百科分类 (optional)
+     * @param  bool|null $general 只要 studio 级术语(不属于任何 channel) (optional)
+     * @param  string|null $order 排序字段 (optional, default to 'updated_at')
+     * @param  string|null $dir 排序方向 (optional)
+     * @param  int|null $page 页码 (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3StudiosStudioTerms'] to see the possible values for this operation
      *
      *
      * @throws \InvalidArgumentException
      * @throws \InvalidArgumentException
      * @return \GuzzleHttp\Psr7\Request
      * @return \GuzzleHttp\Psr7\Request
      */
      */
-    public function postApiV3StudiosStudioChannelsRequest($studio, $post_api_v3_studios_studio_channels_request, string $contentType = self::contentTypes['postApiV3StudiosStudioChannels'][0])
+    public function getApiV3StudiosStudioTermsRequest($studio, $per_page = 20, $search = null, $quality = null, $category = null, $general = null, $order = 'updated_at', $dir = null, $page = null, string $contentType = self::contentTypes['getApiV3StudiosStudioTerms'][0])
     {
     {
 
 
         // verify the required parameter 'studio' is set
         // verify the required parameter 'studio' is set
         if ($studio === null || (is_array($studio) && count($studio) === 0)) {
         if ($studio === null || (is_array($studio) && count($studio) === 0)) {
             throw new \InvalidArgumentException(
             throw new \InvalidArgumentException(
-                'Missing the required parameter $studio when calling postApiV3StudiosStudioChannels'
+                'Missing the required parameter $studio when calling getApiV3StudiosStudioTerms'
             );
             );
         }
         }
 
 
-        // verify the required parameter 'post_api_v3_studios_studio_channels_request' is set
-        if ($post_api_v3_studios_studio_channels_request === null || (is_array($post_api_v3_studios_studio_channels_request) && count($post_api_v3_studios_studio_channels_request) === 0)) {
-            throw new \InvalidArgumentException(
-                'Missing the required parameter $post_api_v3_studios_studio_channels_request when calling postApiV3StudiosStudioChannels'
-            );
-        }
 
 
 
 
-        $resourcePath = '/v3/studios/{studio}/channels';
+
+
+
+
+
+
+
+        $resourcePath = '/v3/studios/{studio}/terms';
         $formParams = [];
         $formParams = [];
         $queryParams = [];
         $queryParams = [];
         $headerParams = [];
         $headerParams = [];
         $httpBody = '';
         $httpBody = '';
         $multipart = false;
         $multipart = false;
 
 
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $per_page,
+            'per_page', // param base name
+            'integer', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $search,
+            'search', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $quality,
+            'quality', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $category,
+            'category', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $general,
+            'general', // param base name
+            'boolean', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $order,
+            'order', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $dir,
+            'dir', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $page,
+            'page', // param base name
+            'integer', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
 
 
 
 
         // path params
         // path params
@@ -901,18 +1004,1071 @@ class StudiosApi
         );
         );
 
 
         // for model (json/xml)
         // for model (json/xml)
-        if (isset($post_api_v3_studios_studio_channels_request)) {
-            if (stripos($headers['Content-Type'], 'application/json') !== false) {
-                # if Content-Type contains "application/json", json_encode the body
+        if (count($formParams) > 0) {
+            if ($multipart) {
+                $multipartContents = [];
+                foreach ($formParams as $formParamName => $formParamValue) {
+                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
+                    foreach ($formParamValueItems as $formParamValueItem) {
+                        $multipartContents[] = [
+                            'name' => $formParamName,
+                            'contents' => $formParamValueItem
+                        ];
+                    }
+                }
+                // for HTTP post (form)
+                $httpBody = new MultipartStream($multipartContents);
+
+            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the form parameters
                 try {
                 try {
-                    $httpBody = json_encode(ObjectSerializer::sanitizeForSerialization($post_api_v3_studios_studio_channels_request), JSON_THROW_ON_ERROR);
+                    $httpBody = json_encode($formParams, JSON_THROW_ON_ERROR);
                 } catch (\JsonException $e) {
                 } catch (\JsonException $e) {
                     throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
                     throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
                 }
                 }
             } else {
             } else {
-                $httpBody = $post_api_v3_studios_studio_channels_request;
+                // for HTTP post (form)
+                $httpBody = ObjectSerializer::buildQuery($formParams);
             }
             }
-        } elseif (count($formParams) > 0) {
+        }
+
+        // this endpoint requires Bearer authentication (access token)
+        if (!empty($this->config->getAccessToken())) {
+            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
+        }
+
+        $defaultHeaders = [];
+        if ($this->config->getUserAgent()) {
+            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
+        }
+
+        $headers = array_merge(
+            $defaultHeaders,
+            $headerParams,
+            $headers
+        );
+
+        $operationHost = $this->config->getHost();
+        $query = ObjectSerializer::buildQuery($queryParams);
+        return new Request(
+            'GET',
+            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
+            $headers,
+            $httpBody
+        );
+    }
+
+    /**
+     * Operation postApiV3StudiosStudioChannels
+     *
+     * 在 studio 名下建 channel
+     *
+     * @param  string $studio 用户 uuid 或团队 uuid (required)
+     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest $post_api_v3_studios_studio_channels_request post_api_v3_studios_studio_channels_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioChannels'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return \WikipaliApi\Model\GetApiV3ChannelsChannel200Response|\WikipaliApi\Model\GetApiV3ChannelsChannel200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails
+     */
+    public function postApiV3StudiosStudioChannels($studio, $post_api_v3_studios_studio_channels_request, string $contentType = self::contentTypes['postApiV3StudiosStudioChannels'][0])
+    {
+        list($response) = $this->postApiV3StudiosStudioChannelsWithHttpInfo($studio, $post_api_v3_studios_studio_channels_request, $contentType);
+        return $response;
+    }
+
+    /**
+     * Operation postApiV3StudiosStudioChannelsWithHttpInfo
+     *
+     * 在 studio 名下建 channel
+     *
+     * @param  string $studio 用户 uuid 或团队 uuid (required)
+     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest $post_api_v3_studios_studio_channels_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioChannels'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return array of \WikipaliApi\Model\GetApiV3ChannelsChannel200Response|\WikipaliApi\Model\GetApiV3ChannelsChannel200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     */
+    public function postApiV3StudiosStudioChannelsWithHttpInfo($studio, $post_api_v3_studios_studio_channels_request, string $contentType = self::contentTypes['postApiV3StudiosStudioChannels'][0])
+    {
+        $request = $this->postApiV3StudiosStudioChannelsRequest($studio, $post_api_v3_studios_studio_channels_request, $contentType);
+
+        try {
+            $options = $this->createHttpClientOption();
+            try {
+                $response = $this->client->send($request, $options);
+            } catch (RequestException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
+                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
+                );
+            } catch (ConnectException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    null,
+                    null
+                );
+            }
+
+            $statusCode = $response->getStatusCode();
+
+
+            switch($statusCode) {
+                case 200:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\GetApiV3ChannelsChannel200Response',
+                        $request,
+                        $response,
+                    );
+                case 201:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\GetApiV3ChannelsChannel200Response',
+                        $request,
+                        $response,
+                    );
+                case 401:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 403:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 422:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+            }
+
+            
+
+            if ($statusCode < 200 || $statusCode > 299) {
+                throw new ApiException(
+                    sprintf(
+                        '[%d] Error connecting to the API (%s)',
+                        $statusCode,
+                        (string) $request->getUri()
+                    ),
+                    $statusCode,
+                    $response->getHeaders(),
+                    (string) $response->getBody()
+                );
+            }
+
+            return $this->handleResponseWithDataType(
+                '\WikipaliApi\Model\GetApiV3ChannelsChannel200Response',
+                $request,
+                $response,
+            );
+        } catch (ApiException $e) {
+            switch ($e->getCode()) {
+                case 200:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\GetApiV3ChannelsChannel200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 201:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\GetApiV3ChannelsChannel200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 401:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 403:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 422:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+            }
+        
+
+            throw $e;
+        }
+    }
+
+    /**
+     * Operation postApiV3StudiosStudioChannelsAsync
+     *
+     * 在 studio 名下建 channel
+     *
+     * @param  string $studio 用户 uuid 或团队 uuid (required)
+     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest $post_api_v3_studios_studio_channels_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioChannels'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function postApiV3StudiosStudioChannelsAsync($studio, $post_api_v3_studios_studio_channels_request, string $contentType = self::contentTypes['postApiV3StudiosStudioChannels'][0])
+    {
+        return $this->postApiV3StudiosStudioChannelsAsyncWithHttpInfo($studio, $post_api_v3_studios_studio_channels_request, $contentType)
+            ->then(
+                function ($response) {
+                    return $response[0];
+                }
+            );
+    }
+
+    /**
+     * Operation postApiV3StudiosStudioChannelsAsyncWithHttpInfo
+     *
+     * 在 studio 名下建 channel
+     *
+     * @param  string $studio 用户 uuid 或团队 uuid (required)
+     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest $post_api_v3_studios_studio_channels_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioChannels'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function postApiV3StudiosStudioChannelsAsyncWithHttpInfo($studio, $post_api_v3_studios_studio_channels_request, string $contentType = self::contentTypes['postApiV3StudiosStudioChannels'][0])
+    {
+        $returnType = '\WikipaliApi\Model\GetApiV3ChannelsChannel200Response';
+        $request = $this->postApiV3StudiosStudioChannelsRequest($studio, $post_api_v3_studios_studio_channels_request, $contentType);
+
+        return $this->client
+            ->sendAsync($request, $this->createHttpClientOption())
+            ->then(
+                function ($response) use ($returnType) {
+                    if ($returnType === '\SplFileObject') {
+                        $content = $response->getBody(); //stream goes to serializer
+                    } else {
+                        $content = (string) $response->getBody();
+                        if ($returnType !== 'string') {
+                            $content = json_decode($content);
+                        }
+                    }
+
+                    return [
+                        ObjectSerializer::deserialize($content, $returnType, []),
+                        $response->getStatusCode(),
+                        $response->getHeaders()
+                    ];
+                },
+                function ($exception) {
+                    $response = $exception->getResponse();
+                    $statusCode = $response->getStatusCode();
+                    throw new ApiException(
+                        sprintf(
+                            '[%d] Error connecting to the API (%s)',
+                            $statusCode,
+                            $exception->getRequest()->getUri()
+                        ),
+                        $statusCode,
+                        $response->getHeaders(),
+                        (string) $response->getBody()
+                    );
+                }
+            );
+    }
+
+    /**
+     * Create request for operation 'postApiV3StudiosStudioChannels'
+     *
+     * @param  string $studio 用户 uuid 或团队 uuid (required)
+     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioChannelsRequest $post_api_v3_studios_studio_channels_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioChannels'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Psr7\Request
+     */
+    public function postApiV3StudiosStudioChannelsRequest($studio, $post_api_v3_studios_studio_channels_request, string $contentType = self::contentTypes['postApiV3StudiosStudioChannels'][0])
+    {
+
+        // verify the required parameter 'studio' is set
+        if ($studio === null || (is_array($studio) && count($studio) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $studio when calling postApiV3StudiosStudioChannels'
+            );
+        }
+
+        // verify the required parameter 'post_api_v3_studios_studio_channels_request' is set
+        if ($post_api_v3_studios_studio_channels_request === null || (is_array($post_api_v3_studios_studio_channels_request) && count($post_api_v3_studios_studio_channels_request) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $post_api_v3_studios_studio_channels_request when calling postApiV3StudiosStudioChannels'
+            );
+        }
+
+
+        $resourcePath = '/v3/studios/{studio}/channels';
+        $formParams = [];
+        $queryParams = [];
+        $headerParams = [];
+        $httpBody = '';
+        $multipart = false;
+
+
+
+        // path params
+        if ($studio !== null) {
+            $resourcePath = str_replace(
+                '{studio}',
+                ObjectSerializer::toPathValue($studio),
+                $resourcePath
+            );
+        }
+
+
+        $headers = $this->headerSelector->selectHeaders(
+            ['application/json', 'application/problem+json', ],
+            $contentType,
+            $multipart
+        );
+
+        // for model (json/xml)
+        if (isset($post_api_v3_studios_studio_channels_request)) {
+            if (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the body
+                try {
+                    $httpBody = json_encode(ObjectSerializer::sanitizeForSerialization($post_api_v3_studios_studio_channels_request), JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                $httpBody = $post_api_v3_studios_studio_channels_request;
+            }
+        } elseif (count($formParams) > 0) {
+            if ($multipart) {
+                $multipartContents = [];
+                foreach ($formParams as $formParamName => $formParamValue) {
+                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
+                    foreach ($formParamValueItems as $formParamValueItem) {
+                        $multipartContents[] = [
+                            'name' => $formParamName,
+                            'contents' => $formParamValueItem
+                        ];
+                    }
+                }
+                // for HTTP post (form)
+                $httpBody = new MultipartStream($multipartContents);
+
+            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the form parameters
+                try {
+                    $httpBody = json_encode($formParams, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                // for HTTP post (form)
+                $httpBody = ObjectSerializer::buildQuery($formParams);
+            }
+        }
+
+        // this endpoint requires Bearer authentication (access token)
+        if (!empty($this->config->getAccessToken())) {
+            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
+        }
+
+        $defaultHeaders = [];
+        if ($this->config->getUserAgent()) {
+            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
+        }
+
+        $headers = array_merge(
+            $defaultHeaders,
+            $headerParams,
+            $headers
+        );
+
+        $operationHost = $this->config->getHost();
+        $query = ObjectSerializer::buildQuery($queryParams);
+        return new Request(
+            'POST',
+            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
+            $headers,
+            $httpBody
+        );
+    }
+
+    /**
+     * Operation postApiV3StudiosStudioTerms
+     *
+     * 新建 studio 级术语
+     *
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioTermsRequest $post_api_v3_studios_studio_terms_request post_api_v3_studios_studio_terms_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioTerms'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return \WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails
+     */
+    public function postApiV3StudiosStudioTerms($studio, $post_api_v3_studios_studio_terms_request, string $contentType = self::contentTypes['postApiV3StudiosStudioTerms'][0])
+    {
+        list($response) = $this->postApiV3StudiosStudioTermsWithHttpInfo($studio, $post_api_v3_studios_studio_terms_request, $contentType);
+        return $response;
+    }
+
+    /**
+     * Operation postApiV3StudiosStudioTermsWithHttpInfo
+     *
+     * 新建 studio 级术语
+     *
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioTermsRequest $post_api_v3_studios_studio_terms_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioTerms'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return array of \WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     */
+    public function postApiV3StudiosStudioTermsWithHttpInfo($studio, $post_api_v3_studios_studio_terms_request, string $contentType = self::contentTypes['postApiV3StudiosStudioTerms'][0])
+    {
+        $request = $this->postApiV3StudiosStudioTermsRequest($studio, $post_api_v3_studios_studio_terms_request, $contentType);
+
+        try {
+            $options = $this->createHttpClientOption();
+            try {
+                $response = $this->client->send($request, $options);
+            } catch (RequestException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
+                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
+                );
+            } catch (ConnectException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    null,
+                    null
+                );
+            }
+
+            $statusCode = $response->getStatusCode();
+
+
+            switch($statusCode) {
+                case 200:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                        $request,
+                        $response,
+                    );
+                case 201:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                        $request,
+                        $response,
+                    );
+                case 401:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 403:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 409:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 422:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+            }
+
+            
+
+            if ($statusCode < 200 || $statusCode > 299) {
+                throw new ApiException(
+                    sprintf(
+                        '[%d] Error connecting to the API (%s)',
+                        $statusCode,
+                        (string) $request->getUri()
+                    ),
+                    $statusCode,
+                    $response->getHeaders(),
+                    (string) $response->getBody()
+                );
+            }
+
+            return $this->handleResponseWithDataType(
+                '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                $request,
+                $response,
+            );
+        } catch (ApiException $e) {
+            switch ($e->getCode()) {
+                case 200:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 201:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 401:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 403:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 409:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 422:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+            }
+        
+
+            throw $e;
+        }
+    }
+
+    /**
+     * Operation postApiV3StudiosStudioTermsAsync
+     *
+     * 新建 studio 级术语
+     *
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioTermsRequest $post_api_v3_studios_studio_terms_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioTerms'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function postApiV3StudiosStudioTermsAsync($studio, $post_api_v3_studios_studio_terms_request, string $contentType = self::contentTypes['postApiV3StudiosStudioTerms'][0])
+    {
+        return $this->postApiV3StudiosStudioTermsAsyncWithHttpInfo($studio, $post_api_v3_studios_studio_terms_request, $contentType)
+            ->then(
+                function ($response) {
+                    return $response[0];
+                }
+            );
+    }
+
+    /**
+     * Operation postApiV3StudiosStudioTermsAsyncWithHttpInfo
+     *
+     * 新建 studio 级术语
+     *
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioTermsRequest $post_api_v3_studios_studio_terms_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioTerms'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function postApiV3StudiosStudioTermsAsyncWithHttpInfo($studio, $post_api_v3_studios_studio_terms_request, string $contentType = self::contentTypes['postApiV3StudiosStudioTerms'][0])
+    {
+        $returnType = '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response';
+        $request = $this->postApiV3StudiosStudioTermsRequest($studio, $post_api_v3_studios_studio_terms_request, $contentType);
+
+        return $this->client
+            ->sendAsync($request, $this->createHttpClientOption())
+            ->then(
+                function ($response) use ($returnType) {
+                    if ($returnType === '\SplFileObject') {
+                        $content = $response->getBody(); //stream goes to serializer
+                    } else {
+                        $content = (string) $response->getBody();
+                        if ($returnType !== 'string') {
+                            $content = json_decode($content);
+                        }
+                    }
+
+                    return [
+                        ObjectSerializer::deserialize($content, $returnType, []),
+                        $response->getStatusCode(),
+                        $response->getHeaders()
+                    ];
+                },
+                function ($exception) {
+                    $response = $exception->getResponse();
+                    $statusCode = $response->getStatusCode();
+                    throw new ApiException(
+                        sprintf(
+                            '[%d] Error connecting to the API (%s)',
+                            $statusCode,
+                            $exception->getRequest()->getUri()
+                        ),
+                        $statusCode,
+                        $response->getHeaders(),
+                        (string) $response->getBody()
+                    );
+                }
+            );
+    }
+
+    /**
+     * Create request for operation 'postApiV3StudiosStudioTerms'
+     *
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  \WikipaliApi\Model\PostApiV3StudiosStudioTermsRequest $post_api_v3_studios_studio_terms_request (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioTerms'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Psr7\Request
+     */
+    public function postApiV3StudiosStudioTermsRequest($studio, $post_api_v3_studios_studio_terms_request, string $contentType = self::contentTypes['postApiV3StudiosStudioTerms'][0])
+    {
+
+        // verify the required parameter 'studio' is set
+        if ($studio === null || (is_array($studio) && count($studio) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $studio when calling postApiV3StudiosStudioTerms'
+            );
+        }
+
+        // verify the required parameter 'post_api_v3_studios_studio_terms_request' is set
+        if ($post_api_v3_studios_studio_terms_request === null || (is_array($post_api_v3_studios_studio_terms_request) && count($post_api_v3_studios_studio_terms_request) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $post_api_v3_studios_studio_terms_request when calling postApiV3StudiosStudioTerms'
+            );
+        }
+
+
+        $resourcePath = '/v3/studios/{studio}/terms';
+        $formParams = [];
+        $queryParams = [];
+        $headerParams = [];
+        $httpBody = '';
+        $multipart = false;
+
+
+
+        // path params
+        if ($studio !== null) {
+            $resourcePath = str_replace(
+                '{studio}',
+                ObjectSerializer::toPathValue($studio),
+                $resourcePath
+            );
+        }
+
+
+        $headers = $this->headerSelector->selectHeaders(
+            ['application/json', 'application/problem+json', ],
+            $contentType,
+            $multipart
+        );
+
+        // for model (json/xml)
+        if (isset($post_api_v3_studios_studio_terms_request)) {
+            if (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the body
+                try {
+                    $httpBody = json_encode(ObjectSerializer::sanitizeForSerialization($post_api_v3_studios_studio_terms_request), JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                $httpBody = $post_api_v3_studios_studio_terms_request;
+            }
+        } elseif (count($formParams) > 0) {
+            if ($multipart) {
+                $multipartContents = [];
+                foreach ($formParams as $formParamName => $formParamValue) {
+                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
+                    foreach ($formParamValueItems as $formParamValueItem) {
+                        $multipartContents[] = [
+                            'name' => $formParamName,
+                            'contents' => $formParamValueItem
+                        ];
+                    }
+                }
+                // for HTTP post (form)
+                $httpBody = new MultipartStream($multipartContents);
+
+            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the form parameters
+                try {
+                    $httpBody = json_encode($formParams, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                // for HTTP post (form)
+                $httpBody = ObjectSerializer::buildQuery($formParams);
+            }
+        }
+
+        // this endpoint requires Bearer authentication (access token)
+        if (!empty($this->config->getAccessToken())) {
+            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
+        }
+
+        $defaultHeaders = [];
+        if ($this->config->getUserAgent()) {
+            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
+        }
+
+        $headers = array_merge(
+            $defaultHeaders,
+            $headerParams,
+            $headers
+        );
+
+        $operationHost = $this->config->getHost();
+        $query = ObjectSerializer::buildQuery($queryParams);
+        return new Request(
+            'POST',
+            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
+            $headers,
+            $httpBody
+        );
+    }
+
+    /**
+     * Operation postApiV3StudiosStudioTermsImports
+     *
+     * 向 studio 导入术语
+     *
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  \SplFileObject $file xlsx 表格,不超过 5MB (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioTermsImports'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return \WikipaliApi\Model\PostApiV3ChannelsChannelTermsImports200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails
+     */
+    public function postApiV3StudiosStudioTermsImports($studio, $file, string $contentType = self::contentTypes['postApiV3StudiosStudioTermsImports'][0])
+    {
+        list($response) = $this->postApiV3StudiosStudioTermsImportsWithHttpInfo($studio, $file, $contentType);
+        return $response;
+    }
+
+    /**
+     * Operation postApiV3StudiosStudioTermsImportsWithHttpInfo
+     *
+     * 向 studio 导入术语
+     *
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  \SplFileObject $file xlsx 表格,不超过 5MB (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioTermsImports'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return array of \WikipaliApi\Model\PostApiV3ChannelsChannelTermsImports200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     */
+    public function postApiV3StudiosStudioTermsImportsWithHttpInfo($studio, $file, string $contentType = self::contentTypes['postApiV3StudiosStudioTermsImports'][0])
+    {
+        $request = $this->postApiV3StudiosStudioTermsImportsRequest($studio, $file, $contentType);
+
+        try {
+            $options = $this->createHttpClientOption();
+            try {
+                $response = $this->client->send($request, $options);
+            } catch (RequestException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
+                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
+                );
+            } catch (ConnectException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    null,
+                    null
+                );
+            }
+
+            $statusCode = $response->getStatusCode();
+
+
+            switch($statusCode) {
+                case 200:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\PostApiV3ChannelsChannelTermsImports200Response',
+                        $request,
+                        $response,
+                    );
+                case 401:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 403:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 422:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+            }
+
+            
+
+            if ($statusCode < 200 || $statusCode > 299) {
+                throw new ApiException(
+                    sprintf(
+                        '[%d] Error connecting to the API (%s)',
+                        $statusCode,
+                        (string) $request->getUri()
+                    ),
+                    $statusCode,
+                    $response->getHeaders(),
+                    (string) $response->getBody()
+                );
+            }
+
+            return $this->handleResponseWithDataType(
+                '\WikipaliApi\Model\PostApiV3ChannelsChannelTermsImports200Response',
+                $request,
+                $response,
+            );
+        } catch (ApiException $e) {
+            switch ($e->getCode()) {
+                case 200:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\PostApiV3ChannelsChannelTermsImports200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 401:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 403:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 422:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+            }
+        
+
+            throw $e;
+        }
+    }
+
+    /**
+     * Operation postApiV3StudiosStudioTermsImportsAsync
+     *
+     * 向 studio 导入术语
+     *
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  \SplFileObject $file xlsx 表格,不超过 5MB (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioTermsImports'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function postApiV3StudiosStudioTermsImportsAsync($studio, $file, string $contentType = self::contentTypes['postApiV3StudiosStudioTermsImports'][0])
+    {
+        return $this->postApiV3StudiosStudioTermsImportsAsyncWithHttpInfo($studio, $file, $contentType)
+            ->then(
+                function ($response) {
+                    return $response[0];
+                }
+            );
+    }
+
+    /**
+     * Operation postApiV3StudiosStudioTermsImportsAsyncWithHttpInfo
+     *
+     * 向 studio 导入术语
+     *
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  \SplFileObject $file xlsx 表格,不超过 5MB (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioTermsImports'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function postApiV3StudiosStudioTermsImportsAsyncWithHttpInfo($studio, $file, string $contentType = self::contentTypes['postApiV3StudiosStudioTermsImports'][0])
+    {
+        $returnType = '\WikipaliApi\Model\PostApiV3ChannelsChannelTermsImports200Response';
+        $request = $this->postApiV3StudiosStudioTermsImportsRequest($studio, $file, $contentType);
+
+        return $this->client
+            ->sendAsync($request, $this->createHttpClientOption())
+            ->then(
+                function ($response) use ($returnType) {
+                    if ($returnType === '\SplFileObject') {
+                        $content = $response->getBody(); //stream goes to serializer
+                    } else {
+                        $content = (string) $response->getBody();
+                        if ($returnType !== 'string') {
+                            $content = json_decode($content);
+                        }
+                    }
+
+                    return [
+                        ObjectSerializer::deserialize($content, $returnType, []),
+                        $response->getStatusCode(),
+                        $response->getHeaders()
+                    ];
+                },
+                function ($exception) {
+                    $response = $exception->getResponse();
+                    $statusCode = $response->getStatusCode();
+                    throw new ApiException(
+                        sprintf(
+                            '[%d] Error connecting to the API (%s)',
+                            $statusCode,
+                            $exception->getRequest()->getUri()
+                        ),
+                        $statusCode,
+                        $response->getHeaders(),
+                        (string) $response->getBody()
+                    );
+                }
+            );
+    }
+
+    /**
+     * Create request for operation 'postApiV3StudiosStudioTermsImports'
+     *
+     * @param  string $studio 用户或团队的 uuid (required)
+     * @param  \SplFileObject $file xlsx 表格,不超过 5MB (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['postApiV3StudiosStudioTermsImports'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Psr7\Request
+     */
+    public function postApiV3StudiosStudioTermsImportsRequest($studio, $file, string $contentType = self::contentTypes['postApiV3StudiosStudioTermsImports'][0])
+    {
+
+        // verify the required parameter 'studio' is set
+        if ($studio === null || (is_array($studio) && count($studio) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $studio when calling postApiV3StudiosStudioTermsImports'
+            );
+        }
+
+        // verify the required parameter 'file' is set
+        if ($file === null || (is_array($file) && count($file) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $file when calling postApiV3StudiosStudioTermsImports'
+            );
+        }
+
+
+        $resourcePath = '/v3/studios/{studio}/terms/imports';
+        $formParams = [];
+        $queryParams = [];
+        $headerParams = [];
+        $httpBody = '';
+        $multipart = false;
+
+
+
+        // path params
+        if ($studio !== null) {
+            $resourcePath = str_replace(
+                '{studio}',
+                ObjectSerializer::toPathValue($studio),
+                $resourcePath
+            );
+        }
+
+        // form params
+        $formDataProcessor = new FormDataProcessor();
+
+        $formData = $formDataProcessor->prepare([
+            'file' => $file,
+        ]);
+
+        $formParams = $formDataProcessor->flatten($formData);
+        $multipart = $formDataProcessor->has_file;
+
+        $multipart = true;
+        $headers = $this->headerSelector->selectHeaders(
+            ['application/json', 'application/problem+json', ],
+            $contentType,
+            $multipart
+        );
+
+        // for model (json/xml)
+        if (count($formParams) > 0) {
             if ($multipart) {
             if ($multipart) {
                 $multipartContents = [];
                 $multipartContents = [];
                 foreach ($formParams as $formParamName => $formParamValue) {
                 foreach ($formParams as $formParamName => $formParamValue) {

+ 1617 - 0
api-test/client/lib/Api/TermsApi.php

@@ -0,0 +1,1617 @@
+<?php
+/**
+ * TermsApi
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Api;
+
+use GuzzleHttp\Client;
+use GuzzleHttp\ClientInterface;
+use GuzzleHttp\Exception\ConnectException;
+use GuzzleHttp\Exception\RequestException;
+use GuzzleHttp\Psr7\MultipartStream;
+use GuzzleHttp\Psr7\Request;
+use GuzzleHttp\RequestOptions;
+use Psr\Http\Message\RequestInterface;
+use Psr\Http\Message\ResponseInterface;
+use WikipaliApi\ApiException;
+use WikipaliApi\Configuration;
+use WikipaliApi\FormDataProcessor;
+use WikipaliApi\HeaderSelector;
+use WikipaliApi\ObjectSerializer;
+
+/**
+ * TermsApi Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+class TermsApi
+{
+    /**
+     * @var ClientInterface
+     */
+    protected $client;
+
+    /**
+     * @var Configuration
+     */
+    protected $config;
+
+    /**
+     * @var HeaderSelector
+     */
+    protected $headerSelector;
+
+    /**
+     * @var int Host index
+     */
+    protected $hostIndex;
+
+    /** @var string[] $contentTypes **/
+    public const contentTypes = [
+        'deleteApiV3TermsTerm' => [
+            'application/json',
+        ],
+        'getApiV3Terms' => [
+            'application/json',
+        ],
+        'getApiV3TermsTerm' => [
+            'application/json',
+        ],
+        'patchApiV3TermsTerm' => [
+            'application/json',
+        ],
+    ];
+
+    /**
+     * @param ClientInterface $client
+     * @param Configuration   $config
+     * @param HeaderSelector  $selector
+     * @param int             $hostIndex (Optional) host index to select the list of hosts if defined in the OpenAPI spec
+     */
+    public function __construct(
+        ?ClientInterface $client = null,
+        ?Configuration $config = null,
+        ?HeaderSelector $selector = null,
+        int $hostIndex = 0
+    ) {
+        $this->client = $client ?: new Client();
+        $this->config = $config ?: Configuration::getDefaultConfiguration();
+        $this->headerSelector = $selector ?: new HeaderSelector();
+        $this->hostIndex = $hostIndex;
+    }
+
+    /**
+     * Set the host index
+     *
+     * @param int $hostIndex Host index (required)
+     */
+    public function setHostIndex($hostIndex): void
+    {
+        $this->hostIndex = $hostIndex;
+    }
+
+    /**
+     * Get the host index
+     *
+     * @return int Host index
+     */
+    public function getHostIndex()
+    {
+        return $this->hostIndex;
+    }
+
+    /**
+     * @return Configuration
+     */
+    public function getConfig()
+    {
+        return $this->config;
+    }
+
+    /**
+     * Operation deleteApiV3TermsTerm
+     *
+     * 删术语
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['deleteApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return \WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails
+     */
+    public function deleteApiV3TermsTerm($term, string $contentType = self::contentTypes['deleteApiV3TermsTerm'][0])
+    {
+        list($response) = $this->deleteApiV3TermsTermWithHttpInfo($term, $contentType);
+        return $response;
+    }
+
+    /**
+     * Operation deleteApiV3TermsTermWithHttpInfo
+     *
+     * 删术语
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['deleteApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return array of \WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     */
+    public function deleteApiV3TermsTermWithHttpInfo($term, string $contentType = self::contentTypes['deleteApiV3TermsTerm'][0])
+    {
+        $request = $this->deleteApiV3TermsTermRequest($term, $contentType);
+
+        try {
+            $options = $this->createHttpClientOption();
+            try {
+                $response = $this->client->send($request, $options);
+            } catch (RequestException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
+                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
+                );
+            } catch (ConnectException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    null,
+                    null
+                );
+            }
+
+            $statusCode = $response->getStatusCode();
+
+
+            switch($statusCode) {
+                case 200:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                        $request,
+                        $response,
+                    );
+                case 401:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 403:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 422:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+            }
+
+            
+
+            if ($statusCode < 200 || $statusCode > 299) {
+                throw new ApiException(
+                    sprintf(
+                        '[%d] Error connecting to the API (%s)',
+                        $statusCode,
+                        (string) $request->getUri()
+                    ),
+                    $statusCode,
+                    $response->getHeaders(),
+                    (string) $response->getBody()
+                );
+            }
+
+            return $this->handleResponseWithDataType(
+                '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                $request,
+                $response,
+            );
+        } catch (ApiException $e) {
+            switch ($e->getCode()) {
+                case 200:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 401:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 403:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 422:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+            }
+        
+
+            throw $e;
+        }
+    }
+
+    /**
+     * Operation deleteApiV3TermsTermAsync
+     *
+     * 删术语
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['deleteApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function deleteApiV3TermsTermAsync($term, string $contentType = self::contentTypes['deleteApiV3TermsTerm'][0])
+    {
+        return $this->deleteApiV3TermsTermAsyncWithHttpInfo($term, $contentType)
+            ->then(
+                function ($response) {
+                    return $response[0];
+                }
+            );
+    }
+
+    /**
+     * Operation deleteApiV3TermsTermAsyncWithHttpInfo
+     *
+     * 删术语
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['deleteApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function deleteApiV3TermsTermAsyncWithHttpInfo($term, string $contentType = self::contentTypes['deleteApiV3TermsTerm'][0])
+    {
+        $returnType = '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response';
+        $request = $this->deleteApiV3TermsTermRequest($term, $contentType);
+
+        return $this->client
+            ->sendAsync($request, $this->createHttpClientOption())
+            ->then(
+                function ($response) use ($returnType) {
+                    if ($returnType === '\SplFileObject') {
+                        $content = $response->getBody(); //stream goes to serializer
+                    } else {
+                        $content = (string) $response->getBody();
+                        if ($returnType !== 'string') {
+                            $content = json_decode($content);
+                        }
+                    }
+
+                    return [
+                        ObjectSerializer::deserialize($content, $returnType, []),
+                        $response->getStatusCode(),
+                        $response->getHeaders()
+                    ];
+                },
+                function ($exception) {
+                    $response = $exception->getResponse();
+                    $statusCode = $response->getStatusCode();
+                    throw new ApiException(
+                        sprintf(
+                            '[%d] Error connecting to the API (%s)',
+                            $statusCode,
+                            $exception->getRequest()->getUri()
+                        ),
+                        $statusCode,
+                        $response->getHeaders(),
+                        (string) $response->getBody()
+                    );
+                }
+            );
+    }
+
+    /**
+     * Create request for operation 'deleteApiV3TermsTerm'
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['deleteApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Psr7\Request
+     */
+    public function deleteApiV3TermsTermRequest($term, string $contentType = self::contentTypes['deleteApiV3TermsTerm'][0])
+    {
+
+        // verify the required parameter 'term' is set
+        if ($term === null || (is_array($term) && count($term) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $term when calling deleteApiV3TermsTerm'
+            );
+        }
+
+
+        $resourcePath = '/v3/terms/{term}';
+        $formParams = [];
+        $queryParams = [];
+        $headerParams = [];
+        $httpBody = '';
+        $multipart = false;
+
+
+
+        // path params
+        if ($term !== null) {
+            $resourcePath = str_replace(
+                '{term}',
+                ObjectSerializer::toPathValue($term),
+                $resourcePath
+            );
+        }
+
+
+        $headers = $this->headerSelector->selectHeaders(
+            ['application/json', 'application/problem+json', ],
+            $contentType,
+            $multipart
+        );
+
+        // for model (json/xml)
+        if (count($formParams) > 0) {
+            if ($multipart) {
+                $multipartContents = [];
+                foreach ($formParams as $formParamName => $formParamValue) {
+                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
+                    foreach ($formParamValueItems as $formParamValueItem) {
+                        $multipartContents[] = [
+                            'name' => $formParamName,
+                            'contents' => $formParamValueItem
+                        ];
+                    }
+                }
+                // for HTTP post (form)
+                $httpBody = new MultipartStream($multipartContents);
+
+            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the form parameters
+                try {
+                    $httpBody = json_encode($formParams, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                // for HTTP post (form)
+                $httpBody = ObjectSerializer::buildQuery($formParams);
+            }
+        }
+
+        // this endpoint requires Bearer authentication (access token)
+        if (!empty($this->config->getAccessToken())) {
+            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
+        }
+
+        $defaultHeaders = [];
+        if ($this->config->getUserAgent()) {
+            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
+        }
+
+        $headers = array_merge(
+            $defaultHeaders,
+            $headerParams,
+            $headers
+        );
+
+        $operationHost = $this->config->getHost();
+        $query = ObjectSerializer::buildQuery($queryParams);
+        return new Request(
+            'DELETE',
+            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
+            $headers,
+            $httpBody
+        );
+    }
+
+    /**
+     * Operation getApiV3Terms
+     *
+     * 按词查术语
+     *
+     * @param  string $word 巴利词,逗号分隔,最多 50 个 (required)
+     * @param  int|null $per_page 每页条数,最大 200 (optional, default to 20)
+     * @param  string|null $tag 义项;传空串只要没有义项的 (optional)
+     * @param  string|null $channel 只要这个 channel 的 (optional)
+     * @param  string|null $language 只要这个语言的 (optional)
+     * @param  bool|null $with_body 每条都带渲染后的正文 &#x60;body&#x60; (optional)
+     * @param  int|null $page 页码 (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3Terms'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return \WikipaliApi\Model\GetApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\ProblemDetails
+     */
+    public function getApiV3Terms($word, $per_page = 20, $tag = null, $channel = null, $language = null, $with_body = null, $page = null, string $contentType = self::contentTypes['getApiV3Terms'][0])
+    {
+        list($response) = $this->getApiV3TermsWithHttpInfo($word, $per_page, $tag, $channel, $language, $with_body, $page, $contentType);
+        return $response;
+    }
+
+    /**
+     * Operation getApiV3TermsWithHttpInfo
+     *
+     * 按词查术语
+     *
+     * @param  string $word 巴利词,逗号分隔,最多 50 个 (required)
+     * @param  int|null $per_page 每页条数,最大 200 (optional, default to 20)
+     * @param  string|null $tag 义项;传空串只要没有义项的 (optional)
+     * @param  string|null $channel 只要这个 channel 的 (optional)
+     * @param  string|null $language 只要这个语言的 (optional)
+     * @param  bool|null $with_body 每条都带渲染后的正文 &#x60;body&#x60; (optional)
+     * @param  int|null $page 页码 (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3Terms'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return array of \WikipaliApi\Model\GetApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     */
+    public function getApiV3TermsWithHttpInfo($word, $per_page = 20, $tag = null, $channel = null, $language = null, $with_body = null, $page = null, string $contentType = self::contentTypes['getApiV3Terms'][0])
+    {
+        $request = $this->getApiV3TermsRequest($word, $per_page, $tag, $channel, $language, $with_body, $page, $contentType);
+
+        try {
+            $options = $this->createHttpClientOption();
+            try {
+                $response = $this->client->send($request, $options);
+            } catch (RequestException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
+                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
+                );
+            } catch (ConnectException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    null,
+                    null
+                );
+            }
+
+            $statusCode = $response->getStatusCode();
+
+
+            switch($statusCode) {
+                case 200:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\GetApiV3ChannelsChannelTerms200Response',
+                        $request,
+                        $response,
+                    );
+                case 422:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+            }
+
+            
+
+            if ($statusCode < 200 || $statusCode > 299) {
+                throw new ApiException(
+                    sprintf(
+                        '[%d] Error connecting to the API (%s)',
+                        $statusCode,
+                        (string) $request->getUri()
+                    ),
+                    $statusCode,
+                    $response->getHeaders(),
+                    (string) $response->getBody()
+                );
+            }
+
+            return $this->handleResponseWithDataType(
+                '\WikipaliApi\Model\GetApiV3ChannelsChannelTerms200Response',
+                $request,
+                $response,
+            );
+        } catch (ApiException $e) {
+            switch ($e->getCode()) {
+                case 200:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\GetApiV3ChannelsChannelTerms200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 422:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+            }
+        
+
+            throw $e;
+        }
+    }
+
+    /**
+     * Operation getApiV3TermsAsync
+     *
+     * 按词查术语
+     *
+     * @param  string $word 巴利词,逗号分隔,最多 50 个 (required)
+     * @param  int|null $per_page 每页条数,最大 200 (optional, default to 20)
+     * @param  string|null $tag 义项;传空串只要没有义项的 (optional)
+     * @param  string|null $channel 只要这个 channel 的 (optional)
+     * @param  string|null $language 只要这个语言的 (optional)
+     * @param  bool|null $with_body 每条都带渲染后的正文 &#x60;body&#x60; (optional)
+     * @param  int|null $page 页码 (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3Terms'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function getApiV3TermsAsync($word, $per_page = 20, $tag = null, $channel = null, $language = null, $with_body = null, $page = null, string $contentType = self::contentTypes['getApiV3Terms'][0])
+    {
+        return $this->getApiV3TermsAsyncWithHttpInfo($word, $per_page, $tag, $channel, $language, $with_body, $page, $contentType)
+            ->then(
+                function ($response) {
+                    return $response[0];
+                }
+            );
+    }
+
+    /**
+     * Operation getApiV3TermsAsyncWithHttpInfo
+     *
+     * 按词查术语
+     *
+     * @param  string $word 巴利词,逗号分隔,最多 50 个 (required)
+     * @param  int|null $per_page 每页条数,最大 200 (optional, default to 20)
+     * @param  string|null $tag 义项;传空串只要没有义项的 (optional)
+     * @param  string|null $channel 只要这个 channel 的 (optional)
+     * @param  string|null $language 只要这个语言的 (optional)
+     * @param  bool|null $with_body 每条都带渲染后的正文 &#x60;body&#x60; (optional)
+     * @param  int|null $page 页码 (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3Terms'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function getApiV3TermsAsyncWithHttpInfo($word, $per_page = 20, $tag = null, $channel = null, $language = null, $with_body = null, $page = null, string $contentType = self::contentTypes['getApiV3Terms'][0])
+    {
+        $returnType = '\WikipaliApi\Model\GetApiV3ChannelsChannelTerms200Response';
+        $request = $this->getApiV3TermsRequest($word, $per_page, $tag, $channel, $language, $with_body, $page, $contentType);
+
+        return $this->client
+            ->sendAsync($request, $this->createHttpClientOption())
+            ->then(
+                function ($response) use ($returnType) {
+                    if ($returnType === '\SplFileObject') {
+                        $content = $response->getBody(); //stream goes to serializer
+                    } else {
+                        $content = (string) $response->getBody();
+                        if ($returnType !== 'string') {
+                            $content = json_decode($content);
+                        }
+                    }
+
+                    return [
+                        ObjectSerializer::deserialize($content, $returnType, []),
+                        $response->getStatusCode(),
+                        $response->getHeaders()
+                    ];
+                },
+                function ($exception) {
+                    $response = $exception->getResponse();
+                    $statusCode = $response->getStatusCode();
+                    throw new ApiException(
+                        sprintf(
+                            '[%d] Error connecting to the API (%s)',
+                            $statusCode,
+                            $exception->getRequest()->getUri()
+                        ),
+                        $statusCode,
+                        $response->getHeaders(),
+                        (string) $response->getBody()
+                    );
+                }
+            );
+    }
+
+    /**
+     * Create request for operation 'getApiV3Terms'
+     *
+     * @param  string $word 巴利词,逗号分隔,最多 50 个 (required)
+     * @param  int|null $per_page 每页条数,最大 200 (optional, default to 20)
+     * @param  string|null $tag 义项;传空串只要没有义项的 (optional)
+     * @param  string|null $channel 只要这个 channel 的 (optional)
+     * @param  string|null $language 只要这个语言的 (optional)
+     * @param  bool|null $with_body 每条都带渲染后的正文 &#x60;body&#x60; (optional)
+     * @param  int|null $page 页码 (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3Terms'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Psr7\Request
+     */
+    public function getApiV3TermsRequest($word, $per_page = 20, $tag = null, $channel = null, $language = null, $with_body = null, $page = null, string $contentType = self::contentTypes['getApiV3Terms'][0])
+    {
+
+        // verify the required parameter 'word' is set
+        if ($word === null || (is_array($word) && count($word) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $word when calling getApiV3Terms'
+            );
+        }
+
+
+
+
+
+
+
+
+        $resourcePath = '/v3/terms';
+        $formParams = [];
+        $queryParams = [];
+        $headerParams = [];
+        $httpBody = '';
+        $multipart = false;
+
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $per_page,
+            'per_page', // param base name
+            'integer', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $word,
+            'word', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            true // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $tag,
+            'tag', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $channel,
+            'channel', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $language,
+            'language', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $with_body,
+            'with_body', // param base name
+            'boolean', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $page,
+            'page', // param base name
+            'integer', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+
+
+
+
+        $headers = $this->headerSelector->selectHeaders(
+            ['application/json', 'application/problem+json', ],
+            $contentType,
+            $multipart
+        );
+
+        // for model (json/xml)
+        if (count($formParams) > 0) {
+            if ($multipart) {
+                $multipartContents = [];
+                foreach ($formParams as $formParamName => $formParamValue) {
+                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
+                    foreach ($formParamValueItems as $formParamValueItem) {
+                        $multipartContents[] = [
+                            'name' => $formParamName,
+                            'contents' => $formParamValueItem
+                        ];
+                    }
+                }
+                // for HTTP post (form)
+                $httpBody = new MultipartStream($multipartContents);
+
+            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the form parameters
+                try {
+                    $httpBody = json_encode($formParams, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                // for HTTP post (form)
+                $httpBody = ObjectSerializer::buildQuery($formParams);
+            }
+        }
+
+        // this endpoint requires Bearer authentication (access token)
+        if (!empty($this->config->getAccessToken())) {
+            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
+        }
+
+        $defaultHeaders = [];
+        if ($this->config->getUserAgent()) {
+            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
+        }
+
+        $headers = array_merge(
+            $defaultHeaders,
+            $headerParams,
+            $headers
+        );
+
+        $operationHost = $this->config->getHost();
+        $query = ObjectSerializer::buildQuery($queryParams);
+        return new Request(
+            'GET',
+            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
+            $headers,
+            $httpBody
+        );
+    }
+
+    /**
+     * Operation getApiV3TermsTerm
+     *
+     * 术语详情
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  string|null $channels 正文按这些 channel 解析(句子、术语),逗号分隔,最多 20 个;只认你看得见的,不给就用术语所在 channel (optional)
+     * @param  string|null $mode 正文模式 (optional, default to 'read')
+     * @param  string|null $format 正文格式:tree 给节点树 &#x60;body&#x60;,html 给 HTML 字符串 &#x60;html&#x60;(WebView 显示用) (optional, default to 'tree')
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return \WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails
+     */
+    public function getApiV3TermsTerm($term, $channels = null, $mode = 'read', $format = 'tree', string $contentType = self::contentTypes['getApiV3TermsTerm'][0])
+    {
+        list($response) = $this->getApiV3TermsTermWithHttpInfo($term, $channels, $mode, $format, $contentType);
+        return $response;
+    }
+
+    /**
+     * Operation getApiV3TermsTermWithHttpInfo
+     *
+     * 术语详情
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  string|null $channels 正文按这些 channel 解析(句子、术语),逗号分隔,最多 20 个;只认你看得见的,不给就用术语所在 channel (optional)
+     * @param  string|null $mode 正文模式 (optional, default to 'read')
+     * @param  string|null $format 正文格式:tree 给节点树 &#x60;body&#x60;,html 给 HTML 字符串 &#x60;html&#x60;(WebView 显示用) (optional, default to 'tree')
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return array of \WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     */
+    public function getApiV3TermsTermWithHttpInfo($term, $channels = null, $mode = 'read', $format = 'tree', string $contentType = self::contentTypes['getApiV3TermsTerm'][0])
+    {
+        $request = $this->getApiV3TermsTermRequest($term, $channels, $mode, $format, $contentType);
+
+        try {
+            $options = $this->createHttpClientOption();
+            try {
+                $response = $this->client->send($request, $options);
+            } catch (RequestException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
+                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
+                );
+            } catch (ConnectException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    null,
+                    null
+                );
+            }
+
+            $statusCode = $response->getStatusCode();
+
+
+            switch($statusCode) {
+                case 200:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                        $request,
+                        $response,
+                    );
+                case 403:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 422:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+            }
+
+            
+
+            if ($statusCode < 200 || $statusCode > 299) {
+                throw new ApiException(
+                    sprintf(
+                        '[%d] Error connecting to the API (%s)',
+                        $statusCode,
+                        (string) $request->getUri()
+                    ),
+                    $statusCode,
+                    $response->getHeaders(),
+                    (string) $response->getBody()
+                );
+            }
+
+            return $this->handleResponseWithDataType(
+                '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                $request,
+                $response,
+            );
+        } catch (ApiException $e) {
+            switch ($e->getCode()) {
+                case 200:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 403:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 422:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+            }
+        
+
+            throw $e;
+        }
+    }
+
+    /**
+     * Operation getApiV3TermsTermAsync
+     *
+     * 术语详情
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  string|null $channels 正文按这些 channel 解析(句子、术语),逗号分隔,最多 20 个;只认你看得见的,不给就用术语所在 channel (optional)
+     * @param  string|null $mode 正文模式 (optional, default to 'read')
+     * @param  string|null $format 正文格式:tree 给节点树 &#x60;body&#x60;,html 给 HTML 字符串 &#x60;html&#x60;(WebView 显示用) (optional, default to 'tree')
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function getApiV3TermsTermAsync($term, $channels = null, $mode = 'read', $format = 'tree', string $contentType = self::contentTypes['getApiV3TermsTerm'][0])
+    {
+        return $this->getApiV3TermsTermAsyncWithHttpInfo($term, $channels, $mode, $format, $contentType)
+            ->then(
+                function ($response) {
+                    return $response[0];
+                }
+            );
+    }
+
+    /**
+     * Operation getApiV3TermsTermAsyncWithHttpInfo
+     *
+     * 术语详情
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  string|null $channels 正文按这些 channel 解析(句子、术语),逗号分隔,最多 20 个;只认你看得见的,不给就用术语所在 channel (optional)
+     * @param  string|null $mode 正文模式 (optional, default to 'read')
+     * @param  string|null $format 正文格式:tree 给节点树 &#x60;body&#x60;,html 给 HTML 字符串 &#x60;html&#x60;(WebView 显示用) (optional, default to 'tree')
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function getApiV3TermsTermAsyncWithHttpInfo($term, $channels = null, $mode = 'read', $format = 'tree', string $contentType = self::contentTypes['getApiV3TermsTerm'][0])
+    {
+        $returnType = '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response';
+        $request = $this->getApiV3TermsTermRequest($term, $channels, $mode, $format, $contentType);
+
+        return $this->client
+            ->sendAsync($request, $this->createHttpClientOption())
+            ->then(
+                function ($response) use ($returnType) {
+                    if ($returnType === '\SplFileObject') {
+                        $content = $response->getBody(); //stream goes to serializer
+                    } else {
+                        $content = (string) $response->getBody();
+                        if ($returnType !== 'string') {
+                            $content = json_decode($content);
+                        }
+                    }
+
+                    return [
+                        ObjectSerializer::deserialize($content, $returnType, []),
+                        $response->getStatusCode(),
+                        $response->getHeaders()
+                    ];
+                },
+                function ($exception) {
+                    $response = $exception->getResponse();
+                    $statusCode = $response->getStatusCode();
+                    throw new ApiException(
+                        sprintf(
+                            '[%d] Error connecting to the API (%s)',
+                            $statusCode,
+                            $exception->getRequest()->getUri()
+                        ),
+                        $statusCode,
+                        $response->getHeaders(),
+                        (string) $response->getBody()
+                    );
+                }
+            );
+    }
+
+    /**
+     * Create request for operation 'getApiV3TermsTerm'
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  string|null $channels 正文按这些 channel 解析(句子、术语),逗号分隔,最多 20 个;只认你看得见的,不给就用术语所在 channel (optional)
+     * @param  string|null $mode 正文模式 (optional, default to 'read')
+     * @param  string|null $format 正文格式:tree 给节点树 &#x60;body&#x60;,html 给 HTML 字符串 &#x60;html&#x60;(WebView 显示用) (optional, default to 'tree')
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['getApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Psr7\Request
+     */
+    public function getApiV3TermsTermRequest($term, $channels = null, $mode = 'read', $format = 'tree', string $contentType = self::contentTypes['getApiV3TermsTerm'][0])
+    {
+
+        // verify the required parameter 'term' is set
+        if ($term === null || (is_array($term) && count($term) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $term when calling getApiV3TermsTerm'
+            );
+        }
+
+
+
+
+
+        $resourcePath = '/v3/terms/{term}';
+        $formParams = [];
+        $queryParams = [];
+        $headerParams = [];
+        $httpBody = '';
+        $multipart = false;
+
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $channels,
+            'channels', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $mode,
+            'mode', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+        // query params
+        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
+            $format,
+            'format', // param base name
+            'string', // openApiType
+            'form', // style
+            true, // explode
+            false // required
+        ) ?? []);
+
+
+        // path params
+        if ($term !== null) {
+            $resourcePath = str_replace(
+                '{term}',
+                ObjectSerializer::toPathValue($term),
+                $resourcePath
+            );
+        }
+
+
+        $headers = $this->headerSelector->selectHeaders(
+            ['application/json', 'application/problem+json', ],
+            $contentType,
+            $multipart
+        );
+
+        // for model (json/xml)
+        if (count($formParams) > 0) {
+            if ($multipart) {
+                $multipartContents = [];
+                foreach ($formParams as $formParamName => $formParamValue) {
+                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
+                    foreach ($formParamValueItems as $formParamValueItem) {
+                        $multipartContents[] = [
+                            'name' => $formParamName,
+                            'contents' => $formParamValueItem
+                        ];
+                    }
+                }
+                // for HTTP post (form)
+                $httpBody = new MultipartStream($multipartContents);
+
+            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the form parameters
+                try {
+                    $httpBody = json_encode($formParams, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                // for HTTP post (form)
+                $httpBody = ObjectSerializer::buildQuery($formParams);
+            }
+        }
+
+        // this endpoint requires Bearer authentication (access token)
+        if (!empty($this->config->getAccessToken())) {
+            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
+        }
+
+        $defaultHeaders = [];
+        if ($this->config->getUserAgent()) {
+            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
+        }
+
+        $headers = array_merge(
+            $defaultHeaders,
+            $headerParams,
+            $headers
+        );
+
+        $operationHost = $this->config->getHost();
+        $query = ObjectSerializer::buildQuery($queryParams);
+        return new Request(
+            'GET',
+            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
+            $headers,
+            $httpBody
+        );
+    }
+
+    /**
+     * Operation patchApiV3TermsTerm
+     *
+     * 改术语
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  \WikipaliApi\Model\PatchApiV3TermsTermRequest|null $patch_api_v3_terms_term_request patch_api_v3_terms_term_request (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['patchApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return \WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails
+     */
+    public function patchApiV3TermsTerm($term, $patch_api_v3_terms_term_request = null, string $contentType = self::contentTypes['patchApiV3TermsTerm'][0])
+    {
+        list($response) = $this->patchApiV3TermsTermWithHttpInfo($term, $patch_api_v3_terms_term_request, $contentType);
+        return $response;
+    }
+
+    /**
+     * Operation patchApiV3TermsTermWithHttpInfo
+     *
+     * 改术语
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  \WikipaliApi\Model\PatchApiV3TermsTermRequest|null $patch_api_v3_terms_term_request (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['patchApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \WikipaliApi\ApiException on non-2xx response or if the response body is not in the expected format
+     * @throws \InvalidArgumentException
+     * @return array of \WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails|\WikipaliApi\Model\ProblemDetails, HTTP status code, HTTP response headers (array of strings)
+     */
+    public function patchApiV3TermsTermWithHttpInfo($term, $patch_api_v3_terms_term_request = null, string $contentType = self::contentTypes['patchApiV3TermsTerm'][0])
+    {
+        $request = $this->patchApiV3TermsTermRequest($term, $patch_api_v3_terms_term_request, $contentType);
+
+        try {
+            $options = $this->createHttpClientOption();
+            try {
+                $response = $this->client->send($request, $options);
+            } catch (RequestException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
+                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
+                );
+            } catch (ConnectException $e) {
+                throw new ApiException(
+                    "[{$e->getCode()}] {$e->getMessage()}",
+                    (int) $e->getCode(),
+                    null,
+                    null
+                );
+            }
+
+            $statusCode = $response->getStatusCode();
+
+
+            switch($statusCode) {
+                case 200:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                        $request,
+                        $response,
+                    );
+                case 401:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 403:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 412:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 422:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+                case 428:
+                    return $this->handleResponseWithDataType(
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $request,
+                        $response,
+                    );
+            }
+
+            
+
+            if ($statusCode < 200 || $statusCode > 299) {
+                throw new ApiException(
+                    sprintf(
+                        '[%d] Error connecting to the API (%s)',
+                        $statusCode,
+                        (string) $request->getUri()
+                    ),
+                    $statusCode,
+                    $response->getHeaders(),
+                    (string) $response->getBody()
+                );
+            }
+
+            return $this->handleResponseWithDataType(
+                '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                $request,
+                $response,
+            );
+        } catch (ApiException $e) {
+            switch ($e->getCode()) {
+                case 200:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 401:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 403:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 412:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 422:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+                case 428:
+                    $data = ObjectSerializer::deserialize(
+                        $e->getResponseBody(),
+                        '\WikipaliApi\Model\ProblemDetails',
+                        $e->getResponseHeaders()
+                    );
+                    $e->setResponseObject($data);
+                    throw $e;
+            }
+        
+
+            throw $e;
+        }
+    }
+
+    /**
+     * Operation patchApiV3TermsTermAsync
+     *
+     * 改术语
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  \WikipaliApi\Model\PatchApiV3TermsTermRequest|null $patch_api_v3_terms_term_request (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['patchApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function patchApiV3TermsTermAsync($term, $patch_api_v3_terms_term_request = null, string $contentType = self::contentTypes['patchApiV3TermsTerm'][0])
+    {
+        return $this->patchApiV3TermsTermAsyncWithHttpInfo($term, $patch_api_v3_terms_term_request, $contentType)
+            ->then(
+                function ($response) {
+                    return $response[0];
+                }
+            );
+    }
+
+    /**
+     * Operation patchApiV3TermsTermAsyncWithHttpInfo
+     *
+     * 改术语
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  \WikipaliApi\Model\PatchApiV3TermsTermRequest|null $patch_api_v3_terms_term_request (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['patchApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Promise\PromiseInterface
+     */
+    public function patchApiV3TermsTermAsyncWithHttpInfo($term, $patch_api_v3_terms_term_request = null, string $contentType = self::contentTypes['patchApiV3TermsTerm'][0])
+    {
+        $returnType = '\WikipaliApi\Model\PostApiV3ChannelsChannelTerms200Response';
+        $request = $this->patchApiV3TermsTermRequest($term, $patch_api_v3_terms_term_request, $contentType);
+
+        return $this->client
+            ->sendAsync($request, $this->createHttpClientOption())
+            ->then(
+                function ($response) use ($returnType) {
+                    if ($returnType === '\SplFileObject') {
+                        $content = $response->getBody(); //stream goes to serializer
+                    } else {
+                        $content = (string) $response->getBody();
+                        if ($returnType !== 'string') {
+                            $content = json_decode($content);
+                        }
+                    }
+
+                    return [
+                        ObjectSerializer::deserialize($content, $returnType, []),
+                        $response->getStatusCode(),
+                        $response->getHeaders()
+                    ];
+                },
+                function ($exception) {
+                    $response = $exception->getResponse();
+                    $statusCode = $response->getStatusCode();
+                    throw new ApiException(
+                        sprintf(
+                            '[%d] Error connecting to the API (%s)',
+                            $statusCode,
+                            $exception->getRequest()->getUri()
+                        ),
+                        $statusCode,
+                        $response->getHeaders(),
+                        (string) $response->getBody()
+                    );
+                }
+            );
+    }
+
+    /**
+     * Create request for operation 'patchApiV3TermsTerm'
+     *
+     * @param  string $term 术语 id(guid) (required)
+     * @param  \WikipaliApi\Model\PatchApiV3TermsTermRequest|null $patch_api_v3_terms_term_request (optional)
+     * @param  string $contentType The value for the Content-Type header. Check self::contentTypes['patchApiV3TermsTerm'] to see the possible values for this operation
+     *
+     * @throws \InvalidArgumentException
+     * @return \GuzzleHttp\Psr7\Request
+     */
+    public function patchApiV3TermsTermRequest($term, $patch_api_v3_terms_term_request = null, string $contentType = self::contentTypes['patchApiV3TermsTerm'][0])
+    {
+
+        // verify the required parameter 'term' is set
+        if ($term === null || (is_array($term) && count($term) === 0)) {
+            throw new \InvalidArgumentException(
+                'Missing the required parameter $term when calling patchApiV3TermsTerm'
+            );
+        }
+
+
+
+        $resourcePath = '/v3/terms/{term}';
+        $formParams = [];
+        $queryParams = [];
+        $headerParams = [];
+        $httpBody = '';
+        $multipart = false;
+
+
+
+        // path params
+        if ($term !== null) {
+            $resourcePath = str_replace(
+                '{term}',
+                ObjectSerializer::toPathValue($term),
+                $resourcePath
+            );
+        }
+
+
+        $headers = $this->headerSelector->selectHeaders(
+            ['application/json', 'application/problem+json', ],
+            $contentType,
+            $multipart
+        );
+
+        // for model (json/xml)
+        if (isset($patch_api_v3_terms_term_request)) {
+            if (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the body
+                try {
+                    $httpBody = json_encode(ObjectSerializer::sanitizeForSerialization($patch_api_v3_terms_term_request), JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                $httpBody = $patch_api_v3_terms_term_request;
+            }
+        } elseif (count($formParams) > 0) {
+            if ($multipart) {
+                $multipartContents = [];
+                foreach ($formParams as $formParamName => $formParamValue) {
+                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
+                    foreach ($formParamValueItems as $formParamValueItem) {
+                        $multipartContents[] = [
+                            'name' => $formParamName,
+                            'contents' => $formParamValueItem
+                        ];
+                    }
+                }
+                // for HTTP post (form)
+                $httpBody = new MultipartStream($multipartContents);
+
+            } elseif (stripos($headers['Content-Type'], 'application/json') !== false) {
+                # if Content-Type contains "application/json", json_encode the form parameters
+                try {
+                    $httpBody = json_encode($formParams, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $e) {
+                    throw new \InvalidArgumentException('json_encode error: ' . $e->getMessage(), 0, $e);
+                }
+            } else {
+                // for HTTP post (form)
+                $httpBody = ObjectSerializer::buildQuery($formParams);
+            }
+        }
+
+        // this endpoint requires Bearer authentication (access token)
+        if (!empty($this->config->getAccessToken())) {
+            $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken();
+        }
+
+        $defaultHeaders = [];
+        if ($this->config->getUserAgent()) {
+            $defaultHeaders['User-Agent'] = $this->config->getUserAgent();
+        }
+
+        $headers = array_merge(
+            $defaultHeaders,
+            $headerParams,
+            $headers
+        );
+
+        $operationHost = $this->config->getHost();
+        $query = ObjectSerializer::buildQuery($queryParams);
+        return new Request(
+            'PATCH',
+            $operationHost . $resourcePath . ($query ? "?{$query}" : ''),
+            $headers,
+            $httpBody
+        );
+    }
+
+    /**
+     * Create http client option
+     *
+     * @throws \RuntimeException on file opening failure
+     * @return array of http client options
+     */
+    protected function createHttpClientOption()
+    {
+        $options = [];
+        if ($this->config->getDebug()) {
+            $options[RequestOptions::DEBUG] = fopen($this->config->getDebugFile(), 'a');
+            if (!$options[RequestOptions::DEBUG]) {
+                throw new \RuntimeException('Failed to open the debug file: ' . $this->config->getDebugFile());
+            }
+        }
+
+        if ($this->config->getCertFile()) {
+            $options[RequestOptions::CERT] = $this->config->getCertFile();
+        }
+
+        if ($this->config->getKeyFile()) {
+            $options[RequestOptions::SSL_KEY] = $this->config->getKeyFile();
+        }
+
+        return $options;
+    }
+
+    private function handleResponseWithDataType(
+        string $dataType,
+        RequestInterface $request,
+        ResponseInterface $response
+    ): array {
+        if ($dataType === '\SplFileObject') {
+            $content = $response->getBody(); //stream goes to serializer
+        } else {
+            $content = (string) $response->getBody();
+            if ($dataType !== 'string') {
+                try {
+                    $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
+                } catch (\JsonException $exception) {
+                    throw new ApiException(
+                        sprintf(
+                            'Error JSON decoding server response (%s)',
+                            $request->getUri()
+                        ),
+                        $response->getStatusCode(),
+                        $response->getHeaders(),
+                        $content
+                    );
+                }
+            }
+        }
+
+        return [
+            ObjectSerializer::deserialize($content, $dataType, []),
+            $response->getStatusCode(),
+            $response->getHeaders()
+        ];
+    }
+
+    private function responseWithinRangeCode(
+        string $rangeCode,
+        int $statusCode
+    ): bool {
+        $left = (int) ($rangeCode[0].'00');
+        $right = (int) ($rangeCode[0].'99');
+
+        return $statusCode >= $left && $statusCode <= $right;
+    }
+}

+ 443 - 0
api-test/client/lib/Model/GetApiV3ChannelsChannelTerms200Response.php

@@ -0,0 +1,443 @@
+<?php
+/**
+ * GetApiV3ChannelsChannelTerms200Response
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * GetApiV3ChannelsChannelTerms200Response Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class GetApiV3ChannelsChannelTerms200Response implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'get_api_v3_channels_channel_terms_200_response';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'data' => '\WikipaliApi\Model\GetApiV3ChannelsChannelTerms200ResponseDataInner[]',
+        'meta' => '\WikipaliApi\Model\PaginationMeta'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'data' => null,
+        'meta' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'data' => false,
+        'meta' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'data' => 'data',
+        'meta' => 'meta'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'data' => 'setData',
+        'meta' => 'setMeta'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'data' => 'getData',
+        'meta' => 'getMeta'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('data', $data ?? [], null);
+        $this->setIfExists('meta', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets data
+     *
+     * @return \WikipaliApi\Model\GetApiV3ChannelsChannelTerms200ResponseDataInner[]|null
+     */
+    public function getData()
+    {
+        return $this->container['data'];
+    }
+
+    /**
+     * Sets data
+     *
+     * @param \WikipaliApi\Model\GetApiV3ChannelsChannelTerms200ResponseDataInner[]|null $data data
+     *
+     * @return self
+     */
+    public function setData($data)
+    {
+        if (is_null($data)) {
+            throw new \InvalidArgumentException('non-nullable data cannot be null');
+        }
+        $this->container['data'] = $data;
+
+        return $this;
+    }
+
+    /**
+     * Gets meta
+     *
+     * @return \WikipaliApi\Model\PaginationMeta|null
+     */
+    public function getMeta()
+    {
+        return $this->container['meta'];
+    }
+
+    /**
+     * Sets meta
+     *
+     * @param \WikipaliApi\Model\PaginationMeta|null $meta meta
+     *
+     * @return self
+     */
+    public function setMeta($meta)
+    {
+        if (is_null($meta)) {
+            throw new \InvalidArgumentException('non-nullable meta cannot be null');
+        }
+        $this->container['meta'] = $meta;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 1302 - 0
api-test/client/lib/Model/GetApiV3ChannelsChannelTerms200ResponseDataInner.php

@@ -0,0 +1,1302 @@
+<?php
+/**
+ * GetApiV3ChannelsChannelTerms200ResponseDataInner
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * GetApiV3ChannelsChannelTerms200ResponseDataInner Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class GetApiV3ChannelsChannelTerms200ResponseDataInner implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'get_api_v3_channels_channel_terms_200_response_data_inner';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'id' => 'string',
+        'word' => 'string',
+        'tag' => 'string',
+        'meaning' => 'string',
+        'other_meaning' => 'string',
+        'language' => 'string',
+        'channel_id' => 'string',
+        'channel' => '\WikipaliApi\Model\GetApiV3ChannelsChannelTerms200ResponseDataInnerChannel',
+        'owner_id' => 'string',
+        'quality' => 'string',
+        'content_type' => 'string',
+        'summary' => 'string',
+        'note' => 'string',
+        'redirect' => 'string',
+        'categories' => 'string[]',
+        'summary_text' => 'string',
+        'body' => '\WikipaliApi\Model\MarkupNode[]',
+        'html' => 'string',
+        'editor' => '\WikipaliApi\Model\GetApiV3AdminAgentRuns200ResponseDataInnerUser',
+        'co_editor' => '\WikipaliApi\Model\GetApiV3AdminAgentRuns200ResponseDataInnerUser',
+        'etag' => 'string',
+        'abilities' => '\WikipaliApi\Model\GetApiV3ChannelsChannelTerms200ResponseDataInnerAbilities',
+        'created_at' => 'string',
+        'updated_at' => 'string',
+        'deleted_at' => 'string'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'id' => null,
+        'word' => null,
+        'tag' => null,
+        'meaning' => null,
+        'other_meaning' => null,
+        'language' => null,
+        'channel_id' => null,
+        'channel' => null,
+        'owner_id' => null,
+        'quality' => null,
+        'content_type' => null,
+        'summary' => null,
+        'note' => null,
+        'redirect' => null,
+        'categories' => null,
+        'summary_text' => null,
+        'body' => null,
+        'html' => null,
+        'editor' => null,
+        'co_editor' => null,
+        'etag' => null,
+        'abilities' => null,
+        'created_at' => null,
+        'updated_at' => null,
+        'deleted_at' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'id' => false,
+        'word' => false,
+        'tag' => true,
+        'meaning' => false,
+        'other_meaning' => true,
+        'language' => false,
+        'channel_id' => true,
+        'channel' => true,
+        'owner_id' => false,
+        'quality' => true,
+        'content_type' => false,
+        'summary' => true,
+        'note' => true,
+        'redirect' => true,
+        'categories' => false,
+        'summary_text' => false,
+        'body' => false,
+        'html' => false,
+        'editor' => true,
+        'co_editor' => true,
+        'etag' => false,
+        'abilities' => false,
+        'created_at' => false,
+        'updated_at' => false,
+        'deleted_at' => true
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'id' => 'id',
+        'word' => 'word',
+        'tag' => 'tag',
+        'meaning' => 'meaning',
+        'other_meaning' => 'other_meaning',
+        'language' => 'language',
+        'channel_id' => 'channel_id',
+        'channel' => 'channel',
+        'owner_id' => 'owner_id',
+        'quality' => 'quality',
+        'content_type' => 'content_type',
+        'summary' => 'summary',
+        'note' => 'note',
+        'redirect' => 'redirect',
+        'categories' => 'categories',
+        'summary_text' => 'summary_text',
+        'body' => 'body',
+        'html' => 'html',
+        'editor' => 'editor',
+        'co_editor' => 'co_editor',
+        'etag' => 'etag',
+        'abilities' => 'abilities',
+        'created_at' => 'created_at',
+        'updated_at' => 'updated_at',
+        'deleted_at' => 'deleted_at'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'id' => 'setId',
+        'word' => 'setWord',
+        'tag' => 'setTag',
+        'meaning' => 'setMeaning',
+        'other_meaning' => 'setOtherMeaning',
+        'language' => 'setLanguage',
+        'channel_id' => 'setChannelId',
+        'channel' => 'setChannel',
+        'owner_id' => 'setOwnerId',
+        'quality' => 'setQuality',
+        'content_type' => 'setContentType',
+        'summary' => 'setSummary',
+        'note' => 'setNote',
+        'redirect' => 'setRedirect',
+        'categories' => 'setCategories',
+        'summary_text' => 'setSummaryText',
+        'body' => 'setBody',
+        'html' => 'setHtml',
+        'editor' => 'setEditor',
+        'co_editor' => 'setCoEditor',
+        'etag' => 'setEtag',
+        'abilities' => 'setAbilities',
+        'created_at' => 'setCreatedAt',
+        'updated_at' => 'setUpdatedAt',
+        'deleted_at' => 'setDeletedAt'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'id' => 'getId',
+        'word' => 'getWord',
+        'tag' => 'getTag',
+        'meaning' => 'getMeaning',
+        'other_meaning' => 'getOtherMeaning',
+        'language' => 'getLanguage',
+        'channel_id' => 'getChannelId',
+        'channel' => 'getChannel',
+        'owner_id' => 'getOwnerId',
+        'quality' => 'getQuality',
+        'content_type' => 'getContentType',
+        'summary' => 'getSummary',
+        'note' => 'getNote',
+        'redirect' => 'getRedirect',
+        'categories' => 'getCategories',
+        'summary_text' => 'getSummaryText',
+        'body' => 'getBody',
+        'html' => 'getHtml',
+        'editor' => 'getEditor',
+        'co_editor' => 'getCoEditor',
+        'etag' => 'getEtag',
+        'abilities' => 'getAbilities',
+        'created_at' => 'getCreatedAt',
+        'updated_at' => 'getUpdatedAt',
+        'deleted_at' => 'getDeletedAt'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('id', $data ?? [], null);
+        $this->setIfExists('word', $data ?? [], null);
+        $this->setIfExists('tag', $data ?? [], null);
+        $this->setIfExists('meaning', $data ?? [], null);
+        $this->setIfExists('other_meaning', $data ?? [], null);
+        $this->setIfExists('language', $data ?? [], null);
+        $this->setIfExists('channel_id', $data ?? [], null);
+        $this->setIfExists('channel', $data ?? [], null);
+        $this->setIfExists('owner_id', $data ?? [], null);
+        $this->setIfExists('quality', $data ?? [], null);
+        $this->setIfExists('content_type', $data ?? [], null);
+        $this->setIfExists('summary', $data ?? [], null);
+        $this->setIfExists('note', $data ?? [], null);
+        $this->setIfExists('redirect', $data ?? [], null);
+        $this->setIfExists('categories', $data ?? [], null);
+        $this->setIfExists('summary_text', $data ?? [], null);
+        $this->setIfExists('body', $data ?? [], null);
+        $this->setIfExists('html', $data ?? [], null);
+        $this->setIfExists('editor', $data ?? [], null);
+        $this->setIfExists('co_editor', $data ?? [], null);
+        $this->setIfExists('etag', $data ?? [], null);
+        $this->setIfExists('abilities', $data ?? [], null);
+        $this->setIfExists('created_at', $data ?? [], null);
+        $this->setIfExists('updated_at', $data ?? [], null);
+        $this->setIfExists('deleted_at', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets id
+     *
+     * @return string|null
+     */
+    public function getId()
+    {
+        return $this->container['id'];
+    }
+
+    /**
+     * Sets id
+     *
+     * @param string|null $id id
+     *
+     * @return self
+     */
+    public function setId($id)
+    {
+        if (is_null($id)) {
+            throw new \InvalidArgumentException('non-nullable id cannot be null');
+        }
+        $this->container['id'] = $id;
+
+        return $this;
+    }
+
+    /**
+     * Gets word
+     *
+     * @return string|null
+     */
+    public function getWord()
+    {
+        return $this->container['word'];
+    }
+
+    /**
+     * Sets word
+     *
+     * @param string|null $word word
+     *
+     * @return self
+     */
+    public function setWord($word)
+    {
+        if (is_null($word)) {
+            throw new \InvalidArgumentException('non-nullable word cannot be null');
+        }
+        $this->container['word'] = $word;
+
+        return $this;
+    }
+
+    /**
+     * Gets tag
+     *
+     * @return string|null
+     */
+    public function getTag()
+    {
+        return $this->container['tag'];
+    }
+
+    /**
+     * Sets tag
+     *
+     * @param string|null $tag tag
+     *
+     * @return self
+     */
+    public function setTag($tag)
+    {
+        if (is_null($tag)) {
+            array_push($this->openAPINullablesSetToNull, 'tag');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('tag', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['tag'] = $tag;
+
+        return $this;
+    }
+
+    /**
+     * Gets meaning
+     *
+     * @return string|null
+     */
+    public function getMeaning()
+    {
+        return $this->container['meaning'];
+    }
+
+    /**
+     * Sets meaning
+     *
+     * @param string|null $meaning meaning
+     *
+     * @return self
+     */
+    public function setMeaning($meaning)
+    {
+        if (is_null($meaning)) {
+            throw new \InvalidArgumentException('non-nullable meaning cannot be null');
+        }
+        $this->container['meaning'] = $meaning;
+
+        return $this;
+    }
+
+    /**
+     * Gets other_meaning
+     *
+     * @return string|null
+     */
+    public function getOtherMeaning()
+    {
+        return $this->container['other_meaning'];
+    }
+
+    /**
+     * Sets other_meaning
+     *
+     * @param string|null $other_meaning other_meaning
+     *
+     * @return self
+     */
+    public function setOtherMeaning($other_meaning)
+    {
+        if (is_null($other_meaning)) {
+            array_push($this->openAPINullablesSetToNull, 'other_meaning');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('other_meaning', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['other_meaning'] = $other_meaning;
+
+        return $this;
+    }
+
+    /**
+     * Gets language
+     *
+     * @return string|null
+     */
+    public function getLanguage()
+    {
+        return $this->container['language'];
+    }
+
+    /**
+     * Sets language
+     *
+     * @param string|null $language language
+     *
+     * @return self
+     */
+    public function setLanguage($language)
+    {
+        if (is_null($language)) {
+            throw new \InvalidArgumentException('non-nullable language cannot be null');
+        }
+        $this->container['language'] = $language;
+
+        return $this;
+    }
+
+    /**
+     * Gets channel_id
+     *
+     * @return string|null
+     */
+    public function getChannelId()
+    {
+        return $this->container['channel_id'];
+    }
+
+    /**
+     * Sets channel_id
+     *
+     * @param string|null $channel_id channel_id
+     *
+     * @return self
+     */
+    public function setChannelId($channel_id)
+    {
+        if (is_null($channel_id)) {
+            array_push($this->openAPINullablesSetToNull, 'channel_id');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('channel_id', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['channel_id'] = $channel_id;
+
+        return $this;
+    }
+
+    /**
+     * Gets channel
+     *
+     * @return \WikipaliApi\Model\GetApiV3ChannelsChannelTerms200ResponseDataInnerChannel|null
+     */
+    public function getChannel()
+    {
+        return $this->container['channel'];
+    }
+
+    /**
+     * Sets channel
+     *
+     * @param \WikipaliApi\Model\GetApiV3ChannelsChannelTerms200ResponseDataInnerChannel|null $channel channel
+     *
+     * @return self
+     */
+    public function setChannel($channel)
+    {
+        if (is_null($channel)) {
+            array_push($this->openAPINullablesSetToNull, 'channel');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('channel', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['channel'] = $channel;
+
+        return $this;
+    }
+
+    /**
+     * Gets owner_id
+     *
+     * @return string|null
+     */
+    public function getOwnerId()
+    {
+        return $this->container['owner_id'];
+    }
+
+    /**
+     * Sets owner_id
+     *
+     * @param string|null $owner_id owner_id
+     *
+     * @return self
+     */
+    public function setOwnerId($owner_id)
+    {
+        if (is_null($owner_id)) {
+            throw new \InvalidArgumentException('non-nullable owner_id cannot be null');
+        }
+        $this->container['owner_id'] = $owner_id;
+
+        return $this;
+    }
+
+    /**
+     * Gets quality
+     *
+     * @return string|null
+     */
+    public function getQuality()
+    {
+        return $this->container['quality'];
+    }
+
+    /**
+     * Sets quality
+     *
+     * @param string|null $quality quality
+     *
+     * @return self
+     */
+    public function setQuality($quality)
+    {
+        if (is_null($quality)) {
+            array_push($this->openAPINullablesSetToNull, 'quality');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('quality', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['quality'] = $quality;
+
+        return $this;
+    }
+
+    /**
+     * Gets content_type
+     *
+     * @return string|null
+     */
+    public function getContentType()
+    {
+        return $this->container['content_type'];
+    }
+
+    /**
+     * Sets content_type
+     *
+     * @param string|null $content_type content_type
+     *
+     * @return self
+     */
+    public function setContentType($content_type)
+    {
+        if (is_null($content_type)) {
+            throw new \InvalidArgumentException('non-nullable content_type cannot be null');
+        }
+        $this->container['content_type'] = $content_type;
+
+        return $this;
+    }
+
+    /**
+     * Gets summary
+     *
+     * @return string|null
+     */
+    public function getSummary()
+    {
+        return $this->container['summary'];
+    }
+
+    /**
+     * Sets summary
+     *
+     * @param string|null $summary summary
+     *
+     * @return self
+     */
+    public function setSummary($summary)
+    {
+        if (is_null($summary)) {
+            array_push($this->openAPINullablesSetToNull, 'summary');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('summary', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['summary'] = $summary;
+
+        return $this;
+    }
+
+    /**
+     * Gets note
+     *
+     * @return string|null
+     */
+    public function getNote()
+    {
+        return $this->container['note'];
+    }
+
+    /**
+     * Sets note
+     *
+     * @param string|null $note note
+     *
+     * @return self
+     */
+    public function setNote($note)
+    {
+        if (is_null($note)) {
+            array_push($this->openAPINullablesSetToNull, 'note');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('note', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['note'] = $note;
+
+        return $this;
+    }
+
+    /**
+     * Gets redirect
+     *
+     * @return string|null
+     */
+    public function getRedirect()
+    {
+        return $this->container['redirect'];
+    }
+
+    /**
+     * Sets redirect
+     *
+     * @param string|null $redirect redirect
+     *
+     * @return self
+     */
+    public function setRedirect($redirect)
+    {
+        if (is_null($redirect)) {
+            array_push($this->openAPINullablesSetToNull, 'redirect');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('redirect', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['redirect'] = $redirect;
+
+        return $this;
+    }
+
+    /**
+     * Gets categories
+     *
+     * @return string[]|null
+     */
+    public function getCategories()
+    {
+        return $this->container['categories'];
+    }
+
+    /**
+     * Sets categories
+     *
+     * @param string[]|null $categories categories
+     *
+     * @return self
+     */
+    public function setCategories($categories)
+    {
+        if (is_null($categories)) {
+            throw new \InvalidArgumentException('non-nullable categories cannot be null');
+        }
+        $this->container['categories'] = $categories;
+
+        return $this;
+    }
+
+    /**
+     * Gets summary_text
+     *
+     * @return string|null
+     */
+    public function getSummaryText()
+    {
+        return $this->container['summary_text'];
+    }
+
+    /**
+     * Sets summary_text
+     *
+     * @param string|null $summary_text summary_text
+     *
+     * @return self
+     */
+    public function setSummaryText($summary_text)
+    {
+        if (is_null($summary_text)) {
+            throw new \InvalidArgumentException('non-nullable summary_text cannot be null');
+        }
+        $this->container['summary_text'] = $summary_text;
+
+        return $this;
+    }
+
+    /**
+     * Gets body
+     *
+     * @return \WikipaliApi\Model\MarkupNode[]|null
+     */
+    public function getBody()
+    {
+        return $this->container['body'];
+    }
+
+    /**
+     * Sets body
+     *
+     * @param \WikipaliApi\Model\MarkupNode[]|null $body 仅在部分查询口径下返回。
+     *
+     * @return self
+     */
+    public function setBody($body)
+    {
+        if (is_null($body)) {
+            throw new \InvalidArgumentException('non-nullable body cannot be null');
+        }
+        $this->container['body'] = $body;
+
+        return $this;
+    }
+
+    /**
+     * Gets html
+     *
+     * @return string|null
+     */
+    public function getHtml()
+    {
+        return $this->container['html'];
+    }
+
+    /**
+     * Sets html
+     *
+     * @param string|null $html 仅在部分查询口径下返回。
+     *
+     * @return self
+     */
+    public function setHtml($html)
+    {
+        if (is_null($html)) {
+            throw new \InvalidArgumentException('non-nullable html cannot be null');
+        }
+        $this->container['html'] = $html;
+
+        return $this;
+    }
+
+    /**
+     * Gets editor
+     *
+     * @return \WikipaliApi\Model\GetApiV3AdminAgentRuns200ResponseDataInnerUser|null
+     */
+    public function getEditor()
+    {
+        return $this->container['editor'];
+    }
+
+    /**
+     * Sets editor
+     *
+     * @param \WikipaliApi\Model\GetApiV3AdminAgentRuns200ResponseDataInnerUser|null $editor editor
+     *
+     * @return self
+     */
+    public function setEditor($editor)
+    {
+        if (is_null($editor)) {
+            array_push($this->openAPINullablesSetToNull, 'editor');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('editor', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['editor'] = $editor;
+
+        return $this;
+    }
+
+    /**
+     * Gets co_editor
+     *
+     * @return \WikipaliApi\Model\GetApiV3AdminAgentRuns200ResponseDataInnerUser|null
+     */
+    public function getCoEditor()
+    {
+        return $this->container['co_editor'];
+    }
+
+    /**
+     * Sets co_editor
+     *
+     * @param \WikipaliApi\Model\GetApiV3AdminAgentRuns200ResponseDataInnerUser|null $co_editor co_editor
+     *
+     * @return self
+     */
+    public function setCoEditor($co_editor)
+    {
+        if (is_null($co_editor)) {
+            array_push($this->openAPINullablesSetToNull, 'co_editor');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('co_editor', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['co_editor'] = $co_editor;
+
+        return $this;
+    }
+
+    /**
+     * Gets etag
+     *
+     * @return string|null
+     */
+    public function getEtag()
+    {
+        return $this->container['etag'];
+    }
+
+    /**
+     * Sets etag
+     *
+     * @param string|null $etag etag
+     *
+     * @return self
+     */
+    public function setEtag($etag)
+    {
+        if (is_null($etag)) {
+            throw new \InvalidArgumentException('non-nullable etag cannot be null');
+        }
+        $this->container['etag'] = $etag;
+
+        return $this;
+    }
+
+    /**
+     * Gets abilities
+     *
+     * @return \WikipaliApi\Model\GetApiV3ChannelsChannelTerms200ResponseDataInnerAbilities|null
+     */
+    public function getAbilities()
+    {
+        return $this->container['abilities'];
+    }
+
+    /**
+     * Sets abilities
+     *
+     * @param \WikipaliApi\Model\GetApiV3ChannelsChannelTerms200ResponseDataInnerAbilities|null $abilities abilities
+     *
+     * @return self
+     */
+    public function setAbilities($abilities)
+    {
+        if (is_null($abilities)) {
+            throw new \InvalidArgumentException('non-nullable abilities cannot be null');
+        }
+        $this->container['abilities'] = $abilities;
+
+        return $this;
+    }
+
+    /**
+     * Gets created_at
+     *
+     * @return string|null
+     */
+    public function getCreatedAt()
+    {
+        return $this->container['created_at'];
+    }
+
+    /**
+     * Sets created_at
+     *
+     * @param string|null $created_at created_at
+     *
+     * @return self
+     */
+    public function setCreatedAt($created_at)
+    {
+        if (is_null($created_at)) {
+            throw new \InvalidArgumentException('non-nullable created_at cannot be null');
+        }
+        $this->container['created_at'] = $created_at;
+
+        return $this;
+    }
+
+    /**
+     * Gets updated_at
+     *
+     * @return string|null
+     */
+    public function getUpdatedAt()
+    {
+        return $this->container['updated_at'];
+    }
+
+    /**
+     * Sets updated_at
+     *
+     * @param string|null $updated_at updated_at
+     *
+     * @return self
+     */
+    public function setUpdatedAt($updated_at)
+    {
+        if (is_null($updated_at)) {
+            throw new \InvalidArgumentException('non-nullable updated_at cannot be null');
+        }
+        $this->container['updated_at'] = $updated_at;
+
+        return $this;
+    }
+
+    /**
+     * Gets deleted_at
+     *
+     * @return string|null
+     */
+    public function getDeletedAt()
+    {
+        return $this->container['deleted_at'];
+    }
+
+    /**
+     * Sets deleted_at
+     *
+     * @param string|null $deleted_at deleted_at
+     *
+     * @return self
+     */
+    public function setDeletedAt($deleted_at)
+    {
+        if (is_null($deleted_at)) {
+            array_push($this->openAPINullablesSetToNull, 'deleted_at');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('deleted_at', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['deleted_at'] = $deleted_at;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 443 - 0
api-test/client/lib/Model/GetApiV3ChannelsChannelTerms200ResponseDataInnerAbilities.php

@@ -0,0 +1,443 @@
+<?php
+/**
+ * GetApiV3ChannelsChannelTerms200ResponseDataInnerAbilities
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * GetApiV3ChannelsChannelTerms200ResponseDataInnerAbilities Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class GetApiV3ChannelsChannelTerms200ResponseDataInnerAbilities implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'get_api_v3_channels_channel_terms_200_response_data_inner_abilities';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'update' => 'bool',
+        'delete' => 'bool'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'update' => null,
+        'delete' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'update' => false,
+        'delete' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'update' => 'update',
+        'delete' => 'delete'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'update' => 'setUpdate',
+        'delete' => 'setDelete'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'update' => 'getUpdate',
+        'delete' => 'getDelete'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('update', $data ?? [], null);
+        $this->setIfExists('delete', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets update
+     *
+     * @return bool|null
+     */
+    public function getUpdate()
+    {
+        return $this->container['update'];
+    }
+
+    /**
+     * Sets update
+     *
+     * @param bool|null $update update
+     *
+     * @return self
+     */
+    public function setUpdate($update)
+    {
+        if (is_null($update)) {
+            throw new \InvalidArgumentException('non-nullable update cannot be null');
+        }
+        $this->container['update'] = $update;
+
+        return $this;
+    }
+
+    /**
+     * Gets delete
+     *
+     * @return bool|null
+     */
+    public function getDelete()
+    {
+        return $this->container['delete'];
+    }
+
+    /**
+     * Sets delete
+     *
+     * @param bool|null $delete delete
+     *
+     * @return self
+     */
+    public function setDelete($delete)
+    {
+        if (is_null($delete)) {
+            throw new \InvalidArgumentException('non-nullable delete cannot be null');
+        }
+        $this->container['delete'] = $delete;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 443 - 0
api-test/client/lib/Model/GetApiV3ChannelsChannelTerms200ResponseDataInnerChannel.php

@@ -0,0 +1,443 @@
+<?php
+/**
+ * GetApiV3ChannelsChannelTerms200ResponseDataInnerChannel
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * GetApiV3ChannelsChannelTerms200ResponseDataInnerChannel Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class GetApiV3ChannelsChannelTerms200ResponseDataInnerChannel implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'get_api_v3_channels_channel_terms_200_response_data_inner_channel';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'id' => 'string',
+        'name' => 'string'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'id' => null,
+        'name' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'id' => false,
+        'name' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'id' => 'id',
+        'name' => 'name'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'id' => 'setId',
+        'name' => 'setName'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'id' => 'getId',
+        'name' => 'getName'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('id', $data ?? [], null);
+        $this->setIfExists('name', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets id
+     *
+     * @return string|null
+     */
+    public function getId()
+    {
+        return $this->container['id'];
+    }
+
+    /**
+     * Sets id
+     *
+     * @param string|null $id id
+     *
+     * @return self
+     */
+    public function setId($id)
+    {
+        if (is_null($id)) {
+            throw new \InvalidArgumentException('non-nullable id cannot be null');
+        }
+        $this->container['id'] = $id;
+
+        return $this;
+    }
+
+    /**
+     * Gets name
+     *
+     * @return string|null
+     */
+    public function getName()
+    {
+        return $this->container['name'];
+    }
+
+    /**
+     * Sets name
+     *
+     * @param string|null $name name
+     *
+     * @return self
+     */
+    public function setName($name)
+    {
+        if (is_null($name)) {
+            throw new \InvalidArgumentException('non-nullable name cannot be null');
+        }
+        $this->container['name'] = $name;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 443 - 0
api-test/client/lib/Model/GetApiV3GlossariesKind200Response.php

@@ -0,0 +1,443 @@
+<?php
+/**
+ * GetApiV3GlossariesKind200Response
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * GetApiV3GlossariesKind200Response Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class GetApiV3GlossariesKind200Response implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'get_api_v3_glossaries_kind__200_response';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'data' => '\WikipaliApi\Model\GetApiV3GlossariesKind200ResponseDataInner[]',
+        'meta' => '\WikipaliApi\Model\GetApiV3GlossariesKind200ResponseMeta'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'data' => null,
+        'meta' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'data' => false,
+        'meta' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'data' => 'data',
+        'meta' => 'meta'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'data' => 'setData',
+        'meta' => 'setMeta'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'data' => 'getData',
+        'meta' => 'getMeta'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('data', $data ?? [], null);
+        $this->setIfExists('meta', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets data
+     *
+     * @return \WikipaliApi\Model\GetApiV3GlossariesKind200ResponseDataInner[]|null
+     */
+    public function getData()
+    {
+        return $this->container['data'];
+    }
+
+    /**
+     * Sets data
+     *
+     * @param \WikipaliApi\Model\GetApiV3GlossariesKind200ResponseDataInner[]|null $data data
+     *
+     * @return self
+     */
+    public function setData($data)
+    {
+        if (is_null($data)) {
+            throw new \InvalidArgumentException('non-nullable data cannot be null');
+        }
+        $this->container['data'] = $data;
+
+        return $this;
+    }
+
+    /**
+     * Gets meta
+     *
+     * @return \WikipaliApi\Model\GetApiV3GlossariesKind200ResponseMeta|null
+     */
+    public function getMeta()
+    {
+        return $this->container['meta'];
+    }
+
+    /**
+     * Sets meta
+     *
+     * @param \WikipaliApi\Model\GetApiV3GlossariesKind200ResponseMeta|null $meta meta
+     *
+     * @return self
+     */
+    public function setMeta($meta)
+    {
+        if (is_null($meta)) {
+            throw new \InvalidArgumentException('non-nullable meta cannot be null');
+        }
+        $this->container['meta'] = $meta;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 559 - 0
api-test/client/lib/Model/GetApiV3GlossariesKind200ResponseDataInner.php

@@ -0,0 +1,559 @@
+<?php
+/**
+ * GetApiV3GlossariesKind200ResponseDataInner
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * GetApiV3GlossariesKind200ResponseDataInner Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class GetApiV3GlossariesKind200ResponseDataInner implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'get_api_v3_glossaries_kind__200_response_data_inner';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'id' => 'string',
+        'word' => 'string',
+        'tag' => 'string',
+        'meaning' => 'string',
+        'other_meaning' => 'string'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'id' => null,
+        'word' => null,
+        'tag' => null,
+        'meaning' => null,
+        'other_meaning' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'id' => false,
+        'word' => false,
+        'tag' => true,
+        'meaning' => false,
+        'other_meaning' => true
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'id' => 'id',
+        'word' => 'word',
+        'tag' => 'tag',
+        'meaning' => 'meaning',
+        'other_meaning' => 'other_meaning'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'id' => 'setId',
+        'word' => 'setWord',
+        'tag' => 'setTag',
+        'meaning' => 'setMeaning',
+        'other_meaning' => 'setOtherMeaning'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'id' => 'getId',
+        'word' => 'getWord',
+        'tag' => 'getTag',
+        'meaning' => 'getMeaning',
+        'other_meaning' => 'getOtherMeaning'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('id', $data ?? [], null);
+        $this->setIfExists('word', $data ?? [], null);
+        $this->setIfExists('tag', $data ?? [], null);
+        $this->setIfExists('meaning', $data ?? [], null);
+        $this->setIfExists('other_meaning', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets id
+     *
+     * @return string|null
+     */
+    public function getId()
+    {
+        return $this->container['id'];
+    }
+
+    /**
+     * Sets id
+     *
+     * @param string|null $id id
+     *
+     * @return self
+     */
+    public function setId($id)
+    {
+        if (is_null($id)) {
+            throw new \InvalidArgumentException('non-nullable id cannot be null');
+        }
+        $this->container['id'] = $id;
+
+        return $this;
+    }
+
+    /**
+     * Gets word
+     *
+     * @return string|null
+     */
+    public function getWord()
+    {
+        return $this->container['word'];
+    }
+
+    /**
+     * Sets word
+     *
+     * @param string|null $word word
+     *
+     * @return self
+     */
+    public function setWord($word)
+    {
+        if (is_null($word)) {
+            throw new \InvalidArgumentException('non-nullable word cannot be null');
+        }
+        $this->container['word'] = $word;
+
+        return $this;
+    }
+
+    /**
+     * Gets tag
+     *
+     * @return string|null
+     */
+    public function getTag()
+    {
+        return $this->container['tag'];
+    }
+
+    /**
+     * Sets tag
+     *
+     * @param string|null $tag tag
+     *
+     * @return self
+     */
+    public function setTag($tag)
+    {
+        if (is_null($tag)) {
+            array_push($this->openAPINullablesSetToNull, 'tag');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('tag', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['tag'] = $tag;
+
+        return $this;
+    }
+
+    /**
+     * Gets meaning
+     *
+     * @return string|null
+     */
+    public function getMeaning()
+    {
+        return $this->container['meaning'];
+    }
+
+    /**
+     * Sets meaning
+     *
+     * @param string|null $meaning meaning
+     *
+     * @return self
+     */
+    public function setMeaning($meaning)
+    {
+        if (is_null($meaning)) {
+            throw new \InvalidArgumentException('non-nullable meaning cannot be null');
+        }
+        $this->container['meaning'] = $meaning;
+
+        return $this;
+    }
+
+    /**
+     * Gets other_meaning
+     *
+     * @return string|null
+     */
+    public function getOtherMeaning()
+    {
+        return $this->container['other_meaning'];
+    }
+
+    /**
+     * Sets other_meaning
+     *
+     * @param string|null $other_meaning other_meaning
+     *
+     * @return self
+     */
+    public function setOtherMeaning($other_meaning)
+    {
+        if (is_null($other_meaning)) {
+            array_push($this->openAPINullablesSetToNull, 'other_meaning');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('other_meaning', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['other_meaning'] = $other_meaning;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 477 - 0
api-test/client/lib/Model/GetApiV3GlossariesKind200ResponseMeta.php

@@ -0,0 +1,477 @@
+<?php
+/**
+ * GetApiV3GlossariesKind200ResponseMeta
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * GetApiV3GlossariesKind200ResponseMeta Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class GetApiV3GlossariesKind200ResponseMeta implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'get_api_v3_glossaries_kind__200_response_meta';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'kind' => 'string',
+        'lang' => 'string',
+        'total' => 'int'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'kind' => null,
+        'lang' => null,
+        'total' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'kind' => false,
+        'lang' => false,
+        'total' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'kind' => 'kind',
+        'lang' => 'lang',
+        'total' => 'total'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'kind' => 'setKind',
+        'lang' => 'setLang',
+        'total' => 'setTotal'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'kind' => 'getKind',
+        'lang' => 'getLang',
+        'total' => 'getTotal'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('kind', $data ?? [], null);
+        $this->setIfExists('lang', $data ?? [], null);
+        $this->setIfExists('total', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets kind
+     *
+     * @return string|null
+     */
+    public function getKind()
+    {
+        return $this->container['kind'];
+    }
+
+    /**
+     * Sets kind
+     *
+     * @param string|null $kind 哪张表
+     *
+     * @return self
+     */
+    public function setKind($kind)
+    {
+        if (is_null($kind)) {
+            throw new \InvalidArgumentException('non-nullable kind cannot be null');
+        }
+        $this->container['kind'] = $kind;
+
+        return $this;
+    }
+
+    /**
+     * Gets lang
+     *
+     * @return string|null
+     */
+    public function getLang()
+    {
+        return $this->container['lang'];
+    }
+
+    /**
+     * Sets lang
+     *
+     * @param string|null $lang 实际用到的语言(没有该语言的表时是 en)
+     *
+     * @return self
+     */
+    public function setLang($lang)
+    {
+        if (is_null($lang)) {
+            throw new \InvalidArgumentException('non-nullable lang cannot be null');
+        }
+        $this->container['lang'] = $lang;
+
+        return $this;
+    }
+
+    /**
+     * Gets total
+     *
+     * @return int|null
+     */
+    public function getTotal()
+    {
+        return $this->container['total'];
+    }
+
+    /**
+     * Sets total
+     *
+     * @param int|null $total 条数
+     *
+     * @return self
+     */
+    public function setTotal($total)
+    {
+        if (is_null($total)) {
+            throw new \InvalidArgumentException('non-nullable total cannot be null');
+        }
+        $this->container['total'] = $total;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 754 - 0
api-test/client/lib/Model/PatchApiV3TermsTermRequest.php

@@ -0,0 +1,754 @@
+<?php
+/**
+ * PatchApiV3TermsTermRequest
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PatchApiV3TermsTermRequest Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PatchApiV3TermsTermRequest implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'patch_api_v3_terms_term__request';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'meaning' => 'string',
+        'other_meaning' => 'string',
+        'note' => 'string',
+        'summary' => 'string',
+        'quality' => 'string',
+        'content_type' => 'string',
+        'redirect' => 'string',
+        'language' => 'string'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'meaning' => null,
+        'other_meaning' => null,
+        'note' => null,
+        'summary' => null,
+        'quality' => null,
+        'content_type' => null,
+        'redirect' => null,
+        'language' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'meaning' => false,
+        'other_meaning' => true,
+        'note' => true,
+        'summary' => true,
+        'quality' => true,
+        'content_type' => false,
+        'redirect' => true,
+        'language' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'meaning' => 'meaning',
+        'other_meaning' => 'other_meaning',
+        'note' => 'note',
+        'summary' => 'summary',
+        'quality' => 'quality',
+        'content_type' => 'content_type',
+        'redirect' => 'redirect',
+        'language' => 'language'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'meaning' => 'setMeaning',
+        'other_meaning' => 'setOtherMeaning',
+        'note' => 'setNote',
+        'summary' => 'setSummary',
+        'quality' => 'setQuality',
+        'content_type' => 'setContentType',
+        'redirect' => 'setRedirect',
+        'language' => 'setLanguage'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'meaning' => 'getMeaning',
+        'other_meaning' => 'getOtherMeaning',
+        'note' => 'getNote',
+        'summary' => 'getSummary',
+        'quality' => 'getQuality',
+        'content_type' => 'getContentType',
+        'redirect' => 'getRedirect',
+        'language' => 'getLanguage'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+    public const QUALITY_FEATURED = 'featured';
+    public const QUALITY_STANDARD = 'standard';
+    public const QUALITY_DRAFT = 'draft';
+    public const QUALITY_PENDING = 'pending';
+    public const CONTENT_TYPE_MARKDOWN = 'markdown';
+    public const CONTENT_TYPE_MARKDOWN_E2 = 'markdown-e2';
+
+    /**
+     * Gets allowable values of the enum
+     *
+     * @return string[]
+     */
+    public function getQualityAllowableValues()
+    {
+        return [
+            self::QUALITY_FEATURED,
+            self::QUALITY_STANDARD,
+            self::QUALITY_DRAFT,
+            self::QUALITY_PENDING,
+        ];
+    }
+
+    /**
+     * Gets allowable values of the enum
+     *
+     * @return string[]
+     */
+    public function getContentTypeAllowableValues()
+    {
+        return [
+            self::CONTENT_TYPE_MARKDOWN,
+            self::CONTENT_TYPE_MARKDOWN_E2,
+        ];
+    }
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('meaning', $data ?? [], null);
+        $this->setIfExists('other_meaning', $data ?? [], null);
+        $this->setIfExists('note', $data ?? [], null);
+        $this->setIfExists('summary', $data ?? [], null);
+        $this->setIfExists('quality', $data ?? [], null);
+        $this->setIfExists('content_type', $data ?? [], null);
+        $this->setIfExists('redirect', $data ?? [], null);
+        $this->setIfExists('language', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        $allowedValues = $this->getQualityAllowableValues();
+        if (!is_null($this->container['quality']) && !in_array($this->container['quality'], $allowedValues, true)) {
+            $invalidProperties[] = sprintf(
+                "invalid value '%s' for 'quality', must be one of '%s'",
+                $this->container['quality'],
+                implode("', '", $allowedValues)
+            );
+        }
+
+        $allowedValues = $this->getContentTypeAllowableValues();
+        if (!is_null($this->container['content_type']) && !in_array($this->container['content_type'], $allowedValues, true)) {
+            $invalidProperties[] = sprintf(
+                "invalid value '%s' for 'content_type', must be one of '%s'",
+                $this->container['content_type'],
+                implode("', '", $allowedValues)
+            );
+        }
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets meaning
+     *
+     * @return string|null
+     */
+    public function getMeaning()
+    {
+        return $this->container['meaning'];
+    }
+
+    /**
+     * Sets meaning
+     *
+     * @param string|null $meaning 释义
+     *
+     * @return self
+     */
+    public function setMeaning($meaning)
+    {
+        if (is_null($meaning)) {
+            throw new \InvalidArgumentException('non-nullable meaning cannot be null');
+        }
+        $this->container['meaning'] = $meaning;
+
+        return $this;
+    }
+
+    /**
+     * Gets other_meaning
+     *
+     * @return string|null
+     */
+    public function getOtherMeaning()
+    {
+        return $this->container['other_meaning'];
+    }
+
+    /**
+     * Sets other_meaning
+     *
+     * @param string|null $other_meaning 其它释义
+     *
+     * @return self
+     */
+    public function setOtherMeaning($other_meaning)
+    {
+        if (is_null($other_meaning)) {
+            array_push($this->openAPINullablesSetToNull, 'other_meaning');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('other_meaning', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['other_meaning'] = $other_meaning;
+
+        return $this;
+    }
+
+    /**
+     * Gets note
+     *
+     * @return string|null
+     */
+    public function getNote()
+    {
+        return $this->container['note'];
+    }
+
+    /**
+     * Sets note
+     *
+     * @param string|null $note 正文
+     *
+     * @return self
+     */
+    public function setNote($note)
+    {
+        if (is_null($note)) {
+            array_push($this->openAPINullablesSetToNull, 'note');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('note', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['note'] = $note;
+
+        return $this;
+    }
+
+    /**
+     * Gets summary
+     *
+     * @return string|null
+     */
+    public function getSummary()
+    {
+        return $this->container['summary'];
+    }
+
+    /**
+     * Sets summary
+     *
+     * @param string|null $summary 摘要,格式与 note 相同
+     *
+     * @return self
+     */
+    public function setSummary($summary)
+    {
+        if (is_null($summary)) {
+            array_push($this->openAPINullablesSetToNull, 'summary');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('summary', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['summary'] = $summary;
+
+        return $this;
+    }
+
+    /**
+     * Gets quality
+     *
+     * @return string|null
+     */
+    public function getQuality()
+    {
+        return $this->container['quality'];
+    }
+
+    /**
+     * Sets quality
+     *
+     * @param string|null $quality 质量
+     *
+     * @return self
+     */
+    public function setQuality($quality)
+    {
+        if (is_null($quality)) {
+            array_push($this->openAPINullablesSetToNull, 'quality');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('quality', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $allowedValues = $this->getQualityAllowableValues();
+        if (!is_null($quality) && !in_array($quality, $allowedValues, true)) {
+            throw new \InvalidArgumentException(
+                sprintf(
+                    "Invalid value '%s' for 'quality', must be one of '%s'",
+                    $quality,
+                    implode("', '", $allowedValues)
+                )
+            );
+        }
+        $this->container['quality'] = $quality;
+
+        return $this;
+    }
+
+    /**
+     * Gets content_type
+     *
+     * @return string|null
+     */
+    public function getContentType()
+    {
+        return $this->container['content_type'];
+    }
+
+    /**
+     * Sets content_type
+     *
+     * @param string|null $content_type 正文方言
+     *
+     * @return self
+     */
+    public function setContentType($content_type)
+    {
+        if (is_null($content_type)) {
+            throw new \InvalidArgumentException('non-nullable content_type cannot be null');
+        }
+        $allowedValues = $this->getContentTypeAllowableValues();
+        if (!in_array($content_type, $allowedValues, true)) {
+            throw new \InvalidArgumentException(
+                sprintf(
+                    "Invalid value '%s' for 'content_type', must be one of '%s'",
+                    $content_type,
+                    implode("', '", $allowedValues)
+                )
+            );
+        }
+        $this->container['content_type'] = $content_type;
+
+        return $this;
+    }
+
+    /**
+     * Gets redirect
+     *
+     * @return string|null
+     */
+    public function getRedirect()
+    {
+        return $this->container['redirect'];
+    }
+
+    /**
+     * Sets redirect
+     *
+     * @param string|null $redirect 重定向到 word 或 word@tag
+     *
+     * @return self
+     */
+    public function setRedirect($redirect)
+    {
+        if (is_null($redirect)) {
+            array_push($this->openAPINullablesSetToNull, 'redirect');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('redirect', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['redirect'] = $redirect;
+
+        return $this;
+    }
+
+    /**
+     * Gets language
+     *
+     * @return string|null
+     */
+    public function getLanguage()
+    {
+        return $this->container['language'];
+    }
+
+    /**
+     * Sets language
+     *
+     * @param string|null $language 语言(只有 studio 级术语能改)
+     *
+     * @return self
+     */
+    public function setLanguage($language)
+    {
+        if (is_null($language)) {
+            throw new \InvalidArgumentException('non-nullable language cannot be null');
+        }
+        $this->container['language'] = $language;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 409 - 0
api-test/client/lib/Model/PostApiV3ChannelsChannelTerms200Response.php

@@ -0,0 +1,409 @@
+<?php
+/**
+ * PostApiV3ChannelsChannelTerms200Response
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PostApiV3ChannelsChannelTerms200Response Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PostApiV3ChannelsChannelTerms200Response implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'post_api_v3_channels_channel_terms_200_response';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'data' => '\WikipaliApi\Model\GetApiV3ChannelsChannelTerms200ResponseDataInner'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'data' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'data' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'data' => 'data'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'data' => 'setData'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'data' => 'getData'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('data', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets data
+     *
+     * @return \WikipaliApi\Model\GetApiV3ChannelsChannelTerms200ResponseDataInner|null
+     */
+    public function getData()
+    {
+        return $this->container['data'];
+    }
+
+    /**
+     * Sets data
+     *
+     * @param \WikipaliApi\Model\GetApiV3ChannelsChannelTerms200ResponseDataInner|null $data data
+     *
+     * @return self
+     */
+    public function setData($data)
+    {
+        if (is_null($data)) {
+            throw new \InvalidArgumentException('non-nullable data cannot be null');
+        }
+        $this->container['data'] = $data;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 409 - 0
api-test/client/lib/Model/PostApiV3ChannelsChannelTermsImports200Response.php

@@ -0,0 +1,409 @@
+<?php
+/**
+ * PostApiV3ChannelsChannelTermsImports200Response
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PostApiV3ChannelsChannelTermsImports200Response Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PostApiV3ChannelsChannelTermsImports200Response implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'post_api_v3_channels_channel_terms_imports_200_response';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'data' => '\WikipaliApi\Model\PostApiV3ChannelsChannelTermsImports200ResponseData'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'data' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'data' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'data' => 'data'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'data' => 'setData'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'data' => 'getData'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('data', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets data
+     *
+     * @return \WikipaliApi\Model\PostApiV3ChannelsChannelTermsImports200ResponseData|null
+     */
+    public function getData()
+    {
+        return $this->container['data'];
+    }
+
+    /**
+     * Sets data
+     *
+     * @param \WikipaliApi\Model\PostApiV3ChannelsChannelTermsImports200ResponseData|null $data data
+     *
+     * @return self
+     */
+    public function setData($data)
+    {
+        if (is_null($data)) {
+            throw new \InvalidArgumentException('non-nullable data cannot be null');
+        }
+        $this->container['data'] = $data;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 545 - 0
api-test/client/lib/Model/PostApiV3ChannelsChannelTermsImports200ResponseData.php

@@ -0,0 +1,545 @@
+<?php
+/**
+ * PostApiV3ChannelsChannelTermsImports200ResponseData
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PostApiV3ChannelsChannelTermsImports200ResponseData Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PostApiV3ChannelsChannelTermsImports200ResponseData implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'post_api_v3_channels_channel_terms_imports_200_response_data';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'created' => 'int',
+        'updated' => 'int',
+        'unchanged' => 'int',
+        'reindexed' => 'bool',
+        'errors' => '\WikipaliApi\Model\PostApiV3ChannelsChannelTermsImports200ResponseDataErrorsInner[]'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'created' => null,
+        'updated' => null,
+        'unchanged' => null,
+        'reindexed' => null,
+        'errors' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'created' => false,
+        'updated' => false,
+        'unchanged' => false,
+        'reindexed' => false,
+        'errors' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'created' => 'created',
+        'updated' => 'updated',
+        'unchanged' => 'unchanged',
+        'reindexed' => 'reindexed',
+        'errors' => 'errors'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'created' => 'setCreated',
+        'updated' => 'setUpdated',
+        'unchanged' => 'setUnchanged',
+        'reindexed' => 'setReindexed',
+        'errors' => 'setErrors'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'created' => 'getCreated',
+        'updated' => 'getUpdated',
+        'unchanged' => 'getUnchanged',
+        'reindexed' => 'getReindexed',
+        'errors' => 'getErrors'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('created', $data ?? [], null);
+        $this->setIfExists('updated', $data ?? [], null);
+        $this->setIfExists('unchanged', $data ?? [], null);
+        $this->setIfExists('reindexed', $data ?? [], null);
+        $this->setIfExists('errors', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets created
+     *
+     * @return int|null
+     */
+    public function getCreated()
+    {
+        return $this->container['created'];
+    }
+
+    /**
+     * Sets created
+     *
+     * @param int|null $created created
+     *
+     * @return self
+     */
+    public function setCreated($created)
+    {
+        if (is_null($created)) {
+            throw new \InvalidArgumentException('non-nullable created cannot be null');
+        }
+        $this->container['created'] = $created;
+
+        return $this;
+    }
+
+    /**
+     * Gets updated
+     *
+     * @return int|null
+     */
+    public function getUpdated()
+    {
+        return $this->container['updated'];
+    }
+
+    /**
+     * Sets updated
+     *
+     * @param int|null $updated updated
+     *
+     * @return self
+     */
+    public function setUpdated($updated)
+    {
+        if (is_null($updated)) {
+            throw new \InvalidArgumentException('non-nullable updated cannot be null');
+        }
+        $this->container['updated'] = $updated;
+
+        return $this;
+    }
+
+    /**
+     * Gets unchanged
+     *
+     * @return int|null
+     */
+    public function getUnchanged()
+    {
+        return $this->container['unchanged'];
+    }
+
+    /**
+     * Sets unchanged
+     *
+     * @param int|null $unchanged unchanged
+     *
+     * @return self
+     */
+    public function setUnchanged($unchanged)
+    {
+        if (is_null($unchanged)) {
+            throw new \InvalidArgumentException('non-nullable unchanged cannot be null');
+        }
+        $this->container['unchanged'] = $unchanged;
+
+        return $this;
+    }
+
+    /**
+     * Gets reindexed
+     *
+     * @return bool|null
+     */
+    public function getReindexed()
+    {
+        return $this->container['reindexed'];
+    }
+
+    /**
+     * Sets reindexed
+     *
+     * @param bool|null $reindexed reindexed
+     *
+     * @return self
+     */
+    public function setReindexed($reindexed)
+    {
+        if (is_null($reindexed)) {
+            throw new \InvalidArgumentException('non-nullable reindexed cannot be null');
+        }
+        $this->container['reindexed'] = $reindexed;
+
+        return $this;
+    }
+
+    /**
+     * Gets errors
+     *
+     * @return \WikipaliApi\Model\PostApiV3ChannelsChannelTermsImports200ResponseDataErrorsInner[]|null
+     */
+    public function getErrors()
+    {
+        return $this->container['errors'];
+    }
+
+    /**
+     * Sets errors
+     *
+     * @param \WikipaliApi\Model\PostApiV3ChannelsChannelTermsImports200ResponseDataErrorsInner[]|null $errors errors
+     *
+     * @return self
+     */
+    public function setErrors($errors)
+    {
+        if (is_null($errors)) {
+            throw new \InvalidArgumentException('non-nullable errors cannot be null');
+        }
+        $this->container['errors'] = $errors;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 443 - 0
api-test/client/lib/Model/PostApiV3ChannelsChannelTermsImports200ResponseDataErrorsInner.php

@@ -0,0 +1,443 @@
+<?php
+/**
+ * PostApiV3ChannelsChannelTermsImports200ResponseDataErrorsInner
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PostApiV3ChannelsChannelTermsImports200ResponseDataErrorsInner Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PostApiV3ChannelsChannelTermsImports200ResponseDataErrorsInner implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'post_api_v3_channels_channel_terms_imports_200_response_data_errors_inner';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'row' => 'int',
+        'message' => 'string'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'row' => null,
+        'message' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'row' => false,
+        'message' => false
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'row' => 'row',
+        'message' => 'message'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'row' => 'setRow',
+        'message' => 'setMessage'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'row' => 'getRow',
+        'message' => 'getMessage'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('row', $data ?? [], null);
+        $this->setIfExists('message', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets row
+     *
+     * @return int|null
+     */
+    public function getRow()
+    {
+        return $this->container['row'];
+    }
+
+    /**
+     * Sets row
+     *
+     * @param int|null $row row
+     *
+     * @return self
+     */
+    public function setRow($row)
+    {
+        if (is_null($row)) {
+            throw new \InvalidArgumentException('non-nullable row cannot be null');
+        }
+        $this->container['row'] = $row;
+
+        return $this;
+    }
+
+    /**
+     * Gets message
+     *
+     * @return string|null
+     */
+    public function getMessage()
+    {
+        return $this->container['message'];
+    }
+
+    /**
+     * Sets message
+     *
+     * @param string|null $message message
+     *
+     * @return self
+     */
+    public function setMessage($message)
+    {
+        if (is_null($message)) {
+            throw new \InvalidArgumentException('non-nullable message cannot be null');
+        }
+        $this->container['message'] = $message;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 801 - 0
api-test/client/lib/Model/PostApiV3ChannelsChannelTermsRequest.php

@@ -0,0 +1,801 @@
+<?php
+/**
+ * PostApiV3ChannelsChannelTermsRequest
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PostApiV3ChannelsChannelTermsRequest Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PostApiV3ChannelsChannelTermsRequest implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'post_api_v3_channels_channel_terms_request';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'word' => 'string',
+        'tag' => 'string',
+        'meaning' => 'string',
+        'other_meaning' => 'string',
+        'note' => 'string',
+        'summary' => 'string',
+        'quality' => 'string',
+        'content_type' => 'string',
+        'redirect' => 'string'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'word' => null,
+        'tag' => null,
+        'meaning' => null,
+        'other_meaning' => null,
+        'note' => null,
+        'summary' => null,
+        'quality' => null,
+        'content_type' => null,
+        'redirect' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'word' => false,
+        'tag' => true,
+        'meaning' => false,
+        'other_meaning' => true,
+        'note' => true,
+        'summary' => true,
+        'quality' => true,
+        'content_type' => false,
+        'redirect' => true
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'word' => 'word',
+        'tag' => 'tag',
+        'meaning' => 'meaning',
+        'other_meaning' => 'other_meaning',
+        'note' => 'note',
+        'summary' => 'summary',
+        'quality' => 'quality',
+        'content_type' => 'content_type',
+        'redirect' => 'redirect'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'word' => 'setWord',
+        'tag' => 'setTag',
+        'meaning' => 'setMeaning',
+        'other_meaning' => 'setOtherMeaning',
+        'note' => 'setNote',
+        'summary' => 'setSummary',
+        'quality' => 'setQuality',
+        'content_type' => 'setContentType',
+        'redirect' => 'setRedirect'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'word' => 'getWord',
+        'tag' => 'getTag',
+        'meaning' => 'getMeaning',
+        'other_meaning' => 'getOtherMeaning',
+        'note' => 'getNote',
+        'summary' => 'getSummary',
+        'quality' => 'getQuality',
+        'content_type' => 'getContentType',
+        'redirect' => 'getRedirect'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+    public const QUALITY_FEATURED = 'featured';
+    public const QUALITY_STANDARD = 'standard';
+    public const QUALITY_DRAFT = 'draft';
+    public const QUALITY_PENDING = 'pending';
+    public const CONTENT_TYPE_MARKDOWN = 'markdown';
+    public const CONTENT_TYPE_MARKDOWN_E2 = 'markdown-e2';
+
+    /**
+     * Gets allowable values of the enum
+     *
+     * @return string[]
+     */
+    public function getQualityAllowableValues()
+    {
+        return [
+            self::QUALITY_FEATURED,
+            self::QUALITY_STANDARD,
+            self::QUALITY_DRAFT,
+            self::QUALITY_PENDING,
+        ];
+    }
+
+    /**
+     * Gets allowable values of the enum
+     *
+     * @return string[]
+     */
+    public function getContentTypeAllowableValues()
+    {
+        return [
+            self::CONTENT_TYPE_MARKDOWN,
+            self::CONTENT_TYPE_MARKDOWN_E2,
+        ];
+    }
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('word', $data ?? [], null);
+        $this->setIfExists('tag', $data ?? [], null);
+        $this->setIfExists('meaning', $data ?? [], null);
+        $this->setIfExists('other_meaning', $data ?? [], null);
+        $this->setIfExists('note', $data ?? [], null);
+        $this->setIfExists('summary', $data ?? [], null);
+        $this->setIfExists('quality', $data ?? [], null);
+        $this->setIfExists('content_type', $data ?? [], 'markdown-e2');
+        $this->setIfExists('redirect', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        if ($this->container['word'] === null) {
+            $invalidProperties[] = "'word' can't be null";
+        }
+        if ($this->container['meaning'] === null) {
+            $invalidProperties[] = "'meaning' can't be null";
+        }
+        $allowedValues = $this->getQualityAllowableValues();
+        if (!is_null($this->container['quality']) && !in_array($this->container['quality'], $allowedValues, true)) {
+            $invalidProperties[] = sprintf(
+                "invalid value '%s' for 'quality', must be one of '%s'",
+                $this->container['quality'],
+                implode("', '", $allowedValues)
+            );
+        }
+
+        $allowedValues = $this->getContentTypeAllowableValues();
+        if (!is_null($this->container['content_type']) && !in_array($this->container['content_type'], $allowedValues, true)) {
+            $invalidProperties[] = sprintf(
+                "invalid value '%s' for 'content_type', must be one of '%s'",
+                $this->container['content_type'],
+                implode("', '", $allowedValues)
+            );
+        }
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets word
+     *
+     * @return string
+     */
+    public function getWord()
+    {
+        return $this->container['word'];
+    }
+
+    /**
+     * Sets word
+     *
+     * @param string $word 巴利词,建立后不能改
+     *
+     * @return self
+     */
+    public function setWord($word)
+    {
+        if (is_null($word)) {
+            throw new \InvalidArgumentException('non-nullable word cannot be null');
+        }
+        $this->container['word'] = $word;
+
+        return $this;
+    }
+
+    /**
+     * Gets tag
+     *
+     * @return string|null
+     */
+    public function getTag()
+    {
+        return $this->container['tag'];
+    }
+
+    /**
+     * Sets tag
+     *
+     * @param string|null $tag 义项(同词多义时区分),不能含 @,建立后不能改
+     *
+     * @return self
+     */
+    public function setTag($tag)
+    {
+        if (is_null($tag)) {
+            array_push($this->openAPINullablesSetToNull, 'tag');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('tag', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['tag'] = $tag;
+
+        return $this;
+    }
+
+    /**
+     * Gets meaning
+     *
+     * @return string
+     */
+    public function getMeaning()
+    {
+        return $this->container['meaning'];
+    }
+
+    /**
+     * Sets meaning
+     *
+     * @param string $meaning 释义
+     *
+     * @return self
+     */
+    public function setMeaning($meaning)
+    {
+        if (is_null($meaning)) {
+            throw new \InvalidArgumentException('non-nullable meaning cannot be null');
+        }
+        $this->container['meaning'] = $meaning;
+
+        return $this;
+    }
+
+    /**
+     * Gets other_meaning
+     *
+     * @return string|null
+     */
+    public function getOtherMeaning()
+    {
+        return $this->container['other_meaning'];
+    }
+
+    /**
+     * Sets other_meaning
+     *
+     * @param string|null $other_meaning 其它释义
+     *
+     * @return self
+     */
+    public function setOtherMeaning($other_meaning)
+    {
+        if (is_null($other_meaning)) {
+            array_push($this->openAPINullablesSetToNull, 'other_meaning');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('other_meaning', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['other_meaning'] = $other_meaning;
+
+        return $this;
+    }
+
+    /**
+     * Gets note
+     *
+     * @return string|null
+     */
+    public function getNote()
+    {
+        return $this->container['note'];
+    }
+
+    /**
+     * Sets note
+     *
+     * @param string|null $note 正文
+     *
+     * @return self
+     */
+    public function setNote($note)
+    {
+        if (is_null($note)) {
+            array_push($this->openAPINullablesSetToNull, 'note');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('note', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['note'] = $note;
+
+        return $this;
+    }
+
+    /**
+     * Gets summary
+     *
+     * @return string|null
+     */
+    public function getSummary()
+    {
+        return $this->container['summary'];
+    }
+
+    /**
+     * Sets summary
+     *
+     * @param string|null $summary 摘要,格式与 note 相同
+     *
+     * @return self
+     */
+    public function setSummary($summary)
+    {
+        if (is_null($summary)) {
+            array_push($this->openAPINullablesSetToNull, 'summary');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('summary', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['summary'] = $summary;
+
+        return $this;
+    }
+
+    /**
+     * Gets quality
+     *
+     * @return string|null
+     */
+    public function getQuality()
+    {
+        return $this->container['quality'];
+    }
+
+    /**
+     * Sets quality
+     *
+     * @param string|null $quality 质量
+     *
+     * @return self
+     */
+    public function setQuality($quality)
+    {
+        if (is_null($quality)) {
+            array_push($this->openAPINullablesSetToNull, 'quality');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('quality', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $allowedValues = $this->getQualityAllowableValues();
+        if (!is_null($quality) && !in_array($quality, $allowedValues, true)) {
+            throw new \InvalidArgumentException(
+                sprintf(
+                    "Invalid value '%s' for 'quality', must be one of '%s'",
+                    $quality,
+                    implode("', '", $allowedValues)
+                )
+            );
+        }
+        $this->container['quality'] = $quality;
+
+        return $this;
+    }
+
+    /**
+     * Gets content_type
+     *
+     * @return string|null
+     */
+    public function getContentType()
+    {
+        return $this->container['content_type'];
+    }
+
+    /**
+     * Sets content_type
+     *
+     * @param string|null $content_type 正文方言
+     *
+     * @return self
+     */
+    public function setContentType($content_type)
+    {
+        if (is_null($content_type)) {
+            throw new \InvalidArgumentException('non-nullable content_type cannot be null');
+        }
+        $allowedValues = $this->getContentTypeAllowableValues();
+        if (!in_array($content_type, $allowedValues, true)) {
+            throw new \InvalidArgumentException(
+                sprintf(
+                    "Invalid value '%s' for 'content_type', must be one of '%s'",
+                    $content_type,
+                    implode("', '", $allowedValues)
+                )
+            );
+        }
+        $this->container['content_type'] = $content_type;
+
+        return $this;
+    }
+
+    /**
+     * Gets redirect
+     *
+     * @return string|null
+     */
+    public function getRedirect()
+    {
+        return $this->container['redirect'];
+    }
+
+    /**
+     * Sets redirect
+     *
+     * @param string|null $redirect 重定向到 word 或 word@tag
+     *
+     * @return self
+     */
+    public function setRedirect($redirect)
+    {
+        if (is_null($redirect)) {
+            array_push($this->openAPINullablesSetToNull, 'redirect');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('redirect', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['redirect'] = $redirect;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 838 - 0
api-test/client/lib/Model/PostApiV3StudiosStudioTermsRequest.php

@@ -0,0 +1,838 @@
+<?php
+/**
+ * PostApiV3StudiosStudioTermsRequest
+ *
+ * PHP version 8.1
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ */
+
+/**
+ * MINT API
+ *
+ * International Academy Of Pali Tipitaka(国际巴利三藏学院)  由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。 响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。
+ *
+ * The version of the OpenAPI document: 1.0.0
+ * Generated by: https://openapi-generator.tech
+ * Generator version: 7.25.0
+ */
+
+/**
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+namespace WikipaliApi\Model;
+
+use \ArrayAccess;
+use \WikipaliApi\ObjectSerializer;
+
+/**
+ * PostApiV3StudiosStudioTermsRequest Class Doc Comment
+ *
+ * @category Class
+ * @package  WikipaliApi
+ * @author   OpenAPI Generator team
+ * @link     https://openapi-generator.tech
+ * @implements \ArrayAccess<string, mixed>
+ */
+class PostApiV3StudiosStudioTermsRequest implements ModelInterface, ArrayAccess, \JsonSerializable
+{
+    public const DISCRIMINATOR = null;
+
+    /**
+     * The original name of the model.
+     *
+     * @var string
+     */
+    protected static $openAPIModelName = 'post_api_v3_studios_studio_terms_request';
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @var string[]
+     */
+    protected static $openAPITypes = [
+        'word' => 'string',
+        'tag' => 'string',
+        'meaning' => 'string',
+        'language' => 'string',
+        'other_meaning' => 'string',
+        'note' => 'string',
+        'summary' => 'string',
+        'quality' => 'string',
+        'content_type' => 'string',
+        'redirect' => 'string'
+    ];
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @var string[]
+     * @phpstan-var array<string, string|null>
+     * @psalm-var array<string, string|null>
+     */
+    protected static $openAPIFormats = [
+        'word' => null,
+        'tag' => null,
+        'meaning' => null,
+        'language' => null,
+        'other_meaning' => null,
+        'note' => null,
+        'summary' => null,
+        'quality' => null,
+        'content_type' => null,
+        'redirect' => null
+    ];
+
+    /**
+     * Array of nullable properties. Used for (de)serialization
+     *
+     * @var boolean[]
+     */
+    protected static array $openAPINullables = [
+        'word' => false,
+        'tag' => true,
+        'meaning' => false,
+        'language' => false,
+        'other_meaning' => true,
+        'note' => true,
+        'summary' => true,
+        'quality' => true,
+        'content_type' => false,
+        'redirect' => true
+    ];
+
+    /**
+     * If a nullable field gets set to null, insert it here
+     *
+     * @var boolean[]
+     */
+    protected array $openAPINullablesSetToNull = [];
+
+    /**
+     * Array of property to type mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPITypes()
+    {
+        return self::$openAPITypes;
+    }
+
+    /**
+     * Array of property to format mappings. Used for (de)serialization
+     *
+     * @return array
+     */
+    public static function openAPIFormats()
+    {
+        return self::$openAPIFormats;
+    }
+
+    /**
+     * Array of nullable properties
+     *
+     * @return array
+     */
+    protected static function openAPINullables(): array
+    {
+        return self::$openAPINullables;
+    }
+
+    /**
+     * Array of nullable field names deliberately set to null
+     *
+     * @return boolean[]
+     */
+    private function getOpenAPINullablesSetToNull(): array
+    {
+        return $this->openAPINullablesSetToNull;
+    }
+
+    /**
+     * Setter - Array of nullable field names deliberately set to null
+     *
+     * @param boolean[] $openAPINullablesSetToNull
+     */
+    private function setOpenAPINullablesSetToNull(array $openAPINullablesSetToNull): void
+    {
+        $this->openAPINullablesSetToNull = $openAPINullablesSetToNull;
+    }
+
+    /**
+     * Checks if a property is nullable
+     *
+     * @param string $property
+     * @return bool
+     */
+    public static function isNullable(string $property): bool
+    {
+        return self::openAPINullables()[$property] ?? false;
+    }
+
+    /**
+     * Checks if a nullable property is set to null.
+     *
+     * @param string $property
+     * @return bool
+     */
+    public function isNullableSetToNull(string $property): bool
+    {
+        return in_array($property, $this->getOpenAPINullablesSetToNull(), true);
+    }
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @var string[]
+     */
+    protected static $attributeMap = [
+        'word' => 'word',
+        'tag' => 'tag',
+        'meaning' => 'meaning',
+        'language' => 'language',
+        'other_meaning' => 'other_meaning',
+        'note' => 'note',
+        'summary' => 'summary',
+        'quality' => 'quality',
+        'content_type' => 'content_type',
+        'redirect' => 'redirect'
+    ];
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @var string[]
+     */
+    protected static $setters = [
+        'word' => 'setWord',
+        'tag' => 'setTag',
+        'meaning' => 'setMeaning',
+        'language' => 'setLanguage',
+        'other_meaning' => 'setOtherMeaning',
+        'note' => 'setNote',
+        'summary' => 'setSummary',
+        'quality' => 'setQuality',
+        'content_type' => 'setContentType',
+        'redirect' => 'setRedirect'
+    ];
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @var string[]
+     */
+    protected static $getters = [
+        'word' => 'getWord',
+        'tag' => 'getTag',
+        'meaning' => 'getMeaning',
+        'language' => 'getLanguage',
+        'other_meaning' => 'getOtherMeaning',
+        'note' => 'getNote',
+        'summary' => 'getSummary',
+        'quality' => 'getQuality',
+        'content_type' => 'getContentType',
+        'redirect' => 'getRedirect'
+    ];
+
+    /**
+     * Array of attributes where the key is the local name,
+     * and the value is the original name
+     *
+     * @return array
+     */
+    public static function attributeMap()
+    {
+        return self::$attributeMap;
+    }
+
+    /**
+     * Array of attributes to setter functions (for deserialization of responses)
+     *
+     * @return array
+     */
+    public static function setters()
+    {
+        return self::$setters;
+    }
+
+    /**
+     * Array of attributes to getter functions (for serialization of requests)
+     *
+     * @return array
+     */
+    public static function getters()
+    {
+        return self::$getters;
+    }
+
+    /**
+     * The original name of the model.
+     *
+     * @return string
+     */
+    public function getModelName()
+    {
+        return self::$openAPIModelName;
+    }
+
+    public const QUALITY_FEATURED = 'featured';
+    public const QUALITY_STANDARD = 'standard';
+    public const QUALITY_DRAFT = 'draft';
+    public const QUALITY_PENDING = 'pending';
+    public const CONTENT_TYPE_MARKDOWN = 'markdown';
+    public const CONTENT_TYPE_MARKDOWN_E2 = 'markdown-e2';
+
+    /**
+     * Gets allowable values of the enum
+     *
+     * @return string[]
+     */
+    public function getQualityAllowableValues()
+    {
+        return [
+            self::QUALITY_FEATURED,
+            self::QUALITY_STANDARD,
+            self::QUALITY_DRAFT,
+            self::QUALITY_PENDING,
+        ];
+    }
+
+    /**
+     * Gets allowable values of the enum
+     *
+     * @return string[]
+     */
+    public function getContentTypeAllowableValues()
+    {
+        return [
+            self::CONTENT_TYPE_MARKDOWN,
+            self::CONTENT_TYPE_MARKDOWN_E2,
+        ];
+    }
+
+    /**
+     * Associative array for storing property values
+     *
+     * @var mixed[]
+     */
+    protected $container = [];
+
+    /**
+     * Constructor
+     *
+     * @param mixed[]|null $data Associated array of property values
+     *                      initializing the model
+     */
+    public function __construct(?array $data = null)
+    {
+        $this->setIfExists('word', $data ?? [], null);
+        $this->setIfExists('tag', $data ?? [], null);
+        $this->setIfExists('meaning', $data ?? [], null);
+        $this->setIfExists('language', $data ?? [], null);
+        $this->setIfExists('other_meaning', $data ?? [], null);
+        $this->setIfExists('note', $data ?? [], null);
+        $this->setIfExists('summary', $data ?? [], null);
+        $this->setIfExists('quality', $data ?? [], null);
+        $this->setIfExists('content_type', $data ?? [], 'markdown-e2');
+        $this->setIfExists('redirect', $data ?? [], null);
+    }
+
+    /**
+     * Sets $this->container[$variableName] to the given data or to the given default Value; if $variableName
+     * is nullable and its value is set to null in the $fields array, then mark it as "set to null" in the
+     * $this->openAPINullablesSetToNull array
+     *
+     * @param string $variableName
+     * @param array  $fields
+     * @param mixed  $defaultValue
+     */
+    private function setIfExists(string $variableName, array $fields, $defaultValue): void
+    {
+        if (self::isNullable($variableName) && array_key_exists($variableName, $fields) && is_null($fields[$variableName])) {
+            $this->openAPINullablesSetToNull[] = $variableName;
+        }
+
+        $this->container[$variableName] = $fields[$variableName] ?? $defaultValue;
+    }
+
+    /**
+     * Show all the invalid properties with reasons.
+     *
+     * @return array invalid properties with reasons
+     */
+    public function listInvalidProperties()
+    {
+        $invalidProperties = [];
+
+        if ($this->container['word'] === null) {
+            $invalidProperties[] = "'word' can't be null";
+        }
+        if ($this->container['meaning'] === null) {
+            $invalidProperties[] = "'meaning' can't be null";
+        }
+        if ($this->container['language'] === null) {
+            $invalidProperties[] = "'language' can't be null";
+        }
+        $allowedValues = $this->getQualityAllowableValues();
+        if (!is_null($this->container['quality']) && !in_array($this->container['quality'], $allowedValues, true)) {
+            $invalidProperties[] = sprintf(
+                "invalid value '%s' for 'quality', must be one of '%s'",
+                $this->container['quality'],
+                implode("', '", $allowedValues)
+            );
+        }
+
+        $allowedValues = $this->getContentTypeAllowableValues();
+        if (!is_null($this->container['content_type']) && !in_array($this->container['content_type'], $allowedValues, true)) {
+            $invalidProperties[] = sprintf(
+                "invalid value '%s' for 'content_type', must be one of '%s'",
+                $this->container['content_type'],
+                implode("', '", $allowedValues)
+            );
+        }
+
+        return $invalidProperties;
+    }
+
+    /**
+     * Validate all the properties in the model
+     * return true if all passed
+     *
+     * @return bool True if all properties are valid
+     */
+    public function valid()
+    {
+        return count($this->listInvalidProperties()) === 0;
+    }
+
+
+    /**
+     * Gets word
+     *
+     * @return string
+     */
+    public function getWord()
+    {
+        return $this->container['word'];
+    }
+
+    /**
+     * Sets word
+     *
+     * @param string $word 巴利词,建立后不能改
+     *
+     * @return self
+     */
+    public function setWord($word)
+    {
+        if (is_null($word)) {
+            throw new \InvalidArgumentException('non-nullable word cannot be null');
+        }
+        $this->container['word'] = $word;
+
+        return $this;
+    }
+
+    /**
+     * Gets tag
+     *
+     * @return string|null
+     */
+    public function getTag()
+    {
+        return $this->container['tag'];
+    }
+
+    /**
+     * Sets tag
+     *
+     * @param string|null $tag 义项(同词多义时区分),不能含 @,建立后不能改
+     *
+     * @return self
+     */
+    public function setTag($tag)
+    {
+        if (is_null($tag)) {
+            array_push($this->openAPINullablesSetToNull, 'tag');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('tag', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['tag'] = $tag;
+
+        return $this;
+    }
+
+    /**
+     * Gets meaning
+     *
+     * @return string
+     */
+    public function getMeaning()
+    {
+        return $this->container['meaning'];
+    }
+
+    /**
+     * Sets meaning
+     *
+     * @param string $meaning 释义
+     *
+     * @return self
+     */
+    public function setMeaning($meaning)
+    {
+        if (is_null($meaning)) {
+            throw new \InvalidArgumentException('non-nullable meaning cannot be null');
+        }
+        $this->container['meaning'] = $meaning;
+
+        return $this;
+    }
+
+    /**
+     * Gets language
+     *
+     * @return string
+     */
+    public function getLanguage()
+    {
+        return $this->container['language'];
+    }
+
+    /**
+     * Sets language
+     *
+     * @param string $language 语言
+     *
+     * @return self
+     */
+    public function setLanguage($language)
+    {
+        if (is_null($language)) {
+            throw new \InvalidArgumentException('non-nullable language cannot be null');
+        }
+        $this->container['language'] = $language;
+
+        return $this;
+    }
+
+    /**
+     * Gets other_meaning
+     *
+     * @return string|null
+     */
+    public function getOtherMeaning()
+    {
+        return $this->container['other_meaning'];
+    }
+
+    /**
+     * Sets other_meaning
+     *
+     * @param string|null $other_meaning 其它释义
+     *
+     * @return self
+     */
+    public function setOtherMeaning($other_meaning)
+    {
+        if (is_null($other_meaning)) {
+            array_push($this->openAPINullablesSetToNull, 'other_meaning');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('other_meaning', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['other_meaning'] = $other_meaning;
+
+        return $this;
+    }
+
+    /**
+     * Gets note
+     *
+     * @return string|null
+     */
+    public function getNote()
+    {
+        return $this->container['note'];
+    }
+
+    /**
+     * Sets note
+     *
+     * @param string|null $note 正文
+     *
+     * @return self
+     */
+    public function setNote($note)
+    {
+        if (is_null($note)) {
+            array_push($this->openAPINullablesSetToNull, 'note');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('note', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['note'] = $note;
+
+        return $this;
+    }
+
+    /**
+     * Gets summary
+     *
+     * @return string|null
+     */
+    public function getSummary()
+    {
+        return $this->container['summary'];
+    }
+
+    /**
+     * Sets summary
+     *
+     * @param string|null $summary 摘要,格式与 note 相同
+     *
+     * @return self
+     */
+    public function setSummary($summary)
+    {
+        if (is_null($summary)) {
+            array_push($this->openAPINullablesSetToNull, 'summary');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('summary', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['summary'] = $summary;
+
+        return $this;
+    }
+
+    /**
+     * Gets quality
+     *
+     * @return string|null
+     */
+    public function getQuality()
+    {
+        return $this->container['quality'];
+    }
+
+    /**
+     * Sets quality
+     *
+     * @param string|null $quality 质量
+     *
+     * @return self
+     */
+    public function setQuality($quality)
+    {
+        if (is_null($quality)) {
+            array_push($this->openAPINullablesSetToNull, 'quality');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('quality', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $allowedValues = $this->getQualityAllowableValues();
+        if (!is_null($quality) && !in_array($quality, $allowedValues, true)) {
+            throw new \InvalidArgumentException(
+                sprintf(
+                    "Invalid value '%s' for 'quality', must be one of '%s'",
+                    $quality,
+                    implode("', '", $allowedValues)
+                )
+            );
+        }
+        $this->container['quality'] = $quality;
+
+        return $this;
+    }
+
+    /**
+     * Gets content_type
+     *
+     * @return string|null
+     */
+    public function getContentType()
+    {
+        return $this->container['content_type'];
+    }
+
+    /**
+     * Sets content_type
+     *
+     * @param string|null $content_type 正文方言
+     *
+     * @return self
+     */
+    public function setContentType($content_type)
+    {
+        if (is_null($content_type)) {
+            throw new \InvalidArgumentException('non-nullable content_type cannot be null');
+        }
+        $allowedValues = $this->getContentTypeAllowableValues();
+        if (!in_array($content_type, $allowedValues, true)) {
+            throw new \InvalidArgumentException(
+                sprintf(
+                    "Invalid value '%s' for 'content_type', must be one of '%s'",
+                    $content_type,
+                    implode("', '", $allowedValues)
+                )
+            );
+        }
+        $this->container['content_type'] = $content_type;
+
+        return $this;
+    }
+
+    /**
+     * Gets redirect
+     *
+     * @return string|null
+     */
+    public function getRedirect()
+    {
+        return $this->container['redirect'];
+    }
+
+    /**
+     * Sets redirect
+     *
+     * @param string|null $redirect 重定向到 word 或 word@tag
+     *
+     * @return self
+     */
+    public function setRedirect($redirect)
+    {
+        if (is_null($redirect)) {
+            array_push($this->openAPINullablesSetToNull, 'redirect');
+        } else {
+            $nullablesSetToNull = $this->getOpenAPINullablesSetToNull();
+            $index = array_search('redirect', $nullablesSetToNull);
+            if ($index !== FALSE) {
+                unset($nullablesSetToNull[$index]);
+                $this->setOpenAPINullablesSetToNull($nullablesSetToNull);
+            }
+        }
+        $this->container['redirect'] = $redirect;
+
+        return $this;
+    }
+    /**
+     * Returns true if offset exists. False otherwise.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return boolean
+     */
+    public function offsetExists(mixed $offset): bool
+    {
+        return isset($this->container[$offset]);
+    }
+
+    /**
+     * Gets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return mixed|null
+     */
+    #[\ReturnTypeWillChange]
+    public function offsetGet(mixed $offset)
+    {
+        return $this->container[$offset] ?? null;
+    }
+
+    /**
+     * Sets value based on offset.
+     *
+     * @param int|null $offset Offset
+     * @param mixed    $value  Value to be set
+     *
+     * @return void
+     */
+    public function offsetSet($offset, $value): void
+    {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    /**
+     * Unsets offset.
+     *
+     * @param integer|string $offset Offset
+     *
+     * @return void
+     */
+    public function offsetUnset(mixed $offset): void
+    {
+        unset($this->container[$offset]);
+    }
+
+    /**
+     * Serializes the object to a value that can be serialized natively by json_encode().
+     * @link https://www.php.net/manual/en/jsonserializable.jsonserialize.php
+     *
+     * @return mixed Returns data which can be serialized by json_encode(), which is a value
+     * of any type other than a resource.
+     */
+    #[\ReturnTypeWillChange]
+    public function jsonSerialize()
+    {
+       return ObjectSerializer::sanitizeForSerialization($this);
+    }
+
+    /**
+     * Gets the string presentation of the object
+     *
+     * @return string
+     */
+    public function __toString()
+    {
+        return json_encode(
+            ObjectSerializer::sanitizeForSerialization($this),
+            JSON_PRETTY_PRINT
+        );
+    }
+
+    /**
+     * Gets a header-safe presentation of the object
+     *
+     * @return string
+     */
+    public function toHeaderValue()
+    {
+        return json_encode(ObjectSerializer::sanitizeForSerialization($this));
+    }
+}
+
+

+ 38 - 177
api-v13/app/Http/Controllers/Library/WikiController.php

@@ -4,24 +4,18 @@ namespace App\Http\Controllers\Library;
 
 
 use App\Helpers\WikiContentParser;
 use App\Helpers\WikiContentParser;
 use App\Http\Controllers\Controller;
 use App\Http\Controllers\Controller;
-use App\Services\OpenSearchService;
 use App\Services\TermService;
 use App\Services\TermService;
+use App\Services\WikiService;
 use Illuminate\Http\Request;
 use Illuminate\Http\Request;
-use Illuminate\Support\Str;
 
 
+/**
+ * library 百科页。词条数据直接查库({@see WikiService}),不经 OpenSearch。
+ */
 class WikiController extends Controller
 class WikiController extends Controller
 {
 {
-    // 质量等级(数值越小等级越高)
-    private $qualityRank = [
-        'featured' => 1,
-        'standard' => 2,
-        'draft' => 3,
-        'pending' => 4,
-    ];
-
     public function __construct(
     public function __construct(
         private TermService $termService,
         private TermService $termService,
-        private OpenSearchService $searchService
+        private WikiService $wiki,
     ) {}
     ) {}
 
 
     // ── Mock 数据 ────────────────────────────────────────────────
     // ── Mock 数据 ────────────────────────────────────────────────
@@ -75,15 +69,24 @@ HTML,
 
 
         if ($category) {
         if ($category) {
             $taxNode = collect(config('taxonomy'))->firstWhere('id', $category);
             $taxNode = collect(config('taxonomy'))->firstWhere('id', $category);
-            $subs = $taxNode ? $this->subEntries($taxNode['subs'], $lang, $quality) : null;
+            // 不是分类树里的一级 id,就当作分类名(词条正文里的 {{category|…}} 链过来的)
+            $subs = $taxNode
+                ? $this->subEntries($taxNode['subs'], $lang, $quality)
+                : [[
+                    'id' => $category,
+                    'label' => $category,
+                    'tags' => [],
+                    'entries' => $this->wiki->categoryEntries([$category], $lang, $quality),
+                ]];
         }
         }
 
 
         $result = $this->termService->communityTerms($lang);
         $result = $this->termService->communityTerms($lang);
         $fakeRequest = Request::create('', 'GET', []);
         $fakeRequest = Request::create('', 'GET', []);
         $terms = $result['data']->toArray($fakeRequest);
         $terms = $result['data']->toArray($fakeRequest);
-        $first = $terms[0];
+        // 该语言的社区 channel 不存在或没有数据时不显示「今日词条」(原来直接取 [0],会 500)
+        $first = $terms[0] ?? null;
 
 
-        $today = [
+        $today = $first ? [
             'word' => $first['word'],
             'word' => $first['word'],
             'lang' => $first['language'],
             'lang' => $first['language'],
             'slug' => $first['word'],
             'slug' => $first['word'],
@@ -91,7 +94,7 @@ HTML,
             'quality' => 'featured',
             'quality' => 'featured',
             'category' => '法义术语',
             'category' => '法义术语',
             'content' => $first['summary'],
             'content' => $first['summary'],
-        ];
+        ] : null;
 
 
         return response()
         return response()
             ->view('library.wiki.index', [
             ->view('library.wiki.index', [
@@ -109,136 +112,46 @@ HTML,
     }
     }
 
 
     /**
     /**
-     * 给每个二级分类注入 词条列表
-     * 真实数据替换时:按 sub['tags'] 查询术语表,返回同结构数组即可
+     * 给每个二级分类注入词条列表:分类名为二级分类本身或它下面的任一标签。
      */
      */
     private function subEntries(array $subs, string $lang, string $quality): array
     private function subEntries(array $subs, string $lang, string $quality): array
     {
     {
         return array_map(function ($sub) use ($lang, $quality) {
         return array_map(function ($sub) use ($lang, $quality) {
-            $entries = $this->querySubCat($sub['tags'], $lang, $quality);
+            $entries = $this->wiki->categoryEntries([$sub['label'], ...$sub['tags']], $lang, $quality);
 
 
             return array_merge($sub, ['entries' => $entries]);
             return array_merge($sub, ['entries' => $entries]);
         }, $subs);
         }, $subs);
     }
     }
 
 
-    private function querySubCat(array $cats, string $lang, string $quality): array
-    {
-        $params = [
-            'pageSize' => 1000,
-            'resourceType' => 'term',
-            'language' => $lang,
-            'tags' => array_map(fn ($n) => "category:{$n}", $cats),
-        ];
-
-        $result = $this->searchService->search($params);
-
-        // 当前允许的最大等级
-        $maxRank = $this->qualityRank[$quality] ?? 4;
-
-        $unique = [];
-
-        foreach ($result['hits']['hits'] as $item) {
-            $text = $item['_source']['title']['text'];
-            $id = $item['_source']['resource_id'];
-
-            if (isset($item['_source']['tags'])) {
-                $itemQuality = $this->getQuality($item['_source']['tags']) ?? 'pending';
-            } else {
-                $itemQuality = 'pending';
-            }
-
-            $itemRank = $this->qualityRank[$itemQuality] ?? 4;
-
-            // 按输入质量过滤
-            if ($itemRank > $maxRank) {
-                continue;
-            }
-
-            $record = [
-                'id' => $id,
-                'word' => $text['pali'],
-                'zh' => $text['zh'],
-                'quality' => $itemQuality,
-            ];
-
-            // 用 pali + zh 去重
-            $key = mb_strtolower(trim($text['pali']).'|'.trim($text['zh']));
-
-            // 如果不存在,直接保存
-            if (! isset($unique[$key])) {
-                $unique[$key] = $record;
-
-                continue;
-            }
-
-            // 已存在时,保留质量更高的
-            $existingQuality = $unique[$key]['quality'];
-            $existingRank = $this->qualityRank[$existingQuality] ?? 4;
-
-            if ($itemRank < $existingRank) {
-                $unique[$key] = $record;
-            }
-        }
-
-        return array_values($unique);
-    }
-
-    private function getQuality(array $tags)
-    {
-        $qualityTag = array_find($tags, function ($tag) {
-            return str_contains($tag, 'quality:');
-        });
-        if ($qualityTag) {
-            return mb_substr($qualityTag, 8, null, 'UTF-8');
-        } else {
-            return null;
-        }
-    }
-
-    private function getCategories(array $tags)
-    {
-        $catTag = array_filter($tags, function ($tag) {
-            return str_contains($tag, 'category:');
-        });
-
-        return array_map(fn ($item) => mb_substr($item, mb_strlen('category:', 'UTF-8')), $catTag);
-    }
-
+    /**
+     * 词条详情。$word 是词或 guid;词条设了重定向(同一词条的另一种拼写)就转到目标词条。
+     */
     public function show(string $lang, string $word)
     public function show(string $lang, string $word)
     {
     {
-        if (Str::isUuid($word)) {
-            $term = $this->termService->find($word, 'html');
-        } else {
-            $term = $this->termService->communityWiki($word, $lang, 'html');
-        }
-
-        try {
-            $result = $this->searchService->get("term_{$term['guid']}");
-        } catch (\Throwable $th) {
+        $term = $this->wiki->find($lang, $word);
+        if (! $term) {
             abort(404);
             abort(404);
         }
         }
-
-        if (isset($result['_source']['tags'])) {
-            $quality = $this->getQuality($result['_source']['tags']);
-        } else {
-            $quality = null;
+        $target = $this->wiki->redirectTarget($term);
+        if ($target) {
+            return redirect()->route('library.wiki.show', [$lang, $target->guid]);
         }
         }
 
 
-        $cats = $this->getCategories($result['_source']['tags']);
+        $cats = $this->wiki->categoriesOf($term);
         $entry = [
         $entry = [
-            'word' => $term['word'],
-            'lang' => $term['language'],
-            'slug' => $term['word'],
-            'meaning' => $term['meaning'],
-            'quality' => $quality,   // featured | standard | draft | pending | null
+            'word' => $term->word,
+            'lang' => $term->language,
+            'slug' => $term->word,
+            'meaning' => $term->meaning,
+            'quality' => $term->quality,   // featured | standard | draft | pending | null
             'category' => '法义术语',
             'category' => '法义术语',
             'tags' => $cats,
             'tags' => $cats,
             'langs' => [
             'langs' => [
                 ['lang' => 'zh-Hant', 'label' => '繁体中文',   'word' => '无常'],
                 ['lang' => 'zh-Hant', 'label' => '繁体中文',   'word' => '无常'],
                 ['lang' => 'en', 'label' => 'English', 'word' => 'Impermanence'],
                 ['lang' => 'en', 'label' => 'English', 'word' => 'Impermanence'],
             ],
             ],
-            'related' => $this->related($cats),
-            'content' => $term['html'] ?? '',
+            'related' => $this->wiki->related($term, $cats),
+            'content' => $this->wiki->contentHtml($term, $lang),
         ];
         ];
         $parsed = WikiContentParser::parse($entry['content']);
         $parsed = WikiContentParser::parse($entry['content']);
 
 
@@ -246,9 +159,9 @@ HTML,
             'entry' => array_merge($entry, [
             'entry' => array_merge($entry, [
                 'content' => $parsed['content'],
                 'content' => $parsed['content'],
                 'toc' => $parsed['toc'],
                 'toc' => $parsed['toc'],
-                'edit_url' => config('mint.server.dashboard_base_path')."/workspace/term/{$term['guid']}/edit",
+                'edit_url' => config('mint.server.dashboard_base_path')."/workspace/term/{$term->guid}/edit",
                 'zh' => '编辑',
                 'zh' => '编辑',
-                'other_versions' => $this->otherVersions($term['word']),
+                'other_versions' => $this->wiki->otherVersions($term),
             ]),
             ]),
             'categories' => $this->categories(),
             'categories' => $this->categories(),
             'lang' => $lang,
             'lang' => $lang,
@@ -256,28 +169,6 @@ HTML,
         ]);
         ]);
     }
     }
 
 
-    private function related(array $tags): array
-    {
-        $params = [
-            'pageSize' => 5,
-            'resourceType' => 'term',
-            'tags' => array_map(fn ($n) => "category:{$n}", $tags),
-        ];
-
-        $result = $this->searchService->search($params);
-        $relates = [];
-
-        foreach ($result['hits']['hits'] as $item) {
-            $relates[] = [
-                'word' => $item['_source']['title']['text']['pali'],
-                'zh' => $item['_source']['title']['text']['zh'],
-                'lang' => $item['_source']['language'],
-            ];
-        }
-
-        return $relates;
-    }
-
     // ── Helpers ──────────────────────────────────────────────────
     // ── Helpers ──────────────────────────────────────────────────
 
 
     private function categories(): array
     private function categories(): array
@@ -369,34 +260,4 @@ HTML,
             ['word' => 'Rājagaha', 'lang' => 'pi'],
             ['word' => 'Rājagaha', 'lang' => 'pi'],
         ];
         ];
     }
     }
-
-    private function otherVersions(string $word): array
-    {
-        $params = [
-            'query' => $word,
-            'pageSize' => 10,
-            'resourceType' => 'term',
-            'tags' => array_map(fn ($n) => "quality:{$n}", array_keys($this->qualityRank)),
-        ];
-
-        $result = $this->searchService->search($params);
-        $versions = [];
-
-        foreach ($result['hits']['hits'] as $item) {
-            $text = $item['_source']['title']['text'];
-            $id = $item['_source']['resource_id'];
-            $versions[] = [
-                'type' => 'term',
-                'id' => $id,
-                'lang' => $item['_source']['language'],
-                'title' => $text['zh'] ?? 'null',
-                'quality' => $this->getQuality($item['_source']['tags'] ?? 'quality:pending'),
-                'category' => '法義術語',
-                'snippet' => $item['_source']['summary']['text'],
-                'updated' => $item['_source']['updated_at'],
-            ];
-        }
-
-        return $versions;
-    }
 }
 }

+ 102 - 0
api-v13/app/Http/Controllers/V3/ChannelTermController.php

@@ -0,0 +1,102 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\IndexTermRequest;
+use App\Http\Requests\V3\StoreTermRequest;
+use App\Http\Resources\V3\TermResource;
+use App\Models\Channel;
+use App\Services\V3\AgentGrantService;
+use App\Services\V3\TermExchangeService;
+use App\Services\V3\TermService;
+
+/**
+ * 某个 channel 的术语:列表与新建。
+ *
+ * 取代 `GET /v2/terms?view=channel` 与带 channel 的 `POST /v2/terms`(`DhammaTermController`),v2 原样保留。
+ */
+class ChannelTermController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(
+        private readonly TermService $terms,
+        private readonly AgentGrantService $grants,
+        private readonly TermExchangeService $exchange,
+    ) {}
+
+    /**
+     * channel 的术语列表
+     *
+     * 能读 channel 的人都能看。请求头 `Accept` 是
+     * `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` 时导出成 xlsx:整表(过滤同列表、不分页),
+     * 列为 id / word / tag / meaning / other_meaning / summary / note / quality / content_type / redirect / language /
+     * channel_id / etag,可改后用导入接口传回(取代 v2 `terms-export`)。
+     *
+     * @unauthenticated
+     *
+     * @urlParam channel string required channel uid
+     *
+     * @queryParam search string 按词、释义搜索
+     * @queryParam quality string 质量;pending 含未评级的。Enum: featured,standard,draft,pending
+     * @queryParam category string 百科分类
+     * @queryParam order string 排序字段。Enum: updated_at,created_at,word Default: updated_at
+     * @queryParam dir string 排序方向。Enum: asc,desc
+     * @queryParam page integer 页码
+     * @queryParam per_page integer 每页条数,最大 200。Default: 20
+     *
+     * @responseStatus 403 私有 channel,且看不见
+     */
+    public function index(IndexTermRequest $request, Channel $channel)
+    {
+        if (in_array(TermExchangeService::MIME, $request->getAcceptableContentTypes(), true)) {
+            return response($this->exchange->export($this->terms->filtered(
+                $this->terms->channelQuery($channel, $this->currentUserUid($request)),
+                $request->validated(),
+            )), 200, ['Content-Type' => TermExchangeService::MIME, 'Content-Disposition' => 'attachment; filename="terms.xlsx"']);
+        }
+
+        return TermResource::collection($this->terms->listInChannel(
+            $channel,
+            $request->validated(),
+            $this->currentUserUid($request),
+            $request->integer('per_page', 20),
+        ));
+    }
+
+    /**
+     * 在 channel 里新建术语
+     *
+     * 能写 channel 内容的人(含团队 editor)。owner 与语言跟 channel。同一 channel 里 word@tag 唯一(409)。
+     * 分类写在 note 的 `{{category|…}}` 里。AI 模型凭 `X-Agent-Grant` 代写。
+     *
+     * @urlParam channel string required channel uid
+     *
+     * @bodyParam word string required 巴利词,建立后不能改
+     * @bodyParam tag string|null 义项(同词多义时区分),不能含 @,建立后不能改
+     * @bodyParam meaning string required 释义
+     * @bodyParam other_meaning string|null 其它释义
+     * @bodyParam note string|null 正文
+     * @bodyParam summary string|null 摘要,格式与 note 相同
+     * @bodyParam quality string|null 质量。Enum: featured,standard,draft,pending
+     * @bodyParam content_type string 正文方言。Enum: markdown,markdown-e2 Default: markdown-e2
+     * @bodyParam redirect string|null 重定向到 word 或 word@tag
+     *
+     * @responseStatus 201 已新建
+     * @responseStatus 403 不能写这个 channel
+     * @responseStatus 409 已有这个 word@tag
+     */
+    public function store(StoreTermRequest $request, Channel $channel)
+    {
+        return TermResource::make($this->terms->createInChannel(
+            $channel,
+            $this->grants->actor(
+                $this->currentUser($request)['user_uid'],
+                $request->header(AgentGrantService::HEADER),
+            ),
+            $request->validated(),
+        ))->response()->setStatusCode(201);
+    }
+}

+ 45 - 0
api-v13/app/Http/Controllers/V3/ChannelTermImportController.php

@@ -0,0 +1,45 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\ImportTermsRequest;
+use App\Http\Resources\V3\TermImportResource;
+use App\Models\Channel;
+use App\Services\V3\TermExchangeService;
+
+/**
+ * 向 channel 导入术语(xlsx)。
+ *
+ * 取代 `GET /v2/terms-import?view=channel`(`TermExportController@import`)。v2 原样保留。
+ */
+class ChannelTermImportController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(private readonly TermExchangeService $exchange) {}
+
+    /**
+     * 向 channel 导入术语
+     *
+     * 上传 xlsx(第一行是列名,至少有 word、meaning;可以直接用导出的表格)。所有行都落在这个 channel,
+     * 语言跟随 channel。有 id 的行改那一条(word / tag 不能改;带 etag 列时与当前不一致就跳过),
+     * 没有 id 的按 word + tag 找,有就改、没有就建。**部分成功**:出错的行跳过,`errors` 逐行给出原因。
+     * 能写这个 channel 的人(含团队 editor)才能导入;AI 模型不能导入。最多 5000 行。
+     *
+     * @urlParam channel string required channel uid
+     *
+     * @bodyParam file file required xlsx 表格,不超过 5MB
+     *
+     * @responseStatus 403 不能写这个 channel
+     */
+    public function __invoke(ImportTermsRequest $request, Channel $channel)
+    {
+        return TermImportResource::make($this->exchange->importToChannel(
+            $channel,
+            $this->currentUser($request)['user_uid'],
+            $request->file('file'),
+        ));
+    }
+}

+ 46 - 0
api-v13/app/Http/Controllers/V3/GlossaryController.php

@@ -0,0 +1,46 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\IndexGlossaryRequest;
+use App\Http\Resources\V3\GlossaryEntryResource;
+use App\Services\V3\GlossaryService;
+
+/**
+ * 术语词汇表:语法术语表 / 社区译名表(只读)。
+ *
+ * 取代 `GET /v2/term-vocabulary?view=grammar|community`(`TermVocabularyController@index`)。
+ * v2 那份在 dashboard-v4 下线前原样保留,不要改动。
+ */
+class GlossaryController extends Controller
+{
+    public function __construct(private readonly GlossaryService $glossaries) {}
+
+    /**
+     * 术语词汇表
+     *
+     * 整表返回、不分页(客户端启动时拉一次,本地查词)。`meta.lang` 是实际用到的语言:
+     * 该语言没有这张表时回退到英文。
+     *
+     * @unauthenticated
+     *
+     * @urlParam kind string required 哪张表:grammar 语法术语,community 社区译名。Enum: grammar,community
+     *
+     * @queryParam lang string 语言,如 zh-Hans。缺省用界面语言(Accept-Language 协商的结果)
+     *
+     * @meta kind string 哪张表
+     * @meta lang string 实际用到的语言(没有该语言的表时是 en)
+     * @meta total integer 条数
+     */
+    public function __invoke(IndexGlossaryRequest $request, string $kind)
+    {
+        $result = $this->glossaries->entries($kind, $request->validated('lang') ?? app()->getLocale());
+
+        return GlossaryEntryResource::collection($result['items'])->additional(['meta' => [
+            'kind' => $kind,
+            'lang' => $result['lang'],
+            'total' => $result['items']->count(),
+        ]]);
+    }
+}

+ 100 - 0
api-v13/app/Http/Controllers/V3/StudioTermController.php

@@ -0,0 +1,100 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\IndexTermRequest;
+use App\Http\Requests\V3\StoreTermRequest;
+use App\Http\Resources\V3\TermResource;
+use App\Services\V3\AgentGrantService;
+use App\Services\V3\TermExchangeService;
+use App\Services\V3\TermService;
+
+/**
+ * 某个 studio(本人或团队)的术语:列表与新建 studio 级术语。
+ *
+ * 取代 `GET /v2/terms?view=studio` 与不带 channel 的 `POST /v2/terms`(`DhammaTermController`),v2 原样保留。
+ */
+class StudioTermController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(
+        private readonly TermService $terms,
+        private readonly AgentGrantService $grants,
+        private readonly TermExchangeService $exchange,
+    ) {}
+
+    /**
+     * studio 的术语列表
+     *
+     * studio 名下的全部术语(它的 channel 里的与 studio 级的)。本人或团队成员能看。请求头 `Accept` 是
+     * `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` 时导出成 xlsx(列与说明同 channel 的术语列表),
+     * 取代 v2 `terms-export?view=studio`。
+     *
+     * @urlParam studio string required 用户或团队的 uuid
+     *
+     * @queryParam search string 按词、释义搜索
+     * @queryParam quality string 质量;pending 含未评级的。Enum: featured,standard,draft,pending
+     * @queryParam category string 百科分类
+     * @queryParam general boolean 只要 studio 级术语(不属于任何 channel)
+     * @queryParam order string 排序字段。Enum: updated_at,created_at,word Default: updated_at
+     * @queryParam dir string 排序方向。Enum: asc,desc
+     * @queryParam page integer 页码
+     * @queryParam per_page integer 每页条数,最大 200。Default: 20
+     *
+     * @responseStatus 403 不是本人,也不是团队成员
+     */
+    public function index(IndexTermRequest $request, string $studio)
+    {
+        if (in_array(TermExchangeService::MIME, $request->getAcceptableContentTypes(), true)) {
+            return response($this->exchange->export($this->terms->filtered(
+                $this->terms->studioQuery($studio, ['general' => $request->boolean('general')] + $request->validated(), $this->currentUser($request)['user_uid']),
+                $request->validated(),
+            )), 200, ['Content-Type' => TermExchangeService::MIME, 'Content-Disposition' => 'attachment; filename="terms.xlsx"']);
+        }
+
+        return TermResource::collection($this->terms->listInStudio(
+            $studio,
+            ['general' => $request->boolean('general')] + $request->validated(),
+            $this->currentUser($request)['user_uid'],
+            $request->integer('per_page', 20),
+        ));
+    }
+
+    /**
+     * 新建 studio 级术语
+     *
+     * 不属于任何 channel,owner 名下所有 channel 共用。本人或团队 owner / manager 能建;AI 模型不能建。
+     * 同一 studio、同一语言里 word@tag 唯一(409)。
+     *
+     * @urlParam studio string required 用户或团队的 uuid
+     *
+     * @bodyParam word string required 巴利词,建立后不能改
+     * @bodyParam tag string|null 义项(同词多义时区分),不能含 @,建立后不能改
+     * @bodyParam meaning string required 释义
+     * @bodyParam language string required 语言
+     * @bodyParam other_meaning string|null 其它释义
+     * @bodyParam note string|null 正文
+     * @bodyParam summary string|null 摘要,格式与 note 相同
+     * @bodyParam quality string|null 质量。Enum: featured,standard,draft,pending
+     * @bodyParam content_type string 正文方言。Enum: markdown,markdown-e2 Default: markdown-e2
+     * @bodyParam redirect string|null 重定向到 word 或 word@tag
+     *
+     * @responseStatus 201 已新建
+     * @responseStatus 403 不能在这个 studio 新建
+     * @responseStatus 409 已有这个 word@tag
+     */
+    public function store(StoreTermRequest $request, string $studio)
+    {
+        return TermResource::make($this->terms->createInStudio(
+            $studio,
+            $this->grants->actor(
+                $this->currentUser($request)['user_uid'],
+                $request->header(AgentGrantService::HEADER),
+            ),
+            $request->validated(),
+        ))->response()->setStatusCode(201);
+    }
+}

+ 43 - 0
api-v13/app/Http/Controllers/V3/StudioTermImportController.php

@@ -0,0 +1,43 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\ImportTermsRequest;
+use App\Http\Resources\V3\TermImportResource;
+use App\Services\V3\TermExchangeService;
+
+/**
+ * 向 studio 导入术语(xlsx)。
+ *
+ * 取代 `GET /v2/terms-import?view=studio`(`TermExportController@import`)。v2 原样保留。
+ */
+class StudioTermImportController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(private readonly TermExchangeService $exchange) {}
+
+    /**
+     * 向 studio 导入术语
+     *
+     * 上传 xlsx。`channel_id` 列有值的行落在那个 channel(必须属于这个 studio、你能写),没有的是 studio 通用术语
+     * (要填 `language`;新建要团队 owner / manager,修改团队 editor 也行)。其余规则同向 channel 导入:
+     * 部分成功、word / tag 不能改、带 etag 列时校验。AI 模型不能导入。最多 5000 行。
+     *
+     * @urlParam studio string required 用户或团队的 uuid
+     *
+     * @bodyParam file file required xlsx 表格,不超过 5MB
+     *
+     * @responseStatus 403 不是本人,也不是团队成员
+     */
+    public function __invoke(ImportTermsRequest $request, string $studio)
+    {
+        return TermImportResource::make($this->exchange->importToStudio(
+            $studio,
+            $this->currentUser($request)['user_uid'],
+            $request->file('file'),
+        ));
+    }
+}

+ 127 - 0
api-v13/app/Http/Controllers/V3/TermController.php

@@ -0,0 +1,127 @@
+<?php
+
+namespace App\Http\Controllers\V3;
+
+use App\Http\Controllers\Concerns\ResolvesCurrentUser;
+use App\Http\Controllers\Controller;
+use App\Http\Requests\V3\LookupTermRequest;
+use App\Http\Requests\V3\ShowTermRequest;
+use App\Http\Requests\V3\UpdateTermRequest;
+use App\Http\Resources\V3\TermResource;
+use App\Models\DhammaTerm;
+use App\Services\V3\AgentGrantService;
+use App\Services\V3\TermService;
+use Illuminate\Http\Request;
+
+/**
+ * 术语 / 百科词条:按词查、单条、改、删。
+ *
+ * 取代 `GET /v2/terms?view=word`、`GET /v2/terms/{id}`、`PUT /v2/terms/{id}`、`DELETE /v2/terms/{id}`
+ * (`DhammaTermController`)。v2 那份在 dashboard-v4 下线前原样保留,不要改动。
+ * 列表与新建在 {@see ChannelTermController}、{@see StudioTermController}。
+ *
+ * AI 模型可凭人类授权(请求头 `X-Agent-Grant`)代写 channel 里的术语:editor 记授权人、co_editor 记模型。
+ */
+class TermController extends Controller
+{
+    use ResolvesCurrentUser;
+
+    public function __construct(
+        private readonly TermService $terms,
+        private readonly AgentGrantService $grants,
+    ) {}
+
+    /**
+     * 按词查术语
+     *
+     * 这些词在你看得见的 channel 与 studio 级术语里的词条(编辑时看同词的其它义项、社区译法)。
+     *
+     * @unauthenticated
+     *
+     * @queryParam word string required 巴利词,逗号分隔,最多 50 个
+     * @queryParam tag string 义项;传空串只要没有义项的
+     * @queryParam channel string 只要这个 channel 的
+     * @queryParam language string 只要这个语言的
+     * @queryParam with_body boolean 每条都带渲染后的正文 `body`
+     * @queryParam page integer 页码
+     * @queryParam per_page integer 每页条数,最大 200。Default: 20
+     */
+    public function index(LookupTermRequest $request)
+    {
+        return TermResource::collection($this->terms->lookup(
+            ['with_body' => $request->boolean('with_body')] + $request->validated(),
+            $this->currentUserUid($request),
+            $request->integer('per_page', 20),
+        ));
+    }
+
+    /**
+     * 术语详情
+     *
+     * 带渲染后的「摘要 + 正文」(`body`)。channel 里的术语跟 channel 的可见性,studio 级的谁都能看。
+     * 响应带 `ETag` 头(与 `etag` 字段相同),修改时放进 `If-Match`。
+     *
+     * @unauthenticated
+     *
+     * @urlParam term string required 术语 id(guid)
+     *
+     * @queryParam channels string 正文按这些 channel 解析(句子、术语),逗号分隔,最多 20 个;只认你看得见的,不给就用术语所在 channel
+     * @queryParam mode string 正文模式。Enum: read,edit Default: read
+     * @queryParam format string 正文格式:tree 给节点树 `body`,html 给 HTML 字符串 `html`(WebView 显示用)。Enum: tree,html Default: tree
+     *
+     * @responseStatus 403 所在 channel 看不见
+     */
+    public function show(ShowTermRequest $request, DhammaTerm $term)
+    {
+        return TermResource::make($this->terms->show($term, $this->currentUserUid($request), $request->render()));
+    }
+
+    /**
+     * 改术语
+     *
+     * 只改传了的字段;word / tag 不能改(要改就新建一条,把旧的 redirect 过去)。必须带请求头
+     * `If-Match`(取自详情的 `etag` / `ETag`):不带 428,这条在你编辑期间被改过 412(响应里给出最新的 `etag`)。
+     * 分类从 note 的 `{{category|…}}` 重新抽取。channel 里的术语跟 channel 的写权限,studio 级的要团队 editor 以上。
+     *
+     * @urlParam term string required 术语 id(guid)
+     *
+     * @bodyParam meaning string 释义
+     * @bodyParam other_meaning string|null 其它释义
+     * @bodyParam note string|null 正文
+     * @bodyParam summary string|null 摘要,格式与 note 相同
+     * @bodyParam quality string|null 质量。Enum: featured,standard,draft,pending
+     * @bodyParam content_type string 正文方言。Enum: markdown,markdown-e2
+     * @bodyParam redirect string|null 重定向到 word 或 word@tag
+     * @bodyParam language string 语言(只有 studio 级术语能改)
+     *
+     * @responseStatus 403 不能修改
+     * @responseStatus 412 这条在你编辑期间被改过
+     * @responseStatus 428 没带 If-Match
+     */
+    public function update(UpdateTermRequest $request, DhammaTerm $term)
+    {
+        return TermResource::make($this->terms->update(
+            $term,
+            $this->grants->actor(
+                $this->currentUser($request)['user_uid'],
+                $request->header(AgentGrantService::HEADER),
+            ),
+            $request->validated(),
+            $request->header('If-Match'),
+        ));
+    }
+
+    /**
+     * 删术语
+     *
+     * 软删除,返回被删的术语。拥有者本人或团队 owner 能删;AI 模型不能删。
+     *
+     * @urlParam term string required 术语 id(guid)
+     *
+     * @responseStatus 403 不能删除
+     */
+    public function destroy(Request $request, DhammaTerm $term)
+    {
+        return TermResource::make($this->terms->delete($term, $this->currentUser($request)['user_uid']));
+    }
+}

+ 26 - 0
api-v13/app/Http/Requests/V3/ImportTermsRequest.php

@@ -0,0 +1,26 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * 术语导入:上传一个 xlsx(multipart/form-data 的 `file`),不超过 5MB。
+ */
+class ImportTermsRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'file' => ['required', 'file', 'extensions:xlsx', 'max:5120'],
+        ];
+    }
+}

+ 26 - 0
api-v13/app/Http/Requests/V3/IndexGlossaryRequest.php

@@ -0,0 +1,26 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * `GET /v3/glossaries/{kind}`:词汇表的语言(可选,缺省用请求协商出的界面语言)。
+ */
+class IndexGlossaryRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'lang' => ['sometimes', 'string', 'max:16', 'regex:/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/'],
+        ];
+    }
+}

+ 37 - 0
api-v13/app/Http/Requests/V3/IndexTermRequest.php

@@ -0,0 +1,37 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use App\Models\DhammaTerm;
+use App\Services\V3\TermService;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Validation\Rule;
+
+/**
+ * 术语列表(某个 channel / studio 的)的过滤与分页。都是可选叠加的过滤。
+ */
+class IndexTermRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'search' => ['sometimes', 'nullable', 'string', 'max:128'],
+            'quality' => ['sometimes', 'string', Rule::in(DhammaTerm::QUALITIES)],
+            'category' => ['sometimes', 'string', 'max:128'],
+            // 查询串里是字符串:Laravel 的 boolean 规则不收 "true"/"false",取值处用 \$request->boolean()
+            'general' => ['sometimes', 'in:true,false,1,0'],
+            'order' => ['sometimes', 'string', Rule::in(TermService::ORDERS)],
+            'dir' => ['sometimes', 'in:asc,desc'],
+            'page' => ['integer', 'min:1'],
+            'per_page' => ['integer', 'min:1', 'max:200'],
+        ];
+    }
+}

+ 37 - 0
api-v13/app/Http/Requests/V3/LookupTermRequest.php

@@ -0,0 +1,37 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * `GET /v3/terms`:按词查。word 必填(逗号分隔,最多 50 个)。
+ */
+class LookupTermRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'word' => ['required', 'string', 'max:2048', function (string $attribute, mixed $value, \Closure $fail) {
+                if (count(array_filter(explode(',', (string) $value), fn ($w) => trim($w) !== '')) > 50) {
+                    $fail(__('validation.max.array', ['attribute' => $attribute, 'max' => 50]));
+                }
+            }],
+            'tag' => ['sometimes', 'nullable', 'string', 'max:1024'],
+            'channel' => ['sometimes', 'uuid'],
+            'language' => ['sometimes', 'string', 'max:16'],
+            // 查询串里是字符串:Laravel 的 boolean 规则不收 "true"/"false",取值处用 \$request->boolean()
+            'with_body' => ['sometimes', 'in:true,false,1,0'],
+            'page' => ['integer', 'min:1'],
+            'per_page' => ['integer', 'min:1', 'max:200'],
+        ];
+    }
+}

+ 41 - 0
api-v13/app/Http/Requests/V3/ShowTermRequest.php

@@ -0,0 +1,41 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use Illuminate\Foundation\Http\FormRequest;
+
+/**
+ * `GET /v3/terms/{term}`:正文按哪些 channel 渲染、read / edit 模式、节点树或 HTML(都可选)。
+ */
+class ShowTermRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'channels' => ['sometimes', 'string', 'max:1024', 'regex:/^[0-9a-fA-F-]{36}(,[0-9a-fA-F-]{36}){0,19}$/'],
+            'mode' => ['sometimes', 'in:read,edit'],
+            'format' => ['sometimes', 'in:tree,html'],
+        ];
+    }
+
+    /**
+     * @return array{channels?: list<string>, mode?: string, format?: string}
+     */
+    public function render(): array
+    {
+        $data = $this->validated();
+        if (isset($data['channels'])) {
+            $data['channels'] = array_values(array_unique(explode(',', $data['channels'])));
+        }
+
+        return $data;
+    }
+}

+ 41 - 0
api-v13/app/Http/Requests/V3/StoreTermRequest.php

@@ -0,0 +1,41 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use App\Models\DhammaTerm;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Validation\Rule;
+
+/**
+ * 新建术语(`POST /v3/channels/{channel}/terms`、`POST /v3/studios/{studio}/terms`)。
+ *
+ * studio 级术语要给 language;channel 里的跟 channel 的语言,传了也不用。分类写在 note 的 {{category|…}} 里。
+ */
+class StoreTermRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        $isStudio = $this->route('studio') !== null;
+
+        return [
+            'word' => ['required', 'string', 'max:1024'],
+            'tag' => ['sometimes', 'nullable', 'string', 'max:1024', 'not_regex:/@/'],
+            'meaning' => ['required', 'string', 'max:1024'],
+            'other_meaning' => ['sometimes', 'nullable', 'string', 'max:1024'],
+            'note' => ['sometimes', 'nullable', 'string'],
+            'summary' => ['sometimes', 'nullable', 'string'],
+            'quality' => ['sometimes', 'nullable', 'string', Rule::in(DhammaTerm::QUALITIES)],
+            'content_type' => ['sometimes', 'string', Rule::in(DhammaTerm::CONTENT_TYPES)],
+            'redirect' => ['sometimes', 'nullable', 'string', 'max:1024'],
+            'language' => [$isStudio ? 'required' : 'prohibited', 'string', 'max:16'],
+        ];
+    }
+}

+ 49 - 0
api-v13/app/Http/Requests/V3/UpdateTermRequest.php

@@ -0,0 +1,49 @@
+<?php
+
+namespace App\Http\Requests\V3;
+
+use App\Models\DhammaTerm;
+use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Validation\Rule;
+
+/**
+ * `PATCH /v3/terms/{term}`:只改传了的字段。word / tag 建立后不准改(引用方写 `[[word@tag]]`),
+ * 要改就新建一条、把旧的 redirect 过去。乐观锁的 If-Match 在 Service 里判。
+ */
+class UpdateTermRequest extends FormRequest
+{
+    public function authorize(): bool
+    {
+        return true;
+    }
+
+    /**
+     * @return array<string, array<int, mixed>>
+     */
+    public function rules(): array
+    {
+        return [
+            'word' => ['prohibited'],
+            'tag' => ['prohibited'],
+            'meaning' => ['sometimes', 'string', 'max:1024'],
+            'other_meaning' => ['sometimes', 'nullable', 'string', 'max:1024'],
+            'note' => ['sometimes', 'nullable', 'string'],
+            'summary' => ['sometimes', 'nullable', 'string'],
+            'quality' => ['sometimes', 'nullable', 'string', Rule::in(DhammaTerm::QUALITIES)],
+            'content_type' => ['sometimes', 'string', Rule::in(DhammaTerm::CONTENT_TYPES)],
+            'redirect' => ['sometimes', 'nullable', 'string', 'max:1024'],
+            'language' => ['sometimes', 'string', 'max:16'],
+        ];
+    }
+
+    /**
+     * @return array<string, string>
+     */
+    public function messages(): array
+    {
+        return [
+            'word.prohibited' => __('messages.term_word_immutable'),
+            'tag.prohibited' => __('messages.term_word_immutable'),
+        ];
+    }
+}

+ 37 - 0
api-v13/app/Http/Resources/V3/GlossaryEntryResource.php

@@ -0,0 +1,37 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Models\DhammaTerm;
+use Illuminate\Http\Request;
+
+/**
+ * 词汇表的一条(`dhamma_terms` 表里系统 channel 的术语)。只给客户端本地查词要用的字段;`id` 是术语 guid。
+ *
+ * @mixin DhammaTerm
+ */
+class GlossaryEntryResource extends BaseResource
+{
+    /**
+     * @return array{
+     *     id: string,
+     *     word: string,
+     *     tag: string|null,
+     *     meaning: string,
+     *     other_meaning: string|null
+     * }
+     */
+    public function toArray(Request $request): array
+    {
+        $tag = trim((string) $this->tag);
+        $other = trim((string) $this->other_meaning);
+
+        return [
+            'id' => (string) $this->guid,
+            'word' => (string) $this->word,
+            'tag' => $tag === '' ? null : $tag,
+            'meaning' => (string) $this->meaning,
+            'other_meaning' => $other === '' ? null : $other,
+        ];
+    }
+}

+ 33 - 0
api-v13/app/Http/Resources/V3/TermImportResource.php

@@ -0,0 +1,33 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Services\V3\TermExchangeService;
+use Illuminate\Http\Request;
+
+/**
+ * 一次术语导入的结果({@see TermExchangeService})。部分成功:出错的行跳过,`errors` 逐行给出原因(`row` 是表格行号)。
+ * `reindexed` 为 false 表示改动较多,搜索索引等每周的全量重建补上。
+ */
+class TermImportResource extends BaseResource
+{
+    /**
+     * @return array{
+     *     created: int,
+     *     updated: int,
+     *     unchanged: int,
+     *     reindexed: bool,
+     *     errors: list<array{row: int, message: string}>
+     * }
+     */
+    public function toArray(Request $request): array
+    {
+        return [
+            'created' => $this->resource['created'],
+            'updated' => $this->resource['updated'],
+            'unchanged' => $this->resource['unchanged'],
+            'reindexed' => $this->resource['reindexed'],
+            'errors' => $this->resource['errors'],
+        ];
+    }
+}

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

@@ -0,0 +1,103 @@
+<?php
+
+namespace App\Http\Resources\V3;
+
+use App\Http\Resources\Concerns\ResolvesActor;
+use App\Models\DhammaTerm;
+use App\Services\Markup\MarkupService;
+use App\Services\V3\TermService;
+use Illuminate\Http\JsonResponse;
+use Illuminate\Http\Request;
+
+/**
+ * 术语 / 百科词条(`dhamma_terms` 表)。
+ *
+ * **本类不查库。** 编辑者、协作者、分类从预加载的关系上取;`abilities`、`summary_text`、`body`
+ * 由 {@see TermService} 挂上。
+ *
+ * - `id` 是 guid(不暴露雪花 id);`channel_id` 为空的是 studio 级术语,`channel` 是它的名字摘要
+ * - `summary` / `note` 是源码,方言见 `content_type`;`body` 是渲染后的「摘要 + 正文」节点树({@see MarkupService}),
+ *   单条里有,按词查带 `with_body` 时每条也有;单条带 `format=html` 时换成 HTML 字符串 `html`(给 WebView 显示的客户端)
+ * - `summary_text` 是纯文本摘要:有 summary 用它,没有取正文第一段
+ * - `categories` 取自正文的 `{{category|…}}`
+ * - `etag` 是乐观锁的版本标记:修改时原样放进 `If-Match` 请求头(单条响应也带 `ETag` 头)
+ *
+ * @mixin DhammaTerm
+ */
+class TermResource extends BaseResource
+{
+    use ResolvesActor;
+
+    /**
+     * @return array{
+     *     id: string,
+     *     word: string,
+     *     tag: string|null,
+     *     meaning: string,
+     *     other_meaning: string|null,
+     *     language: string,
+     *     channel_id: string|null,
+     *     channel: array{id: string, name: string}|null,
+     *     owner_id: string,
+     *     quality: string|null,
+     *     content_type: string,
+     *     summary: string|null,
+     *     note: string|null,
+     *     redirect: string|null,
+     *     categories: list<string>,
+     *     summary_text: string,
+     *     body?: list<MarkupNode>,
+     *     html?: string,
+     *     editor: array{id: string, nickName: string, userName: string, realName: string, sn: int, avatar: string|null, roles: array|null}|null,
+     *     co_editor: array{id: string, nickName: string, userName: string, realName: string, sn: int, avatar: string|null, roles: array|null}|null,
+     *     etag: string,
+     *     abilities: array{update: bool, delete: bool},
+     *     created_at: string,
+     *     updated_at: string,
+     *     deleted_at: string|null
+     * }
+     */
+    public function toArray(Request $request): array
+    {
+        $tag = trim((string) $this->tag);
+
+        return [
+            'id' => (string) $this->guid,
+            'word' => (string) $this->word,
+            'tag' => $tag === '' ? null : $tag,
+            'meaning' => (string) $this->meaning,
+            'other_meaning' => $this->other_meaning,
+            'language' => (string) $this->language,
+            'channel_id' => $this->channal,
+            'channel' => $this->channel ? ['id' => (string) $this->channel->uid, 'name' => (string) $this->channel->name] : null,
+            'owner_id' => (string) $this->owner,
+            'quality' => $this->quality,
+            'content_type' => $this->effectiveContentType(),
+            'summary' => $this->summary,
+            'note' => $this->note,
+            'redirect' => $this->redirect !== '' ? $this->redirect : null,
+            'categories' => $this->categories->pluck('category')->values()->all(),
+            'summary_text' => (string) ($this->summary_text ?? ''),
+            'body' => $this->when(isset($this->body), fn () => $this->body),
+            'html' => $this->when(isset($this->html), fn () => $this->html),
+            'editor' => $this->actor($this->user, $this->aiModel),
+            'co_editor' => $this->coEditor ? $this->actor(null, $this->coEditor) : null,
+            'etag' => $this->etag(),
+            'abilities' => [
+                'update' => (bool) ($this->abilities['update'] ?? false),
+                'delete' => (bool) ($this->abilities['delete'] ?? false),
+            ],
+            'created_at' => $this->created_at?->toIso8601ZuluString(),
+            'updated_at' => $this->updated_at?->toIso8601ZuluString(),
+            'deleted_at' => $this->deleted_at?->toIso8601ZuluString(),
+        ];
+    }
+
+    /**
+     * 单条响应带 ETag 头(列表不带)。
+     */
+    public function withResponse(Request $request, JsonResponse $response): void
+    {
+        $response->header('ETag', $this->etag());
+    }
+}

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

@@ -4,18 +4,87 @@ namespace App\Models;
 
 
 use Illuminate\Database\Eloquent\Factories\HasFactory;
 use Illuminate\Database\Eloquent\Factories\HasFactory;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
+use Illuminate\Database\Eloquent\Relations\HasMany;
+use Illuminate\Database\Eloquent\SoftDeletes;
 
 
+/**
+ * 术语 / 百科词条(`dhamma_terms` 表)。主键是 guid(uuid),另有雪花 `id` 列。
+ *
+ * 注意列名拼写:channel 存在 `channal` 列。channal 为空的是 studio 级通用术语(owner 名下所有 channel 共用)。
+ * `word` + `tag`(义项)在一个 channel 内唯一,引用方写成 `[[word@tag]]`;v3 建立后不准改,
+ * 要改就新建一条、把旧的 `redirect` 到新的(类似维基百科的重定向)。
+ *
+ * v3 新增的列(v2 不读):co_editor_uid、quality、summary、content_type、version,
+ * 分类在 {@see TermCategory}(term_categories 表)。v3 读写见 `App\Services\V3\TermService`。
+ */
 class DhammaTerm extends Model
 class DhammaTerm extends Model
 {
 {
     use HasFactory;
     use HasFactory;
+    use SoftDeletes;
+
+    /** 词条质量 */
+    public const QUALITIES = ['featured', 'standard', 'draft', 'pending'];
+
+    /** 正文方言:旧方言(v2 写入的都是它)与 v3 的 markdown-e2 */
+    public const CONTENT_TYPES = ['markdown', 'markdown-e2'];
+
+    public const CONTENT_TYPE_V3 = 'markdown-e2';
 
 
     protected $primaryKey = 'guid';
     protected $primaryKey = 'guid';
 
 
+    protected $keyType = 'string';
+
     protected $casts = [
     protected $casts = [
         'guid' => 'string',
         'guid' => 'string',
+        'version' => 'integer',
+        'modify_time' => 'integer',
+        'create_time' => 'integer',
     ];
     ];
 
 
     public $incrementing = false;
     public $incrementing = false;
 
 
     protected $fillable = ['id', 'guid', 'word', 'word_en', 'meaning', 'channal', 'language', 'owner', 'editor_id', 'editor_uid', 'create_time', 'modify_time'];
     protected $fillable = ['id', 'guid', 'word', 'word_en', 'meaning', 'channal', 'language', 'owner', 'editor_id', 'editor_uid', 'create_time', 'modify_time'];
+
+    /** 所属 channel(channal 列);studio 级术语为空 */
+    public function channel(): BelongsTo
+    {
+        return $this->belongsTo(Channel::class, 'channal', 'uid');
+    }
+
+    /** 编辑者(人类用户)。editor_uid 对 user_infos.userid */
+    public function user(): BelongsTo
+    {
+        return $this->belongsTo(UserInfo::class, 'editor_uid', 'userid');
+    }
+
+    /** 编辑者(AI 助手)。存量数据里 AI 写的行 editor_uid 直接是模型 */
+    public function aiModel(): BelongsTo
+    {
+        return $this->belongsTo(AiModel::class, 'editor_uid', 'uid');
+    }
+
+    /** 协作者:人类授权代写的 AI 模型。此时 editor 是授权人 */
+    public function coEditor(): BelongsTo
+    {
+        return $this->belongsTo(AiModel::class, 'co_editor_uid', 'uid');
+    }
+
+    /** 百科分类,按正文里出现的顺序 */
+    public function categories(): HasMany
+    {
+        return $this->hasMany(TermCategory::class, 'term_guid', 'guid')->orderBy('position');
+    }
+
+    /** 实际方言:v2 写入的行库里是默认值 markdown */
+    public function effectiveContentType(): string
+    {
+        return $this->content_type ?: 'markdown';
+    }
+
+    /** 乐观锁用的 ETag:v3 修改 +version,v2 修改只动 modify_time,两者都要算进去 */
+    public function etag(): string
+    {
+        return '"'.((int) $this->version).'.'.((int) $this->modify_time).'"';
+    }
 }
 }

+ 25 - 0
api-v13/app/Models/TermCategory.php

@@ -0,0 +1,25 @@
+<?php
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
+
+/**
+ * 术语的一个百科分类(`term_categories` 表)。由正文里的 `{{category|…}}` 抽出,
+ * v3 写入术语时整体重建,不单独增删。
+ */
+class TermCategory extends Model
+{
+    protected $fillable = ['term_guid', 'category', 'position'];
+
+    protected function casts(): array
+    {
+        return ['position' => 'integer'];
+    }
+
+    public function term(): BelongsTo
+    {
+        return $this->belongsTo(DhammaTerm::class, 'term_guid', 'guid');
+    }
+}

+ 11 - 0
api-v13/app/Services/Markup/Templates/CategoryTemplate.php

@@ -31,4 +31,15 @@ final class CategoryTemplate extends Template
     {
     {
         return (string) $call->param('name');
         return (string) $call->param('name');
     }
     }
+
+    /**
+     * HTML 里带上类名与分类名,由页面决定样式与去向(百科页换成指向分类列表的标签链接,
+     * 见 App\Services\WikiService::contentHtml() 与 resources/css/modules/wiki.css)。
+     */
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        $name = e($this->text($call, $ctx));
+
+        return '<span class="tpl-category" data-category="'.$name.'">'.$name.'</span>';
+    }
 }
 }

+ 21 - 0
api-v13/app/Services/Markup/Templates/ReferenceTemplate.php

@@ -116,6 +116,27 @@ final class ReferenceTemplate extends Template
         return $text;
         return $text;
     }
     }
 
 
+    /**
+     * 一条一行(与 v6 的 ReferenceCtl 一致)。模板落在 `<p>` 里,不能再套块级元素,用 `<br />` 分行;
+     * 没有这个方法时走基类的「转义后的纯文本」,条目间的换行会被浏览器合并成空格。
+     */
+    public function html(Call $call, RenderContext $ctx): string
+    {
+        $references = $this->bibliography($ctx);
+        if ($references === []) {
+            return '';
+        }
+        $title = $this->title($call, $ctx);
+        $items = $title === '' ? [] : ['<span class="tpl-reference-title">'.e($title).'</span>'];
+        foreach ($references as $reference) {
+            $items[] = '<span class="tpl-reference-item">'
+                .e('['.$reference['sn'].'] '.ucfirst($reference['title']).' '.$reference['copyright'])
+                .'</span>';
+        }
+
+        return implode('<br />', $items);
+    }
+
     public function markdown(Call $call, RenderContext $ctx): string
     public function markdown(Call $call, RenderContext $ctx): string
     {
     {
         $references = $this->bibliography($ctx);
         $references = $this->bibliography($ctx);

+ 74 - 25
api-v13/app/Services/TermIndexService.php

@@ -2,11 +2,28 @@
 
 
 namespace App\Services;
 namespace App\Services;
 
 
+use App\Models\Channel;
+use App\Models\DhammaTerm;
+use App\Models\GroupInfo;
+use App\Models\TermCategory;
+use App\Models\UserInfo;
+use App\Services\Markup\Format;
+use App\Services\Markup\MarkupService;
+use App\Services\Markup\RenderOptions;
+use Illuminate\Database\Eloquent\ModelNotFoundException;
+
+/**
+ * 术语写进 OpenSearch(全站搜索用)。v2 与 v3 的写入、`IndexTerm` 命令共用。
+ *
+ * 渲染用新渲染器({@see MarkupService}):内容 = 摘要 + 正文,按 content_type 的方言解析,
+ * 模板按术语所在 channel 取数。分类与质量优先取 v3 的列(term_categories、quality),
+ * 没有时(v2 写入的条目)从正文的 `{{category|…}}` / `{{quality|…}}` 抽。
+ */
 class TermIndexService
 class TermIndexService
 {
 {
     public function __construct(
     public function __construct(
         protected OpenSearchService $openSearchService,
         protected OpenSearchService $openSearchService,
-        protected TermService $termService,
+        protected MarkupService $markup,
     ) {}
     ) {}
 
 
     /**
     /**
@@ -31,15 +48,33 @@ class TermIndexService
      *
      *
      * @param  string  $guid  DhammaTerm 的 guid
      * @param  string  $guid  DhammaTerm 的 guid
      * @return array<string, mixed>
      * @return array<string, mixed>
+     *
+     * @throws ModelNotFoundException 术语不存在(含已删除)
      */
      */
     public function buildDocument(string $guid): array
     public function buildDocument(string $guid): array
     {
     {
-        $termData = $this->termService->find($guid, 'text');
-        $channelName = $termData['channel']['name'] ?? '';
-        $content = $termData['html'] ?? $termData['meaning'];
+        $term = DhammaTerm::where('guid', $guid)->firstOrFail();
+        $channelName = $term->channal ? (string) Channel::where('uid', $term->channal)->value('name') : '';
+        $studioName = (string) (UserInfo::where('userid', $term->owner)->value('username')
+            ?? GroupInfo::where('uid', $term->owner)->value('name')
+            ?? '');
+
+        $summary = trim((string) $term->summary);
+        $options = [
+            'channels' => $term->channal ? [$term->channal] : [],
+            'contentType' => $term->effectiveContentType(),
+        ];
+        $rendered = $this->markup->renderManyAs([
+            'body' => $options + ['source' => trim($summary."\n\n".(string) $term->note)],
+            'summary' => $options + ['source' => $summary !== '' ? $summary : (string) $term->note],
+        ], new RenderOptions(lang: $term->language ?: 'zh-Hans'), [Format::Html, Format::Text]);
+        $display = (string) $rendered[Format::Html->value]['body'];
+        $plainText = (string) $rendered[Format::Text->value]['body'];
+        $summaryText = $this->firstLine((string) $rendered[Format::Text->value]['summary'], $summary !== '');
 
 
-        $categories = $this->extractCategories($termData['note'] ?? '');
-        $quality = $this->extractFirstQuality($termData['note'] ?? '');
+        $categories = TermCategory::where('term_guid', $term->guid)->orderBy('position')->pluck('category')->all()
+            ?: $this->extractCategories((string) $term->note);
+        $quality = $term->quality ?: $this->extractFirstQuality((string) $term->note);
         $tags = [];
         $tags = [];
         foreach ($categories as $category) {
         foreach ($categories as $category) {
             $tags[] = "category:{$category}";
             $tags[] = "category:{$category}";
@@ -48,40 +83,54 @@ class TermIndexService
             $tags[] = "quality:{$quality}";
             $tags[] = "quality:{$quality}";
         }
         }
 
 
-        $document = [
-            'id' => "term_{$guid}",
-            'resource_id' => $guid,
+        return [
+            'id' => "term_{$term->guid}",
+            'resource_id' => $term->guid,
             'resource_type' => 'term',
             'resource_type' => 'term',
             'title' => [
             'title' => [
                 'text' => [
                 'text' => [
-                    'pali' => $termData['word'],
-                    'zh' => $termData['meaning'],
+                    'pali' => $term->word,
+                    'zh' => $term->meaning,
                 ],
                 ],
                 'suggest' => [
                 'suggest' => [
-                    'pali' => [$termData['word']],
-                    'zh' => [$termData['meaning']],
+                    'pali' => [$term->word],
+                    'zh' => [$term->meaning],
                 ],
                 ],
             ],
             ],
             'summary' => [
             'summary' => [
-                'text' => $termData['summary'] ?? '',
+                'text' => $summaryText,
+            ],
+            // TODO: 补充语言判断,将内容放入对应的 text.pali 或 text.zh 字段
+            'content' => [
+                'text' => ['zh' => $plainText !== '' ? $plainText : (string) $term->meaning],
+                'display' => $display !== '' ? $display : (string) $term->meaning,
             ],
             ],
-            'content' => [],
-            'bold_single' => [$termData['meaning'], $termData['word']],
-            'related_id' => $termData['word'],
+            'bold_single' => [$term->meaning, $term->word],
+            'related_id' => $term->word,
             'category' => null,
             'category' => null,
             'tags' => $tags,
             'tags' => $tags,
-            'language' => $termData['language'],
+            'language' => $term->language,
             'updated_at' => now()->toIso8601String(),
             'updated_at' => now()->toIso8601String(),
-            'path' => $termData['studio']['realName']."/{$channelName}",
-            'metadata' => ['channel' => $termData['channel_id']],
+            'path' => "{$studioName}/{$channelName}",
+            'metadata' => ['channel' => $term->channal],
         ];
         ];
+    }
 
 
-        // TODO: 补充语言判断,将内容放入对应的 text.pali 或 text.zh 字段
-        $plainText = strip_tags($content);
-        $document['content']['text']['zh'] = $plainText;
-        $document['content']['display'] = $content;             // 展示
+    /**
+     * 摘要纯文本:给了 summary 就整段用;没给取正文第一段(纯文本里段落之间只隔一个换行)。
+     */
+    private function firstLine(string $text, bool $whole): string
+    {
+        if ($whole) {
+            return trim($text);
+        }
+        foreach (preg_split('/\n/u', $text) ?: [] as $line) {
+            if (trim($line) !== '') {
+                return trim($line);
+            }
+        }
 
 
-        return $document;
+        return '';
     }
     }
 
 
     /**
     /**

+ 57 - 0
api-v13/app/Services/V3/GlossaryService.php

@@ -0,0 +1,57 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Models\DhammaTerm;
+use App\Services\ChannelService as ChannelLookup;
+use Illuminate\Support\Collection;
+
+/**
+ * 术语词汇表(只读):语法术语表与社区译名表,客户端启动时整表拉取后本地查。
+ *
+ * 取代 v2 `term-vocabulary`(`TermVocabularyController`)。数据就是两个系统 channel 里的术语:
+ * - grammar:`_System_Grammar_Term_{lang}_`
+ * - community:`_community_term_{lang}_`
+ * 该语言的 channel 不存在时回退到英文(与 v2 相同)。注意它与批注的 `glossary` 类型(外挂术语)不是一回事。
+ */
+class GlossaryService
+{
+    public const KINDS = ['grammar', 'community'];
+
+    private const CHANNEL_PREFIX = [
+        'grammar' => '_System_Grammar_Term_',
+        'community' => '_community_term_',
+    ];
+
+    private const FALLBACK_LANG = 'en';
+
+    public function __construct(private readonly ChannelLookup $channels) {}
+
+    /**
+     * 某种词汇表的全部条目(按词排序),以及实际用到的语言。
+     *
+     * @return array{items: Collection<int, DhammaTerm>, lang: string}
+     */
+    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.'_');
+        }
+
+        $items = $channel === false
+            ? collect()
+            : DhammaTerm::query()
+                ->where('channal', $channel)
+                ->whereNotNull('word')
+                ->where('word', '<>', '')
+                ->orderBy('word')
+                ->orderBy('guid')
+                ->get(['guid', 'word', 'tag', 'meaning', 'other_meaning']);
+
+        return ['items' => $items, 'lang' => $served];
+    }
+}

+ 355 - 0
api-v13/app/Services/V3/TermExchangeService.php

@@ -0,0 +1,355 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Exceptions\BusinessException;
+use App\Models\Channel;
+use App\Models\DhammaTerm;
+use Illuminate\Auth\Access\AuthorizationException;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Http\UploadedFile;
+use Illuminate\Validation\ValidationException;
+use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
+use PhpOffice\PhpSpreadsheet\IOFactory;
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
+
+/**
+ * 术语的批量导入 / 导出(xlsx)。
+ *
+ * 取代 v2 `terms-export`(生成后存 Redis 5 分钟、再凭 uuid 下载)与 `terms-import`(GET 写入、读附件临时文件)。
+ *
+ * 导出:列表接口带 `Accept: xlsx` 时整表返回(过滤同列表、不分页),权限同列表。
+ * 导入:上传 xlsx。按**表头的列名**取值,所以 v2 导出的旧表格(id / word / meaning / other_meaning / note / tag /
+ * language / channel_id)也能直接导入。规则(2026-11-17 用户定):
+ * - **部分成功**:出错的行跳过、其余照写,响应逐行列出跳过的原因
+ * - 有 id:改那一条。word / tag 与库里不同就报错(建立后不能改);带 etag 列且与当前不一致就报「导出之后被改过」
+ * - 无 id:同范围里已有同 word + tag 的就改它,没有就新建
+ * - word 为空报错(v2「有 id、word 为空就删除」不保留,删除走单条删除)
+ * - 每行的权限与单条新建 / 修改相同;只给人类(不支持 agent 代写)
+ * - 改动不超过 {@see self::REINDEX_LIMIT} 条时立即重建搜索索引,更多的等每周 `opensearch:index-term`
+ */
+class TermExchangeService
+{
+    public const MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
+
+    public const MAX_ROWS = 5000;
+
+    /** 改动不超过这么多条才立即重建搜索索引(逐条渲染全文,量大会很慢;线上没有队列 worker) */
+    public const REINDEX_LIMIT = 50;
+
+    /** 导出的列(导入按列名认,顺序无所谓) */
+    public const COLUMNS = [
+        'id', 'word', 'tag', 'meaning', 'other_meaning', 'summary', 'note',
+        'quality', 'content_type', 'redirect', 'language', 'channel_id', 'etag',
+    ];
+
+    /** 导入时可以改的内容列 */
+    private const CONTENT = ['meaning', 'other_meaning', 'summary', 'note', 'quality', 'content_type', 'redirect'];
+
+    public function __construct(
+        private readonly TermService $terms,
+        private readonly ChannelAbilityService $channels,
+        private readonly GroupAbilityService $groups,
+        private readonly AgentGrantService $agents,
+    ) {}
+
+    /* ------------------------------------------------------------------ 导出 */
+
+    /**
+     * 把查询结果写成 xlsx(二进制内容)。
+     *
+     * @param  Builder<DhammaTerm>  $query
+     */
+    public function export(Builder $query): string
+    {
+        $spreadsheet = new Spreadsheet;
+        $sheet = $spreadsheet->getActiveSheet();
+        $sheet->fromArray([self::COLUMNS], null, 'A1');
+
+        $line = 2;
+        foreach ($query->cursor() as $term) {
+            $sheet->fromArray([[
+                $term->guid, $term->word, $this->terms->normalizeTag($term->tag), $term->meaning,
+                $term->other_meaning, $term->summary, $term->note, $term->quality,
+                $term->effectiveContentType(), $term->redirect, $term->language, $term->channal, $term->etag(),
+            ]], null, "A{$line}", true);
+            $line++;
+        }
+
+        $stream = fopen('php://memory', 'r+');
+        (new Xlsx($spreadsheet))->save($stream);
+        rewind($stream);
+        $content = (string) stream_get_contents($stream);
+        fclose($stream);
+
+        return $content;
+    }
+
+    /* ------------------------------------------------------------------ 导入 */
+
+    /**
+     * 导入到 channel:所有行都落在这个 channel,owner 与语言跟 channel(表里的 channel_id / language 列不看)。
+     *
+     * @return array{created: int, updated: int, unchanged: int, reindexed: bool, errors: list<array{row: int, message: string}>}
+     *
+     * @throws AuthorizationException 不能写这个 channel,或是 AI 模型
+     * @throws ValidationException 文件读不了、缺 word / meaning 列、行数超限
+     */
+    public function importToChannel(Channel $channel, string $actorUid, UploadedFile $file): array
+    {
+        $this->agents->assertHuman($actorUid);
+        if (! $this->channels->abilities($channel, $actorUid)['write']) {
+            throw new AuthorizationException(__('messages.term_forbidden'));
+        }
+
+        return $this->import($actorUid, $file, fn (array $row) => [
+            'scope' => DhammaTerm::query()->where('channal', $channel->uid),
+            'target' => ['channel' => $channel->uid, 'owner' => $channel->owner_uid, 'language' => $channel->lang],
+            'language_editable' => false,
+        ]);
+    }
+
+    /**
+     * 导入到 studio:channel_id 列有值的落在那个 channel(必须是这个 studio 的、你能写的),
+     * 没有的是 studio 级术语(要 language 列)。
+     *
+     * @return array{created: int, updated: int, unchanged: int, reindexed: bool, errors: list<array{row: int, message: string}>}
+     *
+     * @throws AuthorizationException 不是本人,也不是这个团队的成员;或是 AI 模型
+     * @throws ValidationException
+     */
+    public function importToStudio(string $studioUid, string $actorUid, UploadedFile $file): array
+    {
+        $this->agents->assertHuman($actorUid);
+        if (! $this->groups->can($actorUid, $studioUid, GroupAbilityService::READ)) {
+            throw new AuthorizationException(__('messages.channel_studio_forbidden'));
+        }
+        $channels = [];
+
+        return $this->import($actorUid, $file, function (array $row) use ($studioUid, $actorUid, &$channels) {
+            $channelUid = $row['channel_id'] ?? null;
+            if ($channelUid === null) {
+                $language = $row['language'] ?? null;
+                if ($language === null) {
+                    throw new TermImportRowError(__('messages.term_import_language_required'));
+                }
+
+                return [
+                    'scope' => DhammaTerm::query()->where('owner', $studioUid)->whereNull('channal')->where('language', $language),
+                    'target' => ['channel' => null, 'owner' => $studioUid, 'language' => $language],
+                    'language_editable' => true,
+                ];
+            }
+            $channel = $channels[$channelUid] ??= Channel::where('uid', $channelUid)->first(['uid', 'owner_uid', 'lang', 'status', 'is_system']);
+            if ($channel === null || $channel->owner_uid !== $studioUid) {
+                throw new TermImportRowError(__('messages.term_import_channel_not_in_studio', ['channel' => $channelUid]));
+            }
+            if (! $this->channels->abilities($channel, $actorUid)['write']) {
+                throw new TermImportRowError(__('messages.term_forbidden'));
+            }
+
+            return [
+                'scope' => DhammaTerm::query()->where('channal', $channel->uid),
+                'target' => ['channel' => $channel->uid, 'owner' => $studioUid, 'language' => $channel->lang],
+                'language_editable' => false,
+            ];
+        });
+    }
+
+    /**
+     * @param  callable(array<string, string|null>): array{scope: Builder<DhammaTerm>, target: array{channel: string|null, owner: string, language: string}, language_editable: bool}  $placeOf
+     * @return array{created: int, updated: int, unchanged: int, reindexed: bool, errors: list<array{row: int, message: string}>}
+     */
+    private function import(string $actorUid, UploadedFile $file, callable $placeOf): array
+    {
+        $rows = $this->readRows($file);
+        $actor = ['editor' => $actorUid, 'co_editor' => null, 'scope' => null];
+        $result = ['created' => 0, 'updated' => 0, 'unchanged' => 0, 'reindexed' => false, 'errors' => []];
+        $written = [];
+
+        foreach ($rows as $line => $row) {
+            try {
+                $outcome = $this->importRow($actor, $row, $placeOf($row));
+                $result[$outcome['status']]++;
+                if ($outcome['term'] !== null) {
+                    $written[] = $outcome['term'];
+                }
+            } catch (TermImportRowError|BusinessException $e) {
+                $result['errors'][] = ['row' => $line, 'message' => $e->getMessage()];
+            } catch (ValidationException $e) {
+                $result['errors'][] = ['row' => $line, 'message' => collect($e->errors())->flatten()->implode(' ')];
+            } catch (AuthorizationException $e) {
+                $result['errors'][] = ['row' => $line, 'message' => $e->getMessage() ?: __('messages.term_forbidden')];
+            }
+        }
+
+        if (count($written) <= self::REINDEX_LIMIT) {
+            foreach ($written as $term) {
+                $this->terms->afterWrite($term);
+            }
+            $result['reindexed'] = true;
+        }
+
+        return $result;
+    }
+
+    /**
+     * 一行:新建、修改或没变化。出错抛异常,由调用方记进 errors。
+     *
+     * @param  array{editor: string, co_editor: null, scope: null}  $actor
+     * @param  array<string, string|null>  $row
+     * @param  array{scope: Builder<DhammaTerm>, target: array{channel: string|null, owner: string, language: string}, language_editable: bool}  $place
+     * @return array{status: 'created'|'updated'|'unchanged', term: DhammaTerm|null}
+     */
+    private function importRow(array $actor, array $row, array $place): array
+    {
+        $word = $row['word'] ?? null;
+        if ($word === null) {
+            throw new TermImportRowError(__('messages.term_import_word_required'));
+        }
+        $tag = $this->terms->normalizeTag($row['tag'] ?? null);
+
+        if (($row['id'] ?? null) !== null) {
+            $term = (clone $place['scope'])->where('guid', $row['id'])->first();
+            if ($term === null) {
+                throw new TermImportRowError(__('messages.term_import_not_found', ['id' => $row['id']]));
+            }
+            if ($term->word !== $word || $this->terms->normalizeTag($term->tag) !== $tag) {
+                throw new TermImportRowError(__('messages.term_word_immutable'));
+            }
+            if (($row['etag'] ?? null) !== null && $row['etag'] !== $term->etag()) {
+                throw new TermImportRowError(__('messages.term_import_modified'));
+            }
+        } else {
+            $term = $this->terms->findExisting(clone $place['scope'], $word, $tag);
+        }
+
+        $changes = $this->contentOf($row, $place['language_editable']);
+        $this->terms->guardRedirect($word, $tag, $changes);
+
+        if ($term === null) {
+            $this->assertCanCreate($actor['editor'], $place['target']);
+            if (($changes['meaning'] ?? null) === null) {
+                throw new TermImportRowError(__('messages.term_import_meaning_required'));
+            }
+            $created = $this->terms->insert($actor, $changes + ['word' => $word, 'tag' => $tag] + $place['target'], index: false);
+
+            return ['status' => 'created', 'term' => $created];
+        }
+
+        if (! $this->terms->abilitiesMany(collect([$term]), $actor['editor'])[$term->guid]['update']) {
+            throw new TermImportRowError(__('messages.term_forbidden'));
+        }
+        if (array_key_exists('meaning', $changes) && $changes['meaning'] === null) {
+            throw new TermImportRowError(__('messages.term_import_meaning_required'));
+        }
+        $changes = array_filter($changes, fn ($value, $field) => $value !== $this->current($term, $field), ARRAY_FILTER_USE_BOTH);
+        if ($changes === []) {
+            return ['status' => 'unchanged', 'term' => null];
+        }
+        if (array_key_exists('note', $changes) && ! array_key_exists('content_type', $changes)) {
+            $changes['content_type'] = $term->effectiveContentType();
+        }
+        if (! $this->terms->applyChanges($term, $actor, $changes, index: false)) {
+            throw new TermImportRowError(__('messages.term_import_modified'));
+        }
+
+        return ['status' => 'updated', 'term' => $term->fresh()];
+    }
+
+    /**
+     * 表里有的内容列 → 要写的值(空格子 = 清空)。quality / content_type 校验取值。
+     *
+     * @param  array<string, string|null>  $row
+     * @return array<string, string|null>
+     */
+    private function contentOf(array $row, bool $languageEditable): array
+    {
+        $changes = array_intersect_key($row, array_flip(self::CONTENT));
+        if ($languageEditable && array_key_exists('language', $row) && $row['language'] !== null) {
+            $changes['language'] = $row['language'];
+        }
+        if (($changes['quality'] ?? null) !== null && ! in_array($changes['quality'], DhammaTerm::QUALITIES, true)) {
+            throw new TermImportRowError(__('messages.term_import_bad_value', ['field' => 'quality', 'value' => $changes['quality']]));
+        }
+        if (array_key_exists('content_type', $changes)) {
+            if ($changes['content_type'] === null) {
+                unset($changes['content_type']);
+            } elseif (! in_array($changes['content_type'], DhammaTerm::CONTENT_TYPES, true)) {
+                throw new TermImportRowError(__('messages.term_import_bad_value', ['field' => 'content_type', 'value' => $changes['content_type']]));
+            }
+        }
+
+        return $changes;
+    }
+
+    private function current(DhammaTerm $term, string $field): ?string
+    {
+        $value = $field === 'content_type' ? $term->effectiveContentType() : $term->getAttribute($field);
+
+        return $value === null || $value === '' ? null : (string) $value;
+    }
+
+    /**
+     * @param  array{channel: string|null, owner: string, language: string}  $target
+     */
+    private function assertCanCreate(string $actorUid, array $target): void
+    {
+        $allowed = $target['channel'] !== null
+            ? true   // channel 的写权限在定位时已经查过
+            : $this->groups->can($actorUid, $target['owner'], GroupAbilityService::CREATE);
+        if (! $allowed) {
+            throw new TermImportRowError(__('messages.term_forbidden'));
+        }
+    }
+
+    /**
+     * 读表格:第一行是列名(不分大小写),之后每行按列名取值;整行空的跳过。键是表格里的行号。
+     *
+     * @return array<int, array<string, string|null>>
+     *
+     * @throws ValidationException
+     */
+    private function readRows(UploadedFile $file): array
+    {
+        try {
+            $reader = IOFactory::createReader('Xlsx');
+            $reader->setReadDataOnly(true);
+            $sheet = $reader->load($file->getRealPath())->getActiveSheet();
+        } catch (\Throwable) {
+            throw ValidationException::withMessages(['file' => __('messages.term_import_unreadable')]);
+        }
+
+        $highestColumn = Coordinate::columnIndexFromString($sheet->getHighestColumn());
+        $headers = [];
+        for ($col = 1; $col <= $highestColumn; $col++) {
+            $name = strtolower(trim((string) $sheet->getCell([$col, 1])->getValue()));
+            if (in_array($name, self::COLUMNS, true)) {
+                $headers[$col] = $name;
+            }
+        }
+        if (! in_array('word', $headers, true) || ! in_array('meaning', $headers, true)) {
+            throw ValidationException::withMessages(['file' => __('messages.term_import_header_required')]);
+        }
+
+        $rows = [];
+        $highestRow = $sheet->getHighestDataRow();
+        if ($highestRow - 1 > self::MAX_ROWS) {
+            throw ValidationException::withMessages(['file' => __('messages.term_import_too_many', ['max' => self::MAX_ROWS])]);
+        }
+        for ($line = 2; $line <= $highestRow; $line++) {
+            $row = [];
+            foreach ($headers as $col => $name) {
+                $value = trim((string) $sheet->getCell([$col, $line])->getValue());
+                $row[$name] = $value === '' ? null : $value;
+            }
+            if (array_filter($row, fn ($value) => $value !== null) === []) {
+                continue;
+            }
+            $rows[$line] = $row;
+        }
+
+        return $rows;
+    }
+}

+ 8 - 0
api-v13/app/Services/V3/TermImportRowError.php

@@ -0,0 +1,8 @@
+<?php
+
+namespace App\Services\V3;
+
+/**
+ * 术语导入时某一行不能写入的原因:记进响应的 errors,不中断其它行(见 {@see TermExchangeService})。
+ */
+final class TermImportRowError extends \RuntimeException {}

+ 718 - 0
api-v13/app/Services/V3/TermService.php

@@ -0,0 +1,718 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Exceptions\BusinessException;
+use App\Facades\RedisCache;
+use App\Models\Channel;
+use App\Models\DhammaTerm;
+use App\Models\TermCategory;
+use App\Services\Markup\Format;
+use App\Services\Markup\MarkupService;
+use App\Services\Markup\RenderOptions;
+use App\Services\OpenSearchService;
+use App\Services\TermIndexService;
+use App\Services\UserService;
+use App\Tools\Tools;
+use Illuminate\Auth\Access\AuthorizationException;
+use Illuminate\Contracts\Pagination\LengthAwarePaginator;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Str;
+use Illuminate\Validation\ValidationException;
+
+/**
+ * 术语 / 百科词条(只给 v3 用):查看、按 channel / studio 列出、按词查、建、改、删。
+ *
+ * 取代 v2 `DhammaTermController`(show、index 的 channel / studio / word、store、update、destroy)。
+ * v2 那份原地保留不动(铁律 2),不共用代码。
+ *
+ * 权限:
+ * - 挂在 channel 下的术语跟 channel 走({@see ChannelAbilityService}):能读 channel 就能读,能写 channel 内容就能建、改
+ * - studio 级术语(channal 为空,owner 名下所有 channel 共用):谁都能读;建要 owner 的 create,改要 update
+ *   ({@see GroupAbilityService}:团队 owner / manager 能建,editor 也能改)
+ * - 删:owner 本人或团队 owner(GroupAbilityService 的 delete);只给人类
+ *
+ * 写入方(`$actor`)由 {@see AgentGrantService::actor()} 给出:AI 模型凭人类授权代写时 editor 是授权人、
+ * co_editor 是模型,权限按 editor 判,且只能写授权覆盖的 channel(按 book 限定的授权不覆盖术语)。
+ *
+ * 分类不是入参:写入时从正文的 `{{category|…}}` 抽出存进 term_categories(内容多由 LLM 生成,分类不做限制)。
+ * word + tag 建立后不准改(引用方写 `[[word@tag]]`),要改就新建一条、把旧的 redirect 过去。
+ * 修改带乐观锁:If-Match 必须等于当前 ETag({@see DhammaTerm::etag()}),否则 412;不带 428。
+ */
+class TermService
+{
+    /** 列表可排序的字段 */
+    public const ORDERS = ['updated_at', 'created_at', 'word'];
+
+    /** 改了这些字段算「改内容」:co_editor 跟着这次写入走(人改清空、AI 改换成该模型) */
+    private const CONTENT_FIELDS = ['meaning', 'other_meaning', 'note', 'summary', 'quality', 'content_type', 'redirect', 'language'];
+
+    /** @var array<string, array<string, bool>> 请求内缓存:用户|owner → 能力 */
+    private array $groupAbilities = [];
+
+    public function __construct(
+        private readonly ChannelAbilityService $channels,
+        private readonly GroupAbilityService $groups,
+        private readonly AgentGrantService $agents,
+        private readonly MarkupService $markup,
+        private readonly UserService $users,
+    ) {}
+
+    /* ------------------------------------------------------------------ 读 */
+
+    /**
+     * 单条,带渲染后的正文(摘要 + 正文)。
+     *
+     * 正文默认按术语所在 channel 解析模板;$render 可以指定按哪些 channel 解析(阅读器右栏选版本)
+     * 与 read / edit 模式。指定的 channel 只认查看者看得见的,一个都看不见就退回术语所在 channel。
+     * format=html 时正文输出 HTML(挂在 html 上,给用 WebView 显示的客户端),否则输出节点树(body)。
+     *
+     * @param  array{channels?: list<string>, mode?: string, format?: string}  $render
+     *
+     * @throws AuthorizationException 看不见
+     */
+    public function show(DhammaTerm $term, ?string $viewerUid, array $render = []): DhammaTerm
+    {
+        $abilities = $this->abilitiesMany(collect([$term]), $viewerUid)[$term->guid];
+        if (! $abilities['read']) {
+            throw new AuthorizationException(__('messages.term_forbidden'));
+        }
+        $term->load($this->relations());
+        $this->decorate(collect([$term]), $viewerUid, withBody: true, render: [
+            'channels' => $this->readableChannels($render['channels'] ?? [], $viewerUid),
+            'mode' => $render['mode'] ?? 'read',
+            'format' => $render['format'] ?? 'tree',
+        ]);
+
+        return $term;
+    }
+
+    /**
+     * 这些 channel 里查看者看得见的,保持传入顺序。
+     *
+     * @param  list<string>  $uids
+     * @return list<string>
+     */
+    private function readableChannels(array $uids, ?string $viewerUid): array
+    {
+        if ($uids === []) {
+            return [];
+        }
+        $channels = Channel::whereIn('uid', $uids)->get(['uid', 'owner_uid', 'status', 'is_system']);
+        $abilities = $this->channels->abilitiesMany($channels, $viewerUid);
+
+        return array_values(array_filter($uids, fn (string $uid) => $abilities[$uid]['read'] ?? false));
+    }
+
+    /**
+     * 某个 channel 的术语。
+     *
+     * @param  array{search?: string|null, quality?: string, category?: string, order?: string, dir?: string}  $filters
+     * @return LengthAwarePaginator<int, DhammaTerm>
+     *
+     * @throws AuthorizationException 看不见这个 channel
+     */
+    public function listInChannel(Channel $channel, array $filters, ?string $viewerUid, int $perPage): LengthAwarePaginator
+    {
+        return $this->paginate($this->channelQuery($channel, $viewerUid), $filters, $viewerUid, $perPage);
+    }
+
+    /**
+     * 某个 channel 的术语查询(列表、导出共用)。
+     *
+     * @return Builder<DhammaTerm>
+     *
+     * @throws AuthorizationException 看不见这个 channel
+     */
+    public function channelQuery(Channel $channel, ?string $viewerUid): Builder
+    {
+        if (! $this->channels->abilities($channel, $viewerUid)['read']) {
+            throw new AuthorizationException(__('messages.channel_forbidden'));
+        }
+
+        return DhammaTerm::query()->where('channal', $channel->uid);
+    }
+
+    /**
+     * 某个 studio(本人或团队)名下的术语:它的 channel 里的与 studio 级的。`general=true` 只要 studio 级的。
+     *
+     * @param  array{search?: string|null, quality?: string, category?: string, general?: bool, order?: string, dir?: string}  $filters
+     * @return LengthAwarePaginator<int, DhammaTerm>
+     *
+     * @throws AuthorizationException 不是本人,也不是这个团队的成员
+     */
+    public function listInStudio(string $studioUid, array $filters, string $viewerUid, int $perPage): LengthAwarePaginator
+    {
+        return $this->paginate($this->studioQuery($studioUid, $filters, $viewerUid), $filters, $viewerUid, $perPage);
+    }
+
+    /**
+     * 某个 studio 名下术语的查询(列表、导出共用)。`general=true` 只要 studio 级的。
+     *
+     * @param  array{general?: bool}  $filters
+     * @return Builder<DhammaTerm>
+     *
+     * @throws AuthorizationException 不是本人,也不是这个团队的成员
+     */
+    public function studioQuery(string $studioUid, array $filters, string $viewerUid): Builder
+    {
+        if (! $this->groups->can($viewerUid, $studioUid, GroupAbilityService::READ)) {
+            throw new AuthorizationException(__('messages.channel_studio_forbidden'));
+        }
+        $query = DhammaTerm::query()->where('owner', $studioUid);
+        if (! empty($filters['general'])) {
+            $query->whereNull('channal');
+        }
+
+        return $query;
+    }
+
+    /**
+     * 列表的过滤与排序(不分页),导出用。
+     *
+     * @param  Builder<DhammaTerm>  $query
+     * @param  array<string, mixed>  $filters
+     * @return Builder<DhammaTerm>
+     */
+    public function filtered(Builder $query, array $filters): Builder
+    {
+        $this->applyFilters($query, $filters);
+
+        return $query->orderBy('word')->orderBy('guid');
+    }
+
+    /**
+     * 按词查:这些词在所有看得见的 channel 与 studio 级术语里的词条(编辑时看同词的其它义项、社区译法)。
+     *
+     * `with_body` 时每条都带渲染后的正文(同一个词通常只有几条)。
+     *
+     * @param  array{word: string, tag?: string|null, channel?: string, language?: string, with_body?: bool}  $filters
+     * @return LengthAwarePaginator<int, DhammaTerm>
+     */
+    public function lookup(array $filters, ?string $viewerUid, int $perPage): LengthAwarePaginator
+    {
+        $words = array_values(array_filter(array_map('trim', explode(',', $filters['word']))));
+        $query = DhammaTerm::query()->whereIn('word', $words);
+        if (array_key_exists('tag', $filters)) {
+            $this->whereTag($query, $filters['tag']);
+        }
+        if (! empty($filters['channel'])) {
+            $query->where('channal', $filters['channel']);
+        }
+        if (! empty($filters['language'])) {
+            $query->where('language', $filters['language']);
+        }
+        // 看得见的:studio 级术语,或所在 channel 会被列出给查看者
+        $query->where(function (Builder $q) use ($viewerUid) {
+            $q->whereNull('channal')->orWhereIn('channal', function ($sub) use ($viewerUid) {
+                $sub->selectRaw('uid::text')->from('channels')->whereNull('deleted_at');
+                $this->channels->scopeListable($sub, $viewerUid);
+            });
+        });
+
+        return $this->paginate($query, ['order' => 'updated_at'] + $filters, $viewerUid, $perPage, ! empty($filters['with_body']));
+    }
+
+    /* ------------------------------------------------------------------ 写 */
+
+    /**
+     * 在 channel 里新建。owner 与语言跟 channel。
+     *
+     * @param  array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null}  $actor
+     * @param  array<string, mixed>  $data
+     *
+     * @throws AuthorizationException
+     * @throws BusinessException 同一 channel 里已有这个 word@tag(409)
+     */
+    public function createInChannel(Channel $channel, array $actor, array $data): DhammaTerm
+    {
+        if (! $this->agents->covers($actor['scope'], $channel->uid, null)
+            || ! $this->channels->abilities($channel, $actor['editor'])['write']) {
+            throw new AuthorizationException(__('messages.term_forbidden'));
+        }
+        $this->guardUnique(DhammaTerm::query()->where('channal', $channel->uid), $data);
+
+        return $this->create($actor, $data + [
+            'channel' => $channel->uid,
+            'owner' => $channel->owner_uid,
+            'language' => $channel->lang,
+        ]);
+    }
+
+    /**
+     * 在 studio 名下新建 studio 级术语(不属于任何 channel)。只给人类:agent 授权只覆盖 channel。
+     *
+     * @param  array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null}  $actor
+     * @param  array<string, mixed>  $data
+     *
+     * @throws AuthorizationException
+     * @throws BusinessException 同一 studio、同一语言已有这个 word@tag(409)
+     */
+    public function createInStudio(string $studioUid, array $actor, array $data): DhammaTerm
+    {
+        if ($actor['scope'] !== null || ! $this->groups->can($actor['editor'], $studioUid, GroupAbilityService::CREATE)) {
+            throw new AuthorizationException(__('messages.term_forbidden'));
+        }
+        $this->guardUnique(
+            DhammaTerm::query()->where('owner', $studioUid)->whereNull('channal')->where('language', $data['language']),
+            $data,
+        );
+
+        return $this->create($actor, $data + ['channel' => null, 'owner' => $studioUid]);
+    }
+
+    /**
+     * 改(只改传了的字段)。word / tag 不准改(FormRequest 已拦)。带乐观锁:$ifMatch 必须等于当前 ETag。
+     *
+     * @param  array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null}  $actor
+     * @param  array<string, mixed>  $data
+     *
+     * @throws AuthorizationException
+     * @throws BusinessException 428 没带 If-Match;412 这条在你编辑期间被改过
+     * @throws ValidationException
+     */
+    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')) {
+            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)) {
+            throw ValidationException::withMessages(['language' => __('messages.term_language_follows_channel')]);
+        }
+        $this->guardRedirect($term->word, $term->tag, $data);
+
+        $changes = array_intersect_key($data, array_flip(self::CONTENT_FIELDS));
+        if (array_key_exists('note', $changes) || array_key_exists('content_type', $changes)) {
+            $changes['content_type'] ??= $term->effectiveContentType();
+        }
+        $etag = $term->etag();
+        if ($ifMatch !== $etag) {
+            throw $this->modified($term);
+        }
+
+        if (! $this->applyChanges($term, $actor, $changes)) {
+            throw $this->modified($term->fresh() ?? $term);
+        }
+
+        return $this->show($term->fresh(), $actor['editor']);
+    }
+
+    /**
+     * 写入修改(比较并交换:版本与 modify_time 都没变才写),改了 note 就重抽分类,写完清缓存。
+     * 不查权限、不渲染——由调用方负责(单条修改、导入共用)。$index=false 时不立即重建搜索索引。
+     *
+     * @param  array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null}  $actor
+     * @param  array<string, mixed>  $changes  只含要改的内容字段
+     * @return bool 在别人之后写的(期间被改过)返回 false,什么都没写
+     */
+    public function applyChanges(DhammaTerm $term, array $actor, array $changes, bool $index = true): bool
+    {
+        $changed = DB::transaction(function () use ($term, $actor, $changes) {
+            $updates = $changes + [
+                'editor_uid' => $actor['editor'],
+                'editor_id' => $this->users->intIdByUuid($actor['editor']) ?? 0,
+                'co_editor_uid' => $actor['co_editor'],
+                'modify_time' => time() * 1000,
+                'version' => (int) $term->version + 1,
+                'updated_at' => now(),
+            ];
+            // 比较并交换:版本与 modify_time 都没变才写(v2 的修改只动 modify_time)
+            $affected = DhammaTerm::query()
+                ->where('guid', $term->guid)
+                ->where('version', (int) $term->version)
+                ->where('modify_time', (int) $term->modify_time)
+                ->update($updates);
+            if ($affected === 0) {
+                return false;
+            }
+            if (array_key_exists('note', $changes)) {
+                $this->syncCategories($term->guid, $changes['note']);
+            }
+
+            return true;
+        });
+        if ($changed) {
+            $this->afterWrite($term->fresh(), $index);
+        }
+
+        return $changed;
+    }
+
+    /**
+     * 软删除,返回被删的术语(AIP-164)。分类留着,恢复时还在。
+     *
+     * @throws AuthorizationException
+     */
+    public function delete(DhammaTerm $term, string $actorUid): DhammaTerm
+    {
+        $this->agents->assertHuman($actorUid);
+        if (! $this->can($term, $actorUid, 'delete')) {
+            throw new AuthorizationException(__('messages.term_forbidden'));
+        }
+        $term->delete();
+        $this->forgetCache($term);
+        try {
+            app(OpenSearchService::class)->delete("term_{$term->guid}");
+        } catch (\Throwable $e) {
+            Log::warning('Failed to remove deleted term from index', ['guid' => $term->guid, 'error' => $e->getMessage()]);
+        }
+
+        $term->load($this->relations());
+        $this->decorate(collect([$term]), $actorUid, withBody: false);
+
+        return $term;
+    }
+
+    /* ------------------------------------------------------------------ 权限 */
+
+    /**
+     * 本人对这批术语能做什么。channel 的能力整批算一次;studio 级与删除按 owner 算,同一 owner 只查一次。
+     *
+     * @param  Collection<int, DhammaTerm>  $terms
+     * @return array<string, array{read: bool, update: bool, delete: bool}>
+     */
+    public function abilitiesMany(Collection $terms, ?string $userUid): array
+    {
+        $channelUids = $terms->pluck('channal')->filter()->unique()->values();
+        $channelModels = $channelUids->isEmpty()
+            ? collect()
+            : Channel::whereIn('uid', $channelUids)->get(['uid', 'owner_uid', 'status', 'is_system']);
+        $channelAbilities = $this->channels->abilitiesMany($channelModels, $userUid);
+
+        $result = [];
+        foreach ($terms as $term) {
+            if ($term->channal !== null) {
+                $ch = $channelAbilities[$term->channal] ?? ['read' => false, 'write' => false];
+                $read = $ch['read'];
+                $update = $userUid !== null && $ch['write'];
+            } else {
+                $read = true;
+                $update = $userUid !== null && $this->groupCan($userUid, $term->owner, GroupAbilityService::UPDATE);
+            }
+            $delete = $userUid !== null && $this->groupCan($userUid, $term->owner, GroupAbilityService::DELETE);
+            $result[$term->guid] = ['read' => $read, 'update' => $update, 'delete' => $delete];
+        }
+
+        return $result;
+    }
+
+    private function can(DhammaTerm $term, string $userUid, string $ability): bool
+    {
+        return $this->abilitiesMany(collect([$term]), $userUid)[$term->guid][$ability];
+    }
+
+    private function groupCan(string $userUid, string $ownerUid, string $ability): bool
+    {
+        return $this->groupAbilities["{$userUid}|{$ownerUid}"][$ability]
+            ??= $this->groups->can($userUid, $ownerUid, $ability);
+    }
+
+    /* ------------------------------------------------------------------ 内部 */
+
+    /**
+     * @param  Builder<DhammaTerm>  $query
+     * @param  array<string, mixed>  $filters
+     * @return LengthAwarePaginator<int, DhammaTerm>
+     */
+    private function paginate(Builder $query, array $filters, ?string $viewerUid, int $perPage, bool $withBody = false): LengthAwarePaginator
+    {
+        $this->applyFilters($query, $filters);
+        $order = $filters['order'] ?? 'updated_at';
+        $dir = $filters['dir'] ?? ($order === 'word' ? 'asc' : 'desc');
+
+        $page = $query->with($this->relations())
+            ->orderBy($order, $dir)
+            ->orderBy('guid')
+            ->paginate($perPage);
+        $this->decorate($page->getCollection(), $viewerUid, withBody: $withBody);
+
+        return $page;
+    }
+
+    /**
+     * @param  Builder<DhammaTerm>  $query
+     * @param  array<string, mixed>  $filters
+     */
+    private function applyFilters(Builder $query, array $filters): void
+    {
+        if (! empty($filters['search'])) {
+            $like = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $filters['search']).'%';
+            $query->where(fn (Builder $q) => $q->where('word', 'ilike', $like)
+                ->orWhere('word_en', 'ilike', $like)
+                ->orWhere('meaning', 'ilike', $like)
+                ->orWhere('other_meaning', 'ilike', $like));
+        }
+        if (! empty($filters['quality'])) {
+            $filters['quality'] === 'pending'
+                ? $query->where(fn (Builder $q) => $q->where('quality', 'pending')->orWhereNull('quality'))
+                : $query->where('quality', $filters['quality']);
+        }
+        if (! empty($filters['category'])) {
+            // term_categories.term_guid 是 uuid,dhamma_terms.guid 是 varchar
+            $query->whereIn('guid', TermCategory::query()->selectRaw('term_guid::text')->where('category', $filters['category']));
+        }
+    }
+
+    /**
+     * @return list<string>
+     */
+    private function relations(): array
+    {
+        return [
+            ...UserService::eagerLoadActor(),
+            UserService::eagerLoadAssistant('coEditor'),
+            // 只取分类名(与外键、排序);term_categories.id 不对外,也用不到
+            'categories:term_guid,category,position',
+            'channel:uid,name',
+        ];
+    }
+
+    /**
+     * 挂上 abilities、摘要纯文本,详情另挂渲染后的正文。整批渲染一次。
+     *
+     * 正文 = 摘要 + 正文(摘要放在前面,不加分隔)。摘要纯文本:有摘要用摘要,没有取正文第一段。
+     * $render 只用于正文:channels 非空时代替术语所在 channel,mode 为 read / edit,
+     * format 为 tree(挂 body)/ html(挂 html)。
+     *
+     * @param  Collection<int, DhammaTerm>  $terms
+     * @param  array{channels?: list<string>, mode?: string, format?: string}  $render
+     */
+    private function decorate(Collection $terms, ?string $viewerUid, bool $withBody, array $render = []): void
+    {
+        if ($terms->isEmpty()) {
+            return;
+        }
+        $abilities = $this->abilitiesMany($terms, $viewerUid);
+
+        $items = [];
+        foreach ($terms as $term) {
+            $base = [
+                'channels' => $term->channal ? [$term->channal] : [],
+                'contentType' => $term->effectiveContentType(),
+            ];
+            $summary = trim((string) $term->summary);
+            $items["{$term->guid}|summary"] = $base + ['source' => $summary !== '' ? $summary : (string) $term->note];
+            if ($withBody) {
+                $bodyChannels = ! empty($render['channels']) ? $render['channels'] : $base['channels'];
+                $items["{$term->guid}|body"] = ['channels' => $bodyChannels] + $base + ['source' => trim($summary."\n\n".(string) $term->note)];
+            }
+        }
+        $bodyFormat = ($render['format'] ?? 'tree') === 'html' ? Format::Html : Format::Tree;
+        $rendered = $this->markup->renderManyAs(
+            $items,
+            new RenderOptions(mode: $render['mode'] ?? 'read'),
+            $withBody ? [Format::Text, $bodyFormat] : [Format::Text],
+        );
+
+        foreach ($terms as $term) {
+            $term->abilities = $abilities[$term->guid];
+            $text = (string) $rendered[Format::Text->value]["{$term->guid}|summary"];
+            $term->summary_text = trim((string) $term->summary) !== '' ? trim($text) : $this->firstParagraph($text);
+            if ($withBody && $bodyFormat === Format::Html) {
+                $term->html = (string) $rendered[Format::Html->value]["{$term->guid}|body"];
+            } elseif ($withBody) {
+                $term->body = $rendered[Format::Tree->value]["{$term->guid}|body"];
+            }
+        }
+    }
+
+    /**
+     * 纯文本渲染({@see Format::Text})里段落之间只隔一个换行,第一个非空行就是第一段。
+     */
+    private function firstParagraph(string $text): string
+    {
+        foreach (preg_split('/\n/u', $text) ?: [] as $paragraph) {
+            $paragraph = trim($paragraph);
+            if ($paragraph !== '') {
+                return $paragraph;
+            }
+        }
+
+        return '';
+    }
+
+    /**
+     * @param  array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null}  $actor
+     * @param  array<string, mixed>  $data  已含 channel / owner / language
+     */
+    private function create(array $actor, array $data): DhammaTerm
+    {
+        $this->guardRedirect($data['word'], $data['tag'] ?? null, $data);
+
+        return $this->show($this->insert($actor, $data), $actor['editor']);
+    }
+
+    /**
+     * 写入一条新术语并抽分类、清缓存。不查权限、不查重、不渲染——由调用方负责(单条新建、导入共用)。
+     * $index=false 时不立即重建搜索索引。
+     *
+     * @param  array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null}  $actor
+     * @param  array<string, mixed>  $data  已含 channel / owner / language
+     */
+    public function insert(array $actor, array $data, bool $index = true): DhammaTerm
+    {
+        $now = time() * 1000;
+        $term = new DhammaTerm;
+        $term->forceFill([
+            'id' => app('snowflake')->id(),
+            'guid' => (string) Str::uuid(),
+            'word' => $data['word'],
+            'word_en' => Tools::getWordEn($data['word']),
+            'tag' => $this->normalizeTag($data['tag'] ?? null),
+            'meaning' => $data['meaning'],
+            'other_meaning' => $data['other_meaning'] ?? null,
+            'note' => $data['note'] ?? null,
+            'summary' => $data['summary'] ?? null,
+            'quality' => $data['quality'] ?? null,
+            'content_type' => $data['content_type'] ?? DhammaTerm::CONTENT_TYPE_V3,
+            'redirect' => $data['redirect'] ?? null,
+            'channal' => $data['channel'],
+            'language' => $data['language'],
+            'owner' => $data['owner'],
+            'editor_uid' => $actor['editor'],
+            'editor_id' => $this->users->intIdByUuid($actor['editor']) ?? 0,
+            'co_editor_uid' => $actor['co_editor'],
+            'version' => 1,
+            'create_time' => $now,
+            'modify_time' => $now,
+        ]);
+        DB::transaction(function () use ($term) {
+            $term->save();
+            $this->syncCategories($term->guid, $term->note);
+        });
+        $this->afterWrite($term, $index);
+
+        return $term->fresh();
+    }
+
+    /**
+     * 同一范围里 word + tag 唯一(tag 空串与 null 视为相同)。
+     *
+     * @param  Builder<DhammaTerm>  $scope
+     * @param  array<string, mixed>  $data
+     *
+     * @throws BusinessException
+     */
+    private function guardUnique(Builder $scope, array $data): void
+    {
+        $existing = $this->findExisting($scope, $data['word'], $data['tag'] ?? null)?->guid;
+        if ($existing !== null) {
+            throw new BusinessException(__('messages.term_exists'), 409, 'term-exists', ['existing' => $existing]);
+        }
+    }
+
+    /**
+     * 范围内同 word + tag 的那一条(tag 空串与 null 视为相同)。
+     *
+     * @param  Builder<DhammaTerm>  $scope
+     */
+    public function findExisting(Builder $scope, string $word, ?string $tag): ?DhammaTerm
+    {
+        $query = $scope->where('word', $word);
+        $this->whereTag($query, $tag);
+
+        return $query->first();
+    }
+
+    /**
+     * redirect 写成 word 或 word@tag,不能指向自己。目标是否存在不查(内容多由 LLM 生成,批量写入时目标可能还没建)。
+     *
+     * @param  array<string, mixed>  $data
+     *
+     * @throws ValidationException
+     */
+    public function guardRedirect(string $word, ?string $tag, array $data): void
+    {
+        $redirect = $data['redirect'] ?? null;
+        if ($redirect === null || $redirect === '') {
+            return;
+        }
+        [$targetWord, $targetTag] = array_pad(explode('@', $redirect, 2), 2, '');
+        if ($targetWord === $word && $targetTag === (string) $this->normalizeTag($tag)) {
+            throw ValidationException::withMessages(['redirect' => __('messages.term_redirect_self')]);
+        }
+    }
+
+    /**
+     * @param  Builder<DhammaTerm>  $query
+     */
+    private function whereTag(Builder $query, ?string $tag): void
+    {
+        $tag = $this->normalizeTag($tag);
+        $tag === null
+            ? $query->where(fn (Builder $q) => $q->whereNull('tag')->orWhere('tag', ''))
+            : $query->where('tag', $tag);
+    }
+
+    public function normalizeTag(?string $tag): ?string
+    {
+        $tag = trim((string) $tag);
+
+        return $tag === '' ? null : $tag;
+    }
+
+    /**
+     * 从正文抽出 {{category|…}},整体替换这条术语的分类。同名的只留第一个。
+     */
+    private function syncCategories(string $guid, ?string $note): void
+    {
+        preg_match_all('/\{\{category\|([^}|]+)\}\}/u', (string) $note, $matches);
+        $names = array_values(array_unique(array_filter(array_map(
+            fn (string $name) => mb_substr(trim($name), 0, 128),
+            $matches[1] ?? [],
+        ))));
+
+        TermCategory::where('term_guid', $guid)->delete();
+        foreach ($names as $position => $name) {
+            TermCategory::create(['term_guid' => $guid, 'category' => $name, 'position' => $position]);
+        }
+    }
+
+    public function modified(DhammaTerm $term): BusinessException
+    {
+        return new BusinessException(
+            __('messages.term_modified'),
+            412,
+            'term-modified',
+            ['etag' => $term->etag()],
+            'Precondition Failed',
+        );
+    }
+
+    /**
+     * 写入后:清 v2 的术语缓存(v4 / v6 的旧渲染还在读),重建 OpenSearch 索引(全站搜索用;失败不阻断写入)。
+     * $index=false 时只清缓存,索引由每周的 `opensearch:index-term` 补上(大批导入用)。
+     */
+    public function afterWrite(DhammaTerm $term, bool $index = true): void
+    {
+        $this->forgetCache($term);
+        if (! $index) {
+            return;
+        }
+        try {
+            app(TermIndexService::class)->index($term->guid);
+        } catch (\Throwable $e) {
+            Log::warning('Failed to index term after write', ['guid' => $term->guid, 'error' => $e->getMessage()]);
+        }
+    }
+
+    /**
+     * v2 的缓存键是 `/term/{channel uid}/{word}`;studio 级术语要清 owner 名下每个 channel 的
+     * (v2 自己那份清不掉:拿模型而不是 uid 拼键,见 DhammaTermController::deleteCache 的 FIXME)。
+     */
+    private function forgetCache(DhammaTerm $term): void
+    {
+        $channels = $term->channal !== null
+            ? [$term->channal]
+            : Channel::where('owner_uid', $term->owner)->pluck('uid')->all();
+        foreach ($channels as $uid) {
+            RedisCache::forget("/term/{$uid}/{$term->word}");
+        }
+    }
+}

+ 282 - 0
api-v13/app/Services/WikiService.php

@@ -0,0 +1,282 @@
+<?php
+
+namespace App\Services;
+
+use App\Models\Channel;
+use App\Models\DhammaTerm;
+use App\Models\TermCategory;
+use App\Services\Markup\Format;
+use App\Services\Markup\MarkupService;
+use App\Services\Markup\RenderOptions;
+use App\Services\V3\ChannelAbilityService;
+use Illuminate\Database\Eloquent\Builder;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
+
+/**
+ * library 百科页(`/library/wiki/*`)的数据:按分类列词条、词条详情、相关词条、其它版本。
+ *
+ * 直接查库,不经 OpenSearch:质量取 dhamma_terms.quality,分类取 term_categories(v3 写入时从正文
+ * `{{category|…}}` 抽出),摘要取 summary 或正文第一段。正文用新渲染器({@see MarkupService})出 HTML。
+ *
+ * 只列公开的:所在 channel 会被列出(status 30 或系统 channel,{@see ChannelAbilityService::scopeListable()}),
+ * 或 studio 级术语(不属于任何 channel)。
+ */
+class WikiService
+{
+    /** 质量等级,数值越小越高;空按 pending */
+    public const QUALITY_RANK = ['featured' => 1, 'standard' => 2, 'draft' => 3, 'pending' => 4];
+
+    public function __construct(
+        private readonly ChannelAbilityService $channels,
+        private readonly MarkupService $markup,
+    ) {}
+
+    /**
+     * 某组分类下的词条,质量不低于 $minQuality。同一个「词 + 释义」只留质量最高的一条。
+     *
+     * @param  list<string>  $categories
+     * @return list<array{id: string, word: string, zh: string, quality: string}>
+     */
+    public function categoryEntries(array $categories, string $lang, string $minQuality): array
+    {
+        if ($categories === []) {
+            return [];
+        }
+        $maxRank = self::QUALITY_RANK[$minQuality] ?? 4;
+        $terms = $this->publicTerms($lang)
+            ->whereIn('guid', TermCategory::query()->selectRaw('term_guid::text')->whereIn('category', $categories))
+            ->orderBy('word')
+            ->limit(1000)
+            ->get(['guid', 'word', 'meaning', 'quality']);
+
+        $unique = [];
+        foreach ($terms as $term) {
+            $quality = $term->quality ?? 'pending';
+            $rank = self::QUALITY_RANK[$quality] ?? 4;
+            if ($rank > $maxRank) {
+                continue;
+            }
+            $key = mb_strtolower(trim($term->word).'|'.trim($term->meaning));
+            if (isset($unique[$key]) && (self::QUALITY_RANK[$unique[$key]['quality']] ?? 4) <= $rank) {
+                continue;
+            }
+            $unique[$key] = ['id' => (string) $term->guid, 'word' => (string) $term->word, 'zh' => (string) $term->meaning, 'quality' => $quality];
+        }
+
+        return array_values($unique);
+    }
+
+    /**
+     * 按 guid 或词找要显示的词条。
+     *
+     * - guid:这一条(要公开)
+     * - 词:先找该语言社区 channel(`_community_translation_{lang}_`)里的,没有就取公开词条里质量最高、最近更新的
+     */
+    public function find(string $lang, string $wordOrId): ?DhammaTerm
+    {
+        if (Str::isUuid($wordOrId)) {
+            return $this->publicTerms(null)->where('guid', $wordOrId)->first();
+        }
+
+        $community = Channel::where('name', '_community_translation_'.strtolower($lang).'_')
+            ->where('owner_uid', config('mint.admin.root_uuid'))
+            ->value('uid');
+        if ($community) {
+            $term = DhammaTerm::where('channal', $community)->where('word', $wordOrId)->first();
+            if ($term) {
+                return $term;
+            }
+        }
+
+        return $this->publicTerms($lang)
+            ->where('word', $wordOrId)
+            ->orderByRaw("case coalesce(quality, 'pending') when 'featured' then 1 when 'standard' then 2 when 'draft' then 3 else 4 end")
+            ->orderByDesc('updated_at')
+            ->first();
+    }
+
+    /**
+     * 重定向的目标(`word` 或 `word@tag`):先在同一 channel(studio 级的在同一 owner 的 studio 级术语)里找,
+     * 找不到返回 null(读者停在原词条上)。
+     */
+    public function redirectTarget(DhammaTerm $term): ?DhammaTerm
+    {
+        $redirect = trim((string) $term->redirect);
+        if ($redirect === '') {
+            return null;
+        }
+        [$word, $tag] = array_pad(explode('@', $redirect, 2), 2, '');
+        $query = DhammaTerm::query()->where('word', $word);
+        $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);
+
+        $target = $query->first();
+
+        return $target && $target->guid !== $term->guid ? $target : null;
+    }
+
+    /**
+     * 正文 HTML:摘要 + 正文(摘要在前,不加分隔),用词条所在 channel 解析模板。
+     *
+     * 正文里的分类(`{{category|…}}`,渲染器输出 `span.tpl-category[data-category]`)换成指向
+     * 该分类词条列表的链接,$lang 是当前百科页的语言。
+     */
+    public function contentHtml(DhammaTerm $term, string $lang): string
+    {
+        $source = trim(trim((string) $term->summary)."\n\n".(string) $term->note);
+        $html = (string) $this->markup->render($source, new RenderOptions(
+            format: Format::Html,
+            channels: $term->channal ? [$term->channal] : [],
+            contentType: $term->effectiveContentType(),
+            lang: $term->language ?: 'zh-Hans',
+        ));
+
+        return (string) preg_replace_callback(
+            '#<span class="tpl-category" data-category="([^"]*)">(.*?)</span>#u',
+            function (array $m) use ($lang) {
+                $name = html_entity_decode($m[1], ENT_QUOTES | ENT_HTML5);
+                $url = route('library.wiki.index', ['lang' => $lang, 'category' => $name]);
+
+                return '<a class="tpl-category" href="'.e($url).'">'.$m[2].'</a>';
+            },
+            $html,
+        );
+    }
+
+    /**
+     * 这条词条的分类(按正文里出现的顺序)。
+     *
+     * @return list<string>
+     */
+    public function categoriesOf(DhammaTerm $term): array
+    {
+        return TermCategory::where('term_guid', $term->guid)->orderBy('position')->pluck('category')->all();
+    }
+
+    /**
+     * 与它共享分类的其它公开词条,最多 $limit 条,共享分类越多越靠前。
+     *
+     * @param  list<string>  $categories
+     * @return list<array{word: string, zh: string, lang: string}>
+     */
+    public function related(DhammaTerm $term, array $categories, int $limit = 5): array
+    {
+        if ($categories === []) {
+            return [];
+        }
+        $shared = TermCategory::query()
+            ->selectRaw('term_guid::text as guid, count(*) as shared')
+            ->whereIn('category', $categories)
+            ->where('term_guid', '<>', $term->guid)
+            ->groupBy('term_guid');
+
+        return $this->publicTerms(null)
+            ->joinSub($shared, 'shared', 'shared.guid', '=', 'dhamma_terms.guid')
+            ->orderByDesc('shared.shared')
+            ->orderBy('dhamma_terms.word')
+            ->limit($limit)
+            ->get(['dhamma_terms.word', 'dhamma_terms.meaning', 'dhamma_terms.language'])
+            ->map(fn (DhammaTerm $t) => ['word' => (string) $t->word, 'zh' => (string) $t->meaning, 'lang' => (string) $t->language])
+            ->all();
+    }
+
+    /**
+     * 同一个词的其它公开版本(其它 channel、其它语言),最多 $limit 条。摘要是纯文本。
+     *
+     * @return list<array{type: string, id: string, lang: string, title: string, quality: string, category: string, snippet: string, updated: string}>
+     */
+    public function otherVersions(DhammaTerm $term, int $limit = 10): array
+    {
+        $versions = $this->publicTerms(null)
+            ->where('word', $term->word)
+            ->where('guid', '<>', $term->guid)
+            ->orderByDesc('updated_at')
+            ->limit($limit)
+            ->get(['guid', 'word', 'meaning', 'language', 'quality', 'summary', 'note', 'content_type', 'channal', 'updated_at']);
+
+        return $this->withSnippets($versions)->map(fn (DhammaTerm $t) => [
+            'type' => 'term',
+            'id' => (string) $t->guid,
+            'lang' => (string) $t->language,
+            'title' => (string) $t->meaning,
+            'quality' => $t->quality ?? 'pending',
+            'category' => '法义术语',
+            'snippet' => (string) $t->snippet,
+            'updated' => $t->updated_at?->toIso8601String() ?? '',
+        ])->all();
+    }
+
+    /**
+     * 公开的词条:所在 channel 会被列出,或 studio 级术语。$lang 给了就只要这种语言的。
+     *
+     * @return Builder<DhammaTerm>
+     */
+    private function publicTerms(?string $lang): Builder
+    {
+        $query = DhammaTerm::query()->where(function (Builder $q) {
+            $q->whereNull('channal')->orWhereIn('channal', function ($sub) {
+                $sub->selectRaw('uid::text')->from('channels')->whereNull('deleted_at');
+                $this->channels->scopeListable($sub, null);
+            });
+        });
+        if ($lang !== null) {
+            $query->whereIn(DB::raw('lower(language)'), $this->languageVariants($lang));
+        }
+
+        return $query;
+    }
+
+    /**
+     * 库里的语言写法不统一(zh-Hans / zh-hans / zh)。
+     *
+     * @return list<string>
+     */
+    private function languageVariants(string $lang): array
+    {
+        $lang = strtolower($lang);
+
+        return match ($lang) {
+            'zh-hans', 'zh-cn', 'zh' => ['zh-hans', 'zh-cn', 'zh'],
+            'zh-hant', 'zh-tw' => ['zh-hant', 'zh-tw'],
+            default => [$lang],
+        };
+    }
+
+    /**
+     * 给每条挂上纯文本摘要(`snippet`):有 summary 用它,没有取正文第一段。整批渲染一次。
+     *
+     * @param  Collection<int, DhammaTerm>  $terms
+     * @return Collection<int, DhammaTerm>
+     */
+    private function withSnippets(Collection $terms): Collection
+    {
+        $items = [];
+        foreach ($terms as $term) {
+            $summary = trim((string) $term->summary);
+            $items[$term->guid] = [
+                'source' => $summary !== '' ? $summary : (string) $term->note,
+                'channels' => $term->channal ? [$term->channal] : [],
+                'contentType' => $term->effectiveContentType(),
+            ];
+        }
+        $texts = $items === [] ? [] : $this->markup->renderMany($items, new RenderOptions(format: Format::Text));
+
+        return $terms->each(function (DhammaTerm $term) use ($texts) {
+            $text = (string) ($texts[$term->guid] ?? '');
+            $first = '';
+            foreach (preg_split('/\n/u', $text) ?: [] as $line) {
+                if (trim($line) !== '') {
+                    $first = trim($line);
+                    break;
+                }
+            }
+            $term->snippet = Str::limit($first, 200);
+        });
+    }
+}

+ 34 - 0
api-v13/database/migrations/2026_11_17_075645_add_v3_columns_to_dhamma_terms.php

@@ -0,0 +1,34 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+    /**
+     * 术语迁 v3 要的列。v2 / v4 不读这些列;全部可空或带默认值(铁律 4)。
+     */
+    public function up(): void
+    {
+        Schema::table('dhamma_terms', function (Blueprint $table) {
+            $table->uuid('co_editor_uid')->nullable()
+                ->comment('AI 代写时的模型 uid(editor_uid 是授权人);人亲自改内容时清空');
+            $table->string('quality', 16)->nullable()
+                ->comment('词条质量:featured / standard / draft / pending;为空按 pending 显示。取代正文里的 {{quality|…}}');
+            $table->text('summary')->nullable()
+                ->comment('摘要,格式与 note 相同(content_type 决定方言);渲染时放在正文前。为空时由正文第一段推出');
+            $table->string('content_type', 16)->default('markdown')
+                ->comment('summary 与 note 的方言:markdown(旧方言,v2 写入的都是它)/ markdown-e2。库默认 markdown 是因为 v2 写入不设这一列;v3 新建默认 markdown-e2');
+            $table->unsignedInteger('version')->default(1)
+                ->comment('乐观锁版本号,v3 每次修改 +1;ETag 由它与 modify_time 组成(v2 修改只动 modify_time)');
+        });
+    }
+
+    public function down(): void
+    {
+        Schema::table('dhamma_terms', function (Blueprint $table) {
+            $table->dropColumn(['co_editor_uid', 'quality', 'summary', 'content_type', 'version']);
+        });
+    }
+};

+ 30 - 0
api-v13/database/migrations/2026_11_17_075645_create_term_categories_table.php

@@ -0,0 +1,30 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+    /**
+     * 术语的百科分类。分类写在正文的 {{category|…}} 里,v3 写入时抽出来存这里,百科页按它查(不再经 OpenSearch)。
+     */
+    public function up(): void
+    {
+        Schema::create('term_categories', function (Blueprint $table) {
+            $table->id();
+            $table->uuid('term_guid')->comment('术语(dhamma_terms.guid)');
+            $table->string('category', 128)->comment('分类名,取自正文 {{category|…}},原样保存、不限于 config/taxonomy.php');
+            $table->unsignedSmallInteger('position')->default(0)->comment('在正文里出现的顺序,从 0 起');
+            $table->timestamps();
+
+            $table->unique(['term_guid', 'category']);
+            $table->index('category');
+        });
+    }
+
+    public function down(): void
+    {
+        Schema::dropIfExists('term_categories');
+    }
+};

+ 19 - 0
api-v13/resources/css/modules/wiki.css

@@ -150,6 +150,25 @@
     color: var(--tblr-body-color);
     color: var(--tblr-body-color);
 }
 }
 
 
+/* 正文里的 {{category|…}}:渲染器输出 span.tpl-category,百科页换成指向分类列表的链接;样式同 .wiki-tag */
+.wiki-content-body .tpl-category {
+    display: inline-block;
+    font-size: 0.75rem;
+    line-height: 1.5;
+    padding: 3px 10px;
+    margin: 0 4px 4px 0;
+    border-radius: 20px;
+    border: 1px solid var(--tblr-border-color);
+    color: var(--tblr-secondary);
+    text-decoration: none;
+    transition: background 0.12s;
+}
+
+.wiki-content-body a.tpl-category:hover {
+    background: var(--tblr-bg-surface-secondary);
+    color: var(--tblr-body-color);
+}
+
 /* ══════════════════════════════════════════
 /* ══════════════════════════════════════════
    四、首页组件
    四、首页组件
    ══════════════════════════════════════════ */
    ══════════════════════════════════════════ */

+ 51 - 7
api-v13/resources/js/modules/term-tooltip.js

@@ -15,13 +15,41 @@ import * as bootstrap from "bootstrap";
     // ── 缓存层 ────────────────────────────────────────────────────────
     // ── 缓存层 ────────────────────────────────────────────────────────
     const cache = {};
     const cache = {};
 
 
+    // 下面的模板用 innerHTML 拼接,取回的文字先转义
+    const escapeHtml = (text) =>
+        String(text ?? "").replace(/[&<>"']/g, (c) => ({
+            "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
+        })[c]);
+
+    // 百科页上点术语直接跳转;其它页面(阅读页)不跳走,「查看完整条目」在新标签页打开
+    const onWikiPage = /^\/library\/wiki\//.test(window.location.pathname);
+
+    // 词条的百科页地址:语言取当前百科页的,其它页面取 <html lang>
+    function wikiUrl(id) {
+        const m = window.location.pathname.match(/^\/library\/wiki\/([^/]+)/);
+        const lang = m
+            ? decodeURIComponent(m[1])
+            : document.documentElement.lang || "zh-Hans";
+        return `/library/wiki/${encodeURIComponent(lang)}/${encodeURIComponent(id)}`;
+    }
+
+    const linkTarget = onWikiPage ? "" : ' target="_blank" rel="noopener"';
+
+    // v3:summary_text 是纯文本摘要(有摘要用摘要,没有取正文第一段)
     async function fetchTerm(id) {
     async function fetchTerm(id) {
         if (cache[id]) return cache[id];
         if (cache[id]) return cache[id];
-        const res = await fetch(`/api/v2/terms/${id}`);
+        const res = await fetch(`/api/v3/terms/${id}`, {
+            headers: { Accept: "application/json" },
+        });
         if (!res.ok) throw new Error(`fetchTerm ${id} failed: ${res.status}`);
         if (!res.ok) throw new Error(`fetchTerm ${id} failed: ${res.status}`);
-        const json = await res.json();
-        cache[id] = json.data;
-        return json.data;
+        const { data } = await res.json();
+        cache[id] = {
+            word: escapeHtml(data.word),
+            meaning: escapeHtml(data.meaning),
+            summary: escapeHtml(data.summary_text),
+            url: wikiUrl(id),
+        };
+        return cache[id];
     }
     }
 
 
     // ── 设备判断 ──────────────────────────────────────────────────────
     // ── 设备判断 ──────────────────────────────────────────────────────
@@ -58,7 +86,7 @@ import * as bootstrap from "bootstrap";
                         : ""
                         : ""
                 }
                 }
             </div>
             </div>
-            <div><a>查看完整条目</a></div>
+            <div><a href="${data.url}"${linkTarget}>查看完整条目</a></div>
         `;
         `;
     }
     }
 
 
@@ -173,6 +201,15 @@ import * as bootstrap from "bootstrap";
         document.getElementById("wikiTermCardSlot").innerHTML = showSummary
         document.getElementById("wikiTermCardSlot").innerHTML = showSummary
             ? `<div class="wiki-term-card-summary">${summary}</div>`
             ? `<div class="wiki-term-card-summary">${summary}</div>`
             : "";
             : "";
+        const link = document.getElementById("wikiTermDrawerLink");
+        if (link && data.url) {
+            link.href = data.url;
+            if (!onWikiPage) {
+                link.target = "_blank";
+                link.rel = "noopener";
+            }
+            link.style.display = "";
+        }
     }
     }
 
 
     // ── 入口:扫描所有 .term-ref ──────────────────────────────────────
     // ── 入口:扫描所有 .term-ref ──────────────────────────────────────
@@ -204,9 +241,16 @@ import * as bootstrap from "bootstrap";
                 el.removeEventListener("mouseenter", onFirstEnter);
                 el.removeEventListener("mouseenter", onFirstEnter);
             });
             });
 
 
-            // 移动端:点击立即弹出 skeleton,数据回来后填充
+            // 移动端:点击立即弹出 skeleton,数据回来后填充(抽屉里有「查看完整条目」)
+            // 桌面端:百科页上点击直接跳到那条术语
             el.addEventListener("click", async (e) => {
             el.addEventListener("click", async (e) => {
-                if (!isMobile()) return;
+                if (!isMobile()) {
+                    if (onWikiPage) {
+                        e.preventDefault();
+                        window.location.href = wikiUrl(el.dataset.id);
+                    }
+                    return;
+                }
                 e.preventDefault();
                 e.preventDefault();
 
 
                 showMobileDrawerSkeleton();
                 showMobileDrawerSkeleton();

+ 56 - 0
api-v13/resources/js/modules/wiki-share.js

@@ -0,0 +1,56 @@
+// resources/js/modules/wiki-share.js
+// 百科词条页「分享到微信」:弹窗里用 qrcode 在本地生成当前页面 URL 的二维码(不再请求第三方服务)。
+// 仅在有 #wikiShareWechat / #wikiWechatModal / #wikiWechatQr 的页面(library/wiki/show)生效。
+
+import QRCode from "qrcode";
+
+function initWikiShare() {
+    const btn = document.getElementById("wikiShareWechat");
+    const modal = document.getElementById("wikiWechatModal");
+    const backdrop = document.getElementById("wikiWechatBackdrop");
+    const closeBtn = document.getElementById("wikiWechatClose");
+    const qrEl = document.getElementById("wikiWechatQr");
+
+    if (!btn || !modal || !qrEl) {
+        return;
+    }
+
+    const canvas = document.createElement("canvas");
+    qrEl.replaceChildren(canvas);
+
+    async function open() {
+        try {
+            await QRCode.toCanvas(canvas, window.location.href, {
+                width: 180,
+                margin: 2,
+                errorCorrectionLevel: "M",
+                color: {
+                    dark: "#1d273b",
+                    light: "#ffffff",
+                },
+            });
+        } catch (err) {
+            console.warn("[WikiPāli] QR code generation failed", err);
+        }
+        modal.style.display = "flex";
+    }
+
+    function close() {
+        modal.style.display = "none";
+    }
+
+    btn.addEventListener("click", open);
+    closeBtn?.addEventListener("click", close);
+    backdrop?.addEventListener("click", close);
+    document.addEventListener("keydown", (e) => {
+        if (e.key === "Escape") {
+            close();
+        }
+    });
+}
+
+if (document.readyState === "loading") {
+    document.addEventListener("DOMContentLoaded", initWikiShare);
+} else {
+    initWikiShare();
+}

+ 17 - 0
api-v13/resources/lang/en/messages.php

@@ -72,4 +72,21 @@ return [
     'channel_link_fallback_type' => 'A fallback channel must be of the same type as this channel.',
     'channel_link_fallback_type' => 'A fallback channel must be of the same type as this channel.',
     'channel_link_term_source_channel' => 'Only translation channels can have term sources.',
     'channel_link_term_source_channel' => 'Only translation channels can have term sources.',
     'channel_link_term_source_type' => 'Term sources must be translation channels.',
     'channel_link_term_source_type' => 'Term sources must be translation channels.',
+    'term_forbidden' => 'You are not allowed to view or change this term.',
+    'term_exists' => 'A term with the same word and sense (word@tag) already exists here.',
+    'term_word_immutable' => 'The word and sense cannot be changed once created. Create a new term and redirect the old one to it.',
+    'term_if_match_required' => 'Changing a term requires If-Match (the etag from the term details).',
+    'term_modified' => 'Someone else changed this term while you were editing. Reload it and try again.',
+    'term_language_follows_channel' => 'The language of a term in a channel follows the channel and cannot be changed on its own.',
+    'term_redirect_self' => 'A term cannot redirect to itself.',
+    'term_import_word_required' => 'This row has no word. Import only creates or updates terms; delete terms from the list.',
+    'term_import_meaning_required' => 'This row has no meaning.',
+    'term_import_language_required' => 'A studio-wide term (no channel_id) needs a language.',
+    'term_import_channel_not_in_studio' => 'Channel :channel does not exist or does not belong to this studio.',
+    'term_import_not_found' => 'No term with id :id in the scope of this import.',
+    'term_import_modified' => 'Someone changed this term after it was exported. Export again and redo the change.',
+    'term_import_bad_value' => 'Invalid value for :field: :value.',
+    'term_import_unreadable' => 'This file cannot be read. Upload an xlsx spreadsheet.',
+    'term_import_header_required' => 'The first row must hold column names, including at least word and meaning.',
+    'term_import_too_many' => 'At most :max rows can be imported at a time.',
 ];
 ];

+ 17 - 0
api-v13/resources/lang/zh-Hans/messages.php

@@ -72,4 +72,21 @@ return [
     'channel_link_fallback_type' => '降级版本必须与本版本类型相同。',
     'channel_link_fallback_type' => '降级版本必须与本版本类型相同。',
     'channel_link_term_source_channel' => '只有译文(translation)版本才能设置术语路径。',
     'channel_link_term_source_channel' => '只有译文(translation)版本才能设置术语路径。',
     'channel_link_term_source_type' => '术语路径只能选译文(translation)版本。',
     'channel_link_term_source_type' => '术语路径只能选译文(translation)版本。',
+    'term_forbidden' => '你没有权限查看或修改这个术语。',
+    'term_exists' => '这里已经有同一个词与义项(word@tag)的术语了。',
+    'term_word_immutable' => '词与义项建立后不能修改。要改请新建一条术语,再把旧的重定向过去。',
+    'term_if_match_required' => '修改术语要带上 If-Match(取自术语详情的 etag)。',
+    'term_modified' => '这条术语在你编辑期间被别人改过了,请重新加载后再改。',
+    'term_language_follows_channel' => '版本里的术语语言跟随版本,不能单独修改。',
+    'term_redirect_self' => '不能重定向到自己。',
+    'term_import_word_required' => '这一行没有 word。导入只能新建或修改;要删除术语请在列表里删。',
+    'term_import_meaning_required' => '这一行没有 meaning(释义不能为空)。',
+    'term_import_language_required' => 'studio 通用术语(没有 channel_id)要填 language。',
+    'term_import_channel_not_in_studio' => 'channel :channel 不存在,或不属于这个 studio。',
+    'term_import_not_found' => '找不到 id 为 :id 的术语,或它不在这次导入的范围里。',
+    'term_import_modified' => '这条术语在导出之后被别人改过了,请重新导出再改。',
+    'term_import_bad_value' => ':field 的取值「:value」不对。',
+    'term_import_unreadable' => '读不了这个文件,请上传 xlsx 格式的表格。',
+    'term_import_header_required' => '表格第一行要有列名,至少包含 word 与 meaning。',
+    'term_import_too_many' => '一次最多导入 :max 行。',
 ];
 ];

+ 1 - 47
api-v13/resources/views/components/wiki/entry-actions.blade.php

@@ -45,51 +45,5 @@
 </div>
 </div>
 
 
 @push('scripts')
 @push('scripts')
-<script>
-    (function() {
-        const btn = document.getElementById('wikiShareWechat');
-        const modal = document.getElementById('wikiWechatModal');
-        const backdrop = document.getElementById('wikiWechatBackdrop');
-        const closeBtn = document.getElementById('wikiWechatClose');
-        const qrEl = document.getElementById('wikiWechatQr');
-
-        if (!btn || !modal || !qrEl) return;
-
-        function openWechatShare() {
-            const url = encodeURIComponent(window.location.href);
-
-            // 使用更稳定的二维码服务
-            qrEl.innerHTML = `
-            <img
-                src="https://api.qrserver.com/v1/create-qr-code/?size=180x180&data=${url}"
-                width="180"
-                height="180"
-                alt="QR Code"
-            >
-        `;
-
-            modal.style.display = 'flex';
-        }
-
-        function closeWechatShare() {
-            modal.style.display = 'none';
-        }
-
-        btn.addEventListener('click', openWechatShare);
-
-        if (closeBtn) {
-            closeBtn.addEventListener('click', closeWechatShare);
-        }
-
-        if (backdrop) {
-            backdrop.addEventListener('click', closeWechatShare);
-        }
-
-        document.addEventListener('keydown', function(e) {
-            if (e.key === 'Escape') {
-                closeWechatShare();
-            }
-        });
-    })();
-</script>
+@vite('resources/js/modules/wiki-share.js')
 @endpush
 @endpush

+ 1 - 8
api-v13/resources/views/library/wiki/show.blade.php

@@ -29,14 +29,7 @@
         {!! $entry['content'] !!}
         {!! $entry['content'] !!}
     </div>
     </div>
 
 
-    {{-- 标签 --}}
-    <div class="wiki-tags">
-        @foreach ($entry['tags'] as $tag)
-        <a class="wiki-tag" href="{{ route('library.wiki.index',[$lang]) }}?tag={{ $tag }}">
-            {{ $tag }}
-        </a>
-        @endforeach
-    </div>
+    {{-- 分类标签在正文里({{category|…}},可点击),这里不再重复列出 --}}
 
 
     {{-- 其他版本 --}}
     {{-- 其他版本 --}}
     @if(isset($entry['other_versions']) && count($entry['other_versions']) > 0)
     @if(isset($entry['other_versions']) && count($entry['other_versions']) > 0)

+ 1 - 0
api-v13/routes/api.php

@@ -354,6 +354,7 @@ Route::prefix('v3')->as('v3.')->middleware(NegotiateLocale::class)->group(functi
     require __DIR__.'/v3/search.php';
     require __DIR__.'/v3/search.php';
     require __DIR__.'/v3/tipitaka.php';
     require __DIR__.'/v3/tipitaka.php';
     require __DIR__.'/v3/channel.php';
     require __DIR__.'/v3/channel.php';
+    require __DIR__.'/v3/term.php';
     require __DIR__.'/v3/group.php';
     require __DIR__.'/v3/group.php';
     require __DIR__.'/v3/interaction.php';
     require __DIR__.'/v3/interaction.php';
     require __DIR__.'/v3/auth.php';
     require __DIR__.'/v3/auth.php';

+ 47 - 0
api-v13/routes/v3/term.php

@@ -0,0 +1,47 @@
+<?php
+
+/*
+|--------------------------------------------------------------------------
+| v3 · term —— 术语 / 百科词条
+|--------------------------------------------------------------------------
+|
+| 由 routes/api.php 的 v3 组 require 进来,前缀已在那边加好。
+|
+*/
+
+use App\Http\Controllers\V3\ChannelTermController;
+use App\Http\Controllers\V3\ChannelTermImportController;
+use App\Http\Controllers\V3\GlossaryController;
+use App\Http\Controllers\V3\StudioTermController;
+use App\Http\Controllers\V3\StudioTermImportController;
+use App\Http\Controllers\V3\TermController;
+use App\Services\V3\GlossaryService;
+use Illuminate\Support\Facades\Route;
+
+// 读公开(可选登录),写要登录。只注册 PATCH,不注册 PUT
+Route::get('terms', [TermController::class, 'index'])->name('terms.index');
+Route::get('terms/{term}', [TermController::class, 'show'])->name('terms.show')->whereUuid('term');
+Route::patch('terms/{term}', [TermController::class, 'update'])->name('terms.update')
+    ->middleware('auth.v3')->whereUuid('term');
+Route::delete('terms/{term}', [TermController::class, 'destroy'])->name('terms.destroy')
+    ->middleware('auth.v3')->whereUuid('term');
+
+Route::get('channels/{channel}/terms', [ChannelTermController::class, 'index'])->name('channels.terms.index')
+    ->whereUuid('channel');
+Route::post('channels/{channel}/terms', [ChannelTermController::class, 'store'])->name('channels.terms.store')
+    ->middleware('auth.v3')->whereUuid('channel');
+
+Route::get('studios/{studio}/terms', [StudioTermController::class, 'index'])->name('studios.terms.index')
+    ->middleware('auth.v3')->whereUuid('studio');
+Route::post('studios/{studio}/terms', [StudioTermController::class, 'store'])->name('studios.terms.store')
+    ->middleware('auth.v3')->whereUuid('studio');
+
+// 术语词汇表(语法术语 / 社区译名),只读、整表。取代 v2 term-vocabulary
+Route::get('glossaries/{kind}', GlossaryController::class)->name('glossaries.show')
+    ->whereIn('kind', GlossaryService::KINDS);
+
+// 术语导入(xlsx 上传)。导出不另设端点:列表接口带 Accept: xlsx 时直接返回表格
+Route::post('channels/{channel}/terms/imports', ChannelTermImportController::class)->name('channels.terms.imports')
+    ->middleware('auth.v3')->whereUuid('channel');
+Route::post('studios/{studio}/terms/imports', StudioTermImportController::class)->name('studios.terms.imports')
+    ->middleware('auth.v3')->whereUuid('studio');

+ 89 - 0
api-v13/tests/Feature/GlossaryV3Test.php

@@ -0,0 +1,89 @@
+<?php
+
+use App\Models\DhammaTerm;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/*
+ * GET /v3/glossaries/{grammar|community}:系统 channel 里的术语,整表、按词排序。
+ * 这里断言的是形状而非契约(spectator 未安装,见 v3-resource skill 第 3 步)。
+ */
+
+function glossaryTerm(string $channel, string $word, 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,
+        '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;
+}
+
+it('lists the community glossary of a language, sorted by word', function () {
+    $root = config('mint.admin.root_uuid');
+    $zh = makeChannel($root, '_community_term_zh-hans_');
+    $grammar = makeChannel($root, '_System_Grammar_Term_zh-hans_');
+    glossaryTerm($zh, 'sīla', ['tag' => '', 'other_meaning' => '戒律']);
+    glossaryTerm($zh, 'dhamma');
+    glossaryTerm($grammar, 'vibhatti');
+    glossaryTerm($zh, 'deleted')->delete();
+
+    $this->getJson('/api/v3/glossaries/community?lang=zh-Hans')
+        ->assertOk()
+        ->assertJsonPath('meta', ['kind' => 'community', 'lang' => 'zh-Hans', 'total' => 2])
+        ->assertJsonPath('data.*.word', ['dhamma', 'sīla'])
+        ->assertJsonPath('data.1.tag', null)
+        ->assertJsonPath('data.1.other_meaning', '戒律');
+
+    $this->getJson('/api/v3/glossaries/grammar?lang=zh-Hans')->assertJsonPath('data.*.word', ['vibhatti']);
+});
+
+it('falls back to English, and defaults to the negotiated interface language', function () {
+    $root = config('mint.admin.root_uuid');
+    $en = makeChannel($root, '_community_term_en_');
+    $zh = makeChannel($root, '_community_term_zh-hans_');
+    glossaryTerm($en, 'en-word');
+    glossaryTerm($zh, 'zh-word');
+
+    $this->getJson('/api/v3/glossaries/community?lang=my')
+        ->assertJsonPath('meta.lang', 'en')
+        ->assertJsonPath('data.*.word', ['en-word']);
+    $this->getJson('/api/v3/glossaries/community', ['Accept-Language' => 'zh-CN'])
+        ->assertJsonPath('meta.lang', 'zh-Hans')
+        ->assertJsonPath('data.*.word', ['zh-word']);
+});
+
+it('returns an empty list when neither the language nor English has the glossary', function () {
+    $this->getJson('/api/v3/glossaries/grammar?lang=zh-Hans')
+        ->assertOk()
+        ->assertJsonPath('data', [])
+        ->assertJsonPath('meta.total', 0);
+});
+
+it('rejects an unknown kind or a malformed language', function () {
+    $this->getJson('/api/v3/glossaries/other')->assertNotFound();
+    $this->getJson('/api/v3/glossaries/community?lang='.urlencode('../x'))
+        ->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');
+
+    $row = $this->getJson('/api/v3/glossaries/community?lang=zh-Hans')->json('data.0');
+    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);
+});

+ 191 - 0
api-v13/tests/Feature/TermExchangeV3Test.php

@@ -0,0 +1,191 @@
+<?php
+
+use App\Models\AiModel;
+use App\Models\Channel;
+use App\Models\DhammaTerm;
+use App\Models\TermCategory;
+use App\Services\AuthService;
+use App\Services\V3\TermExchangeService;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Http\UploadedFile;
+use PhpOffice\PhpSpreadsheet\IOFactory;
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
+
+uses(RefreshDatabase::class);
+
+/*
+ * 术语导入 / 导出(xlsx):列表接口带 Accept: xlsx 导出;POST …/terms/imports 导入(部分成功)。
+ * 这里断言的是形状而非契约(spectator 未安装,见 v3-resource skill 第 3 步)。
+ */
+
+const XLSX = TermExchangeService::MIME;
+
+/** 生成一个 xlsx 上传文件:第一行是列名 */
+function termSheet(array $header, array $rows): UploadedFile
+{
+    $spreadsheet = new Spreadsheet;
+    $spreadsheet->getActiveSheet()->fromArray([$header, ...$rows], null, 'A1', true);
+    $path = tempnam(sys_get_temp_dir(), 'terms').'.xlsx';
+    (new Xlsx($spreadsheet))->save($path);
+
+    return new UploadedFile($path, 'terms.xlsx', XLSX, null, true);
+}
+
+/** 读回导出的 xlsx:列名 => 值 的行数组 */
+function readSheet(string $content): array
+{
+    $path = tempnam(sys_get_temp_dir(), 'export').'.xlsx';
+    file_put_contents($path, $content);
+    $rows = IOFactory::load($path)->getActiveSheet()->toArray(null, false, false);
+    $header = array_shift($rows);
+
+    return array_map(fn ($row) => array_combine($header, $row), $rows);
+}
+
+function importTo(string $channel, string $as, UploadedFile $file)
+{
+    return test()->post("/api/v3/channels/{$channel}/terms/imports", ['file' => $file], authHeader($as) + ['Accept' => 'application/json']);
+}
+
+function existingTerm(string $channel, string $as, array $body = []): array
+{
+    return test()->postJson("/api/v3/channels/{$channel}/terms", $body + ['word' => 'dhamma', 'meaning' => '法'], authHeader($as))
+        ->assertCreated()->json('data');
+}
+
+/* ------------------------------------------------------------------ 导出 */
+
+it('exports the terms of a channel as xlsx with the filters of the list', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $term = existingTerm($channel, $owner, ['tag' => '义', 'quality' => 'draft', 'note' => '正文 {{category|法义}}']);
+    existingTerm($channel, $owner, ['word' => 'sīla', 'meaning' => '戒']);
+
+    $res = $this->get("/api/v3/channels/{$channel}/terms", ['Accept' => XLSX])->assertOk();
+    expect($res->headers->get('Content-Type'))->toBe(XLSX);
+    $rows = readSheet($res->getContent());
+    expect(array_keys($rows[0]))->toBe(TermExchangeService::COLUMNS)
+        ->and(array_column($rows, 'word'))->toBe(['dhamma', 'sīla'])
+        ->and($rows[0])->toMatchArray(['id' => $term['id'], 'tag' => '义', 'quality' => 'draft', 'etag' => $term['etag'], 'channel_id' => $channel]);
+
+    $filtered = readSheet($this->get("/api/v3/channels/{$channel}/terms?quality=draft", ['Accept' => XLSX])->getContent());
+    expect(array_column($filtered, 'word'))->toBe(['dhamma']);
+
+    Channel::where('uid', $channel)->update(['status' => Channel::STATUS_PRIVATE]);
+    $this->get("/api/v3/channels/{$channel}/terms", ['Accept' => XLSX])->assertForbidden();
+});
+
+it('exports the terms of a studio for its members only', function () {
+    [$team, $users] = makeTeam();
+    existingTerm(makeChannel($team), $users['owner']);
+
+    $rows = readSheet($this->get("/api/v3/studios/{$team}/terms", authHeader($users['reader']) + ['Accept' => XLSX])->assertOk()->getContent());
+    expect(array_column($rows, 'word'))->toBe(['dhamma']);
+    $this->get("/api/v3/studios/{$team}/terms", authHeader($users['outsider']) + ['Accept' => XLSX])->assertForbidden();
+});
+
+/* ------------------------------------------------------------------ 导入 */
+
+it('imports new and changed terms, skipping bad rows with reasons (partial success)', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $existing = existingTerm($channel, $owner, ['tag' => '义']);
+    $untouched = existingTerm($channel, $owner, ['word' => 'sīla', 'meaning' => '戒']);
+
+    $res = importTo($channel, $owner, termSheet(
+        ['id', 'word', 'tag', 'meaning', 'note', 'quality', 'etag'],
+        [
+            [$existing['id'], 'dhamma', '义', '法(改)', '正文 {{category|律学}}', 'standard', $existing['etag']], // 2 改
+            [null, 'kamma', null, '业', null, null, null],                                                          // 3 新建
+            [null, 'sīla', null, '戒', null, null, null],                                                           // 4 无 id 同 word:内容没变
+            [null, null, null, '没有词', null, null, null],                                                          // 5 word 为空
+            [$existing['id'], 'dhammā', '义', 'x', null, null, null],                                                // 6 改 word
+            [null, 'vinaya', null, '律', null, 'great', null],                                                       // 7 quality 不对
+            [null, 'nibbāna', null, null, null, null, null],                                                         // 8 新建缺 meaning
+        ],
+    ))->assertOk();
+
+    expect($res->json('data'))->toMatchArray(['created' => 1, 'updated' => 1, 'unchanged' => 1, 'reindexed' => true])
+        ->and(array_column($res->json('data.errors'), 'row'))->toBe([5, 6, 7, 8]);
+    expect(DhammaTerm::find($existing['id']))->meaning->toBe('法(改)')->quality->toBe('standard')->version->toBe(2);
+    expect(TermCategory::where('term_guid', $existing['id'])->pluck('category')->all())->toBe(['律学']);
+    expect(DhammaTerm::where('channal', $channel)->where('word', 'kamma')->first())
+        ->content_type->toBe('markdown-e2')->language->toBe('zh-Hans');
+    expect(DhammaTerm::find($untouched['id'])->version)->toBe(1);
+});
+
+it('skips rows whose term was changed after export (etag)', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $term = existingTerm($channel, $owner);
+    $this->patchJson("/api/v3/terms/{$term['id']}", ['meaning' => '别人改的'], authHeader($owner) + ['If-Match' => $term['etag']])->assertOk();
+
+    $res = importTo($channel, $owner, termSheet(['id', 'word', 'meaning', 'etag'], [[$term['id'], 'dhamma', '我的', $term['etag']]]));
+    expect($res->json('data.updated'))->toBe(0)->and($res->json('data.errors.0.row'))->toBe(2);
+    expect(DhammaTerm::find($term['id'])->meaning)->toBe('别人改的');
+
+    // 没有 etag 列(手工做的表)照常覆盖
+    importTo($channel, $owner, termSheet(['id', 'word', 'meaning'], [[$term['id'], 'dhamma', '覆盖']]))->assertJsonPath('data.updated', 1);
+});
+
+it('reads a v2 exported sheet by column names', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+
+    importTo($channel, $owner, termSheet(
+        ['id', 'word', 'meaning', 'other_meaning', 'note', 'tag', 'language', 'channel_id'],
+        [[null, 'dhamma', '法', '达摩', '正文', null, 'en', 'ignored']],
+    ))->assertJsonPath('data.created', 1);
+
+    // channel 导入:language / channel_id 列不看,跟随 channel
+    expect(DhammaTerm::where('channal', $channel)->first())->other_meaning->toBe('达摩')->language->toBe('zh-Hans');
+});
+
+it('imports into a studio by channel_id, and needs a language for studio-wide terms', function () {
+    [$team, $users] = makeTeam();
+    $channel = makeChannel($team);
+    $foreign = makeChannel(makeStudio('other'));
+
+    $res = $this->post("/api/v3/studios/{$team}/terms/imports", ['file' => termSheet(
+        ['word', 'meaning', 'language', 'channel_id'],
+        [
+            ['in-channel', '甲', null, $channel],
+            ['general', '乙', 'zh-Hans', null],
+            ['no-language', '丙', null, null],
+            ['foreign', '丁', null, $foreign],
+        ],
+    )], authHeader($users['owner']) + ['Accept' => 'application/json'])->assertOk();
+
+    expect($res->json('data.created'))->toBe(2)->and(array_column($res->json('data.errors'), 'row'))->toBe([4, 5]);
+    expect(DhammaTerm::where('word', 'in-channel')->value('channal'))->toBe($channel);
+    expect(DhammaTerm::where('word', 'general')->first())->channal->toBeNull()->owner->toBe($team);
+
+    // 团队 editor 不能新建 studio 通用术语,但能写 channel 里的
+    $res = $this->post("/api/v3/studios/{$team}/terms/imports", ['file' => termSheet(
+        ['word', 'meaning', 'language', 'channel_id'],
+        [['by-editor', '戊', null, $channel], ['general-by-editor', '己', 'zh-Hans', null]],
+    )], authHeader($users['editor']) + ['Accept' => 'application/json'])->assertOk();
+    expect($res->json('data.created'))->toBe(1)->and($res->json('data.errors.0.row'))->toBe(3);
+});
+
+it('rejects importers without write access, AI models, and unreadable files', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $file = fn () => termSheet(['word', 'meaning'], [['dhamma', '法']]);
+
+    $this->post("/api/v3/channels/{$channel}/terms/imports", ['file' => $file()], ['Accept' => 'application/json'])->assertUnauthorized();
+    importTo($channel, makeStudio('stranger'), $file())->assertForbidden();
+    $model = AiModel::factory()->ownedBy($owner)->create();
+    $this->post("/api/v3/channels/{$channel}/terms/imports", ['file' => $file()], [
+        'Authorization' => 'Bearer '.AuthService::getUserToken($model->uid), 'Accept' => 'application/json',
+    ])->assertForbidden();
+
+    importTo($channel, $owner, UploadedFile::fake()->createWithContent('terms.xlsx', 'not a spreadsheet'))
+        ->assertUnprocessable()->assertJsonValidationErrors('file');
+    importTo($channel, $owner, termSheet(['foo', 'bar'], [['a', 'b']]))
+        ->assertUnprocessable()->assertJsonValidationErrors('file');
+    $this->post("/api/v3/channels/{$channel}/terms/imports", [], authHeader($owner) + ['Accept' => 'application/json'])
+        ->assertUnprocessable()->assertJsonValidationErrors('file');
+    expect(DhammaTerm::count())->toBe(0);
+});

+ 69 - 0
api-v13/tests/Feature/TermIndexServiceTest.php

@@ -0,0 +1,69 @@
+<?php
+
+use App\Models\DhammaTerm;
+use App\Models\TermCategory;
+use App\Services\TermIndexService;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/*
+ * 术语的 OpenSearch 文档用新渲染器构建:内容 = 摘要 + 正文;分类、质量优先取 v3 的列,没有时从正文模板抽。
+ */
+
+function indexTerm(string $channel, array $attrs): DhammaTerm
+{
+    $term = new DhammaTerm;
+    $term->forceFill($attrs + [
+        'id' => random_int(1, PHP_INT_MAX),
+        'guid' => (string) Str::uuid(),
+        'word' => 'dhamma',
+        'word_en' => 'dhamma',
+        'meaning' => '法',
+        'channal' => $channel,
+        'language' => 'zh-Hans',
+        'owner' => 'owner',
+        'editor_id' => 0,
+        'create_time' => time() * 1000,
+        'modify_time' => time() * 1000,
+    ])->save();
+
+    return $term;
+}
+
+it('builds a v3 term document from summary + note with the new renderer and the v3 columns', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner, '译文');
+    $term = indexTerm($channel, [
+        'owner' => $owner,
+        'summary' => '一句话摘要。',
+        'note' => "## 小节\n\n正文**段落**。",
+        'content_type' => 'markdown-e2',
+        'quality' => 'standard',
+    ]);
+    TermCategory::create(['term_guid' => $term->guid, 'category' => '法义', 'position' => 0]);
+
+    $doc = app(TermIndexService::class)->buildDocument($term->guid);
+
+    expect($doc['summary']['text'])->toBe('一句话摘要。');
+    expect($doc['content']['display'])->toContain('一句话摘要。')->toContain('<h2')->toContain('<strong>段落</strong>');
+    expect($doc['content']['text']['zh'])->toContain('正文段落。')->not->toContain('**');
+    expect($doc['tags'])->toBe(['category:法义', 'quality:standard']);
+    expect($doc['path'])->toBe('owner/译文');
+    expect($doc['metadata']['channel'])->toBe($channel);
+});
+
+it('falls back to templates in the note for terms written through v2', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $term = indexTerm($channel, [
+        'owner' => $owner,
+        'note' => "{{quality|draft}}\n第一段。\n\n第二段。{{category|律学}} {{category|学处}}",
+    ]);
+
+    $doc = app(TermIndexService::class)->buildDocument($term->guid);
+
+    expect($doc['tags'])->toBe(['category:律学', 'category:学处', 'quality:draft']);
+    expect($doc['summary']['text'])->not->toBe('')->not->toContain('{{');
+});

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

@@ -0,0 +1,380 @@
+<?php
+
+use App\Models\AiModel;
+use App\Models\Channel;
+use App\Models\DhammaTerm;
+use App\Models\TermCategory;
+use App\Services\AuthService;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/*
+ * v3 术语:/v3/terms、/v3/channels/{c}/terms、/v3/studios/{s}/terms。
+ * 这里断言的是形状而非契约(spectator 未安装,见 v3-resource skill 第 3 步)。
+ */
+
+/** 在 channel 里经 API 建一条术语,返回响应 data */
+function newTerm(string $channel, string $as, array $body = []): array
+{
+    return test()->postJson("/api/v3/channels/{$channel}/terms", $body + [
+        'word' => 'dhamma', 'meaning' => '法', 'note' => "正文第一段。\n\n第二段。{{category|法义}} {{category|基本教义}}",
+    ], authHeader($as))->assertCreated()->json('data');
+}
+
+function termGrant(string $human, AiModel $model, string $channel, int $book = 0): string
+{
+    return test()->postJson('/api/v3/agent-grants', [
+        'ai_model' => $model->uid, 'target_type' => 'channel', 'target_id' => $channel, 'book' => $book,
+    ], authHeader($human))->assertCreated()->json('data.token');
+}
+
+function modelAuth(AiModel $model, ?string $grant = null): array
+{
+    return array_filter([
+        'Authorization' => 'Bearer '.AuthService::getUserToken($model->uid),
+        'X-Agent-Grant' => $grant,
+    ]);
+}
+
+/* ------------------------------------------------------------------ 建 */
+
+it('creates a term in a channel, extracting categories and defaulting to markdown-e2', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+
+    $data = newTerm($channel, $owner, ['tag' => '十七特征', 'quality' => 'draft', 'summary' => '一句话摘要。']);
+
+    expect($data)
+        ->word->toBe('dhamma')
+        ->tag->toBe('十七特征')
+        ->channel_id->toBe($channel)
+        ->owner_id->toBe($owner)
+        ->language->toBe('zh-Hans')
+        ->content_type->toBe('markdown-e2')
+        ->quality->toBe('draft')
+        ->categories->toBe(['法义', '基本教义'])
+        ->summary_text->toBe('一句话摘要。')
+        ->co_editor->toBeNull()
+        ->abilities->toBe(['update' => true, 'delete' => true]);
+    expect($data['editor']['id'])->toBe($owner);
+    expect($data['body'])->toBeArray()->not->toBeEmpty();
+    expect(DhammaTerm::find($data['id']))->version->toBe(1)->editor_id->toBeGreaterThan(0);
+});
+
+it('never exposes the auto-increment id of term_categories', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $term = newTerm($channel, $owner);
+    $ids = TermCategory::where('term_guid', $term['id'])->pluck('id')->all();
+    expect($ids)->toHaveCount(2);
+
+    $responses = [
+        $this->getJson("/api/v3/terms/{$term['id']}")->json('data'),
+        $this->getJson("/api/v3/channels/{$channel}/terms")->json('data.0'),
+        $this->getJson('/api/v3/terms?word=dhamma&with_body=1')->json('data.0'),
+    ];
+    foreach ($responses as $data) {
+        // 分类只以名字出现,没有对象、没有 id
+        expect($data['categories'])->toBe(['法义', '基本教义']);
+        foreach ($ids as $id) {
+            expect(json_encode($data))->not->toMatch('/"id":\s*'.$id.'\b/');
+        }
+    }
+});
+
+it('rejects a duplicate word@tag in the same channel, treating an empty tag as none', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    newTerm($channel, $owner);
+
+    $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'dhamma', 'tag' => '', 'meaning' => '又一个'], authHeader($owner))
+        ->assertStatus(409)
+        ->assertJsonPath('type', fn ($type) => str_contains($type, 'term-exists'));
+    $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'dhamma', 'tag' => '另一义', 'meaning' => '又一个'], authHeader($owner))
+        ->assertCreated();
+});
+
+it('validates term input', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+
+    $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x'], authHeader($owner))
+        ->assertUnprocessable()->assertJsonValidationErrors('meaning');
+    $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x', 'meaning' => 'y', 'tag' => 'a@b'], authHeader($owner))
+        ->assertUnprocessable()->assertJsonValidationErrors('tag');
+    $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x', 'meaning' => 'y', 'quality' => 'great'], authHeader($owner))
+        ->assertUnprocessable()->assertJsonValidationErrors('quality');
+    $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x', 'meaning' => 'y', 'language' => 'en'], authHeader($owner))
+        ->assertUnprocessable()->assertJsonValidationErrors('language');
+    $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x', 'meaning' => 'y', 'redirect' => 'x'], authHeader($owner))
+        ->assertUnprocessable()->assertJsonValidationErrors('redirect');
+    $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x', 'meaning' => 'y'])->assertUnauthorized();
+});
+
+it('lets team editors and above create terms in a team channel', function () {
+    [$team, $users] = makeTeam();
+    $channel = makeChannel($team);
+
+    foreach (['owner', 'manager', 'editor'] as $role) {
+        newTerm($channel, $users[$role], ['word' => "w-{$role}"]);
+    }
+    foreach (['reader', 'outsider'] as $role) {
+        $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x', 'meaning' => 'y'], authHeader($users[$role]))
+            ->assertForbidden();
+    }
+    expect(DhammaTerm::where('channal', $channel)->value('owner'))->toBe($team);
+});
+
+it('creates studio-level terms for owners and managers, and lets editors update them', function () {
+    [$team, $users] = makeTeam();
+    $body = ['word' => 'sīla', 'meaning' => '戒', 'language' => 'zh-Hans'];
+
+    $this->postJson("/api/v3/studios/{$team}/terms", $body, authHeader($users['editor']))->assertForbidden();
+    $created = $this->postJson("/api/v3/studios/{$team}/terms", $body, authHeader($users['manager']))
+        ->assertCreated()
+        ->assertJsonPath('data.channel_id', null)
+        ->json('data');
+
+    $this->patchJson("/api/v3/terms/{$created['id']}", ['meaning' => '戒律'], authHeader($users['editor']) + ['If-Match' => $created['etag']])
+        ->assertOk()->assertJsonPath('data.meaning', '戒律');
+    $this->patchJson("/api/v3/terms/{$created['id']}", ['meaning' => 'x'], authHeader($users['reader']) + ['If-Match' => 'x'])
+        ->assertForbidden();
+});
+
+/* ------------------------------------------------------------------ 读 */
+
+it('shows a term with ETag, and hides terms of private channels', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $term = newTerm($channel, $owner);
+
+    $res = $this->getJson("/api/v3/terms/{$term['id']}")->assertOk();
+    expect($res->headers->get('ETag'))->toBe($term['etag']);
+    expect($res->json('data.abilities'))->toBe(['update' => false, 'delete' => false]);
+    expect($res->json('data.summary_text'))->toBe('正文第一段。');
+
+    Channel::where('uid', $channel)->update(['status' => Channel::STATUS_PRIVATE]);
+    $this->getJson("/api/v3/terms/{$term['id']}")->assertForbidden();
+    $this->getJson("/api/v3/terms/{$term['id']}", authHeader($owner))->assertOk();
+    $this->getJson('/api/v3/terms/'.Str::uuid())->assertNotFound();
+});
+
+it('renders the body against the requested channels, ignoring those the viewer cannot see', function () {
+    $owner = makeStudio('owner');
+    $home = makeChannel($owner, 'home');
+    $other = makeChannel($owner, 'other');
+    $private = makeChannel($owner, 'private');
+    Channel::where('uid', $private)->update(['status' => Channel::STATUS_PRIVATE]);
+    newTerm($home, $owner, ['word' => 'citta', 'meaning' => '本版心']);
+    newTerm($other, $owner, ['word' => 'citta', 'meaning' => '他版心']);
+    newTerm($private, $owner, ['word' => 'citta', 'meaning' => '私有心']);
+    $term = newTerm($home, $owner, ['word' => 'host', 'note' => '见[[citta]]。']);
+    $text = fn (array $res) => json_encode($res['data']['body'], JSON_UNESCAPED_UNICODE);
+
+    expect($text($this->getJson("/api/v3/terms/{$term['id']}")->json()))->toContain('本版心');
+    expect($text($this->getJson("/api/v3/terms/{$term['id']}?channels={$other}")->json()))->toContain('他版心');
+    // 看不见的 channel 被忽略,退回术语所在 channel
+    expect($text($this->getJson("/api/v3/terms/{$term['id']}?channels={$private}")->json()))->toContain('本版心');
+    expect($text($this->getJson("/api/v3/terms/{$term['id']}?channels={$private}", authHeader($owner))->json()))->toContain('私有心');
+
+    $this->getJson("/api/v3/terms/{$term['id']}?mode=edit")->assertOk();
+
+    // format=html:正文换成新渲染器的 HTML 字符串
+    $html = $this->getJson("/api/v3/terms/{$term['id']}?format=html")->assertOk()->json('data');
+    expect($html)->not->toHaveKey('body');
+    expect($html['html'])->toContain('class="term-ref"')->toContain('本版心');
+    $this->getJson("/api/v3/terms/{$term['id']}?format=pdf")->assertUnprocessable()->assertJsonValidationErrors('format');
+    $this->getJson("/api/v3/terms/{$term['id']}?mode=write")->assertUnprocessable()->assertJsonValidationErrors('mode');
+    $this->getJson("/api/v3/terms/{$term['id']}?channels=nope")->assertUnprocessable()->assertJsonValidationErrors('channels');
+});
+
+it('lists the terms of a channel with filters', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    newTerm($channel, $owner, ['word' => 'a', 'quality' => 'featured']);
+    newTerm($channel, $owner, ['word' => 'b', 'note' => '{{category|律学}}']);
+
+    $this->getJson("/api/v3/channels/{$channel}/terms?order=word")
+        ->assertOk()->assertJsonPath('meta.total', 2)->assertJsonPath('data.*.word', ['a', 'b']);
+    $this->getJson("/api/v3/channels/{$channel}/terms?quality=featured")->assertJsonPath('data.*.word', ['a']);
+    $this->getJson("/api/v3/channels/{$channel}/terms?quality=pending")->assertJsonPath('data.*.word', ['b']);
+    $this->getJson("/api/v3/channels/{$channel}/terms?category=".urlencode('律学'))->assertJsonPath('data.*.word', ['b']);
+    $this->getJson("/api/v3/channels/{$channel}/terms?search=A")->assertJsonPath('data.*.word', ['a']);
+    $this->getJson("/api/v3/channels/{$channel}/terms?quality=great")->assertUnprocessable();
+
+    Channel::where('uid', $channel)->update(['status' => Channel::STATUS_PRIVATE]);
+    $this->getJson("/api/v3/channels/{$channel}/terms")->assertForbidden();
+});
+
+it('lists the terms of a studio for its members only', function () {
+    [$team, $users] = makeTeam();
+    newTerm(makeChannel($team), $users['owner'], ['word' => 'in-channel']);
+    $this->postJson("/api/v3/studios/{$team}/terms", ['word' => 'general', 'meaning' => 'g', 'language' => 'zh-Hans'], authHeader($users['owner']))->assertCreated();
+
+    $this->getJson("/api/v3/studios/{$team}/terms?order=word", authHeader($users['reader']))
+        ->assertOk()->assertJsonPath('data.*.word', ['general', 'in-channel']);
+    $this->getJson("/api/v3/studios/{$team}/terms?general=1", authHeader($users['reader']))
+        ->assertJsonPath('data.*.word', ['general']);
+    $this->getJson("/api/v3/studios/{$team}/terms?general=true", authHeader($users['reader']))
+        ->assertJsonPath('data.*.word', ['general']);
+    $this->getJson("/api/v3/studios/{$team}/terms?general=false&order=word", authHeader($users['reader']))
+        ->assertJsonPath('data.*.word', ['general', 'in-channel']);
+    $this->getJson("/api/v3/studios/{$team}/terms", authHeader($users['outsider']))->assertForbidden();
+    $this->getJson("/api/v3/studios/{$team}/terms")->assertUnauthorized();
+});
+
+it('looks terms up by word across visible channels only', function () {
+    $owner = makeStudio('owner');
+    $public = makeChannel($owner, 'public');
+    $private = makeChannel($owner, 'private');
+    Channel::where('uid', $private)->update(['status' => Channel::STATUS_PRIVATE]);
+    newTerm($public, $owner, ['word' => 'citta', 'meaning' => '心']);
+    newTerm($private, $owner, ['word' => 'citta', 'meaning' => '心(私有)']);
+    newTerm($public, $owner, ['word' => 'citta', 'tag' => '十七特征', 'meaning' => '心(特征)']);
+
+    $this->getJson('/api/v3/terms?word=citta')->assertOk()->assertJsonPath('meta.total', 2);
+    $this->getJson('/api/v3/terms?word=citta', authHeader($owner))->assertJsonPath('meta.total', 3);
+    $this->getJson('/api/v3/terms?word=citta&tag='.urlencode('十七特征'))->assertJsonPath('data.*.meaning', ['心(特征)']);
+    $this->getJson('/api/v3/terms?word=citta&tag=')->assertJsonPath('data.*.meaning', ['心']);
+    $this->getJson('/api/v3/terms')->assertUnprocessable()->assertJsonValidationErrors('word');
+
+    // 默认不带正文;with_body 时每条都带,并带上 channel 名字
+    expect($this->getJson('/api/v3/terms?word=citta')->json('data.0'))->not->toHaveKey('body');
+    // 查询串里的 true / false(v6 发的就是它们),不能 422,false 也不能当真
+    expect($this->getJson('/api/v3/terms?word=citta&with_body=false')->assertOk()->json('data.0'))->not->toHaveKey('body');
+    $this->getJson('/api/v3/terms?word=citta&with_body=true')->assertOk()->assertJsonPath('data.0.body', fn ($body) => is_array($body) && $body !== []);
+    $this->getJson('/api/v3/terms?word=citta&with_body=1')
+        ->assertJsonPath('data.0.body', fn ($body) => is_array($body) && $body !== [])
+        ->assertJsonPath('data.0.channel.name', 'public');
+});
+
+it('loads a page of terms with a constant number of queries', function () {
+    $owner = makeStudio('owner');
+    $count = function (int $n) use ($owner) {
+        $channel = makeChannel($owner, "c{$n}");
+        foreach (range(1, $n) as $i) {
+            newTerm($channel, $owner, ['word' => "w{$i}"]);
+        }
+        DB::flushQueryLog();
+        DB::enableQueryLog();
+        $this->getJson("/api/v3/channels/{$channel}/terms", authHeader($owner))->assertOk();
+        $queries = count(DB::getQueryLog());
+        DB::disableQueryLog();
+
+        return $queries;
+    };
+
+    expect($count(8))->toBe($count(2));
+});
+
+/* ------------------------------------------------------------------ 改:乐观锁、word/tag 不可改 */
+
+it('requires If-Match, rejects a stale one, and bumps the version', function () {
+    $owner = makeStudio('owner');
+    $term = newTerm(makeChannel($owner), $owner);
+    $url = "/api/v3/terms/{$term['id']}";
+
+    $this->patchJson($url, ['meaning' => '新释义'], authHeader($owner))->assertStatus(428);
+    $this->patchJson($url, ['meaning' => '新释义'], authHeader($owner) + ['If-Match' => '"9.9"'])
+        ->assertStatus(412)->assertJsonPath('etag', $term['etag']);
+
+    $updated = $this->patchJson($url, ['meaning' => '新释义'], authHeader($owner) + ['If-Match' => $term['etag']])
+        ->assertOk()->assertJsonPath('data.meaning', '新释义')->json('data');
+    expect($updated['etag'])->not->toBe($term['etag']);
+    expect(DhammaTerm::find($term['id'])->version)->toBe(2);
+
+    // 用旧的 etag 再改一次:412
+    $this->patchJson($url, ['meaning' => '再改'], authHeader($owner) + ['If-Match' => $term['etag']])->assertStatus(412);
+});
+
+it('notices changes made through v2, which only touch modify_time', function () {
+    $owner = makeStudio('owner');
+    $term = newTerm(makeChannel($owner), $owner);
+    DhammaTerm::where('guid', $term['id'])->update(['modify_time' => DB::raw('modify_time + 1'), 'meaning' => 'v2 改的']);
+
+    $this->patchJson("/api/v3/terms/{$term['id']}", ['meaning' => 'v3'], authHeader($owner) + ['If-Match' => $term['etag']])
+        ->assertStatus(412);
+});
+
+it('never lets word or tag change, and re-extracts categories when the note changes', function () {
+    $owner = makeStudio('owner');
+    $term = newTerm(makeChannel($owner), $owner);
+    $url = "/api/v3/terms/{$term['id']}";
+
+    $this->patchJson($url, ['word' => 'other'], authHeader($owner) + ['If-Match' => $term['etag']])
+        ->assertUnprocessable()->assertJsonValidationErrors('word');
+    $this->patchJson($url, ['tag' => 'x'], authHeader($owner) + ['If-Match' => $term['etag']])
+        ->assertUnprocessable()->assertJsonValidationErrors('tag');
+
+    $this->patchJson($url, ['note' => '{{category|律学}}', 'redirect' => 'dhamma@新义'], authHeader($owner) + ['If-Match' => $term['etag']])
+        ->assertOk()
+        ->assertJsonPath('data.categories', ['律学'])
+        ->assertJsonPath('data.redirect', 'dhamma@新义');
+    expect(TermCategory::where('term_guid', $term['id'])->pluck('category')->all())->toBe(['律学']);
+});
+
+it('keeps the language of a channel term tied to the channel', function () {
+    $owner = makeStudio('owner');
+    $term = newTerm(makeChannel($owner), $owner);
+
+    $this->patchJson("/api/v3/terms/{$term['id']}", ['language' => 'en'], authHeader($owner) + ['If-Match' => $term['etag']])
+        ->assertUnprocessable()->assertJsonValidationErrors('language');
+});
+
+/* ------------------------------------------------------------------ agent 代写 */
+
+it('records the grantor as editor and the model as co-editor, and clears it when a person edits', function () {
+    $human = makeStudio('owner');
+    $channel = makeChannel($human);
+    $model = AiModel::factory()->ownedBy($human)->create();
+    $grant = termGrant($human, $model, $channel);
+
+    $term = $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'kamma', 'meaning' => '业'], modelAuth($model, $grant))
+        ->assertCreated()
+        ->assertJsonPath('data.editor.id', $human)
+        ->assertJsonPath('data.co_editor.id', $model->uid)
+        ->json('data');
+
+    $edited = $this->patchJson("/api/v3/terms/{$term['id']}", ['meaning' => '业力'], modelAuth($model, $grant) + ['If-Match' => $term['etag']])
+        ->assertOk()->assertJsonPath('data.co_editor.id', $model->uid)->json('data');
+    $this->patchJson("/api/v3/terms/{$term['id']}", ['meaning' => '業'], authHeader($human) + ['If-Match' => $edited['etag']])
+        ->assertOk()->assertJsonPath('data.co_editor', null);
+});
+
+it('rejects agent writes without a covering grant, studio-level agent writes, and agent deletes', function () {
+    $human = makeStudio('owner');
+    $channel = makeChannel($human);
+    $other = makeChannel($human, 'other');
+    $model = AiModel::factory()->ownedBy($human)->create();
+    $body = ['word' => 'kamma', 'meaning' => '业'];
+
+    $this->postJson("/api/v3/channels/{$channel}/terms", $body, modelAuth($model))->assertForbidden();
+    $this->postJson("/api/v3/channels/{$channel}/terms", $body, modelAuth($model, termGrant($human, $model, $other)))->assertForbidden();
+    // 按 book 限定的授权不覆盖术语(术语不属于某本书)
+    $this->postJson("/api/v3/channels/{$channel}/terms", $body, modelAuth($model, termGrant($human, $model, $channel, 3)))->assertForbidden();
+    $this->postJson("/api/v3/studios/{$human}/terms", $body + ['language' => 'zh-Hans'], modelAuth($model, termGrant($human, $model, $channel)))
+        ->assertForbidden();
+
+    $term = newTerm($channel, $human);
+    $this->deleteJson("/api/v3/terms/{$term['id']}", [], modelAuth($model))->assertForbidden();
+});
+
+/* ------------------------------------------------------------------ 删 */
+
+it('soft deletes for the owner or team owner only', function () {
+    [$team, $users] = makeTeam();
+    $term = newTerm(makeChannel($team), $users['editor']);
+    $url = "/api/v3/terms/{$term['id']}";
+
+    $this->deleteJson($url, [], authHeader($users['editor']))->assertForbidden();
+    $this->deleteJson($url, [], authHeader($users['manager']))->assertForbidden();
+    $this->deleteJson($url, [], authHeader($users['owner']))
+        ->assertOk()->assertJsonPath('data.id', $term['id'])
+        ->assertJsonPath('data.deleted_at', fn ($at) => $at !== null);
+
+    $this->assertSoftDeleted('dhamma_terms', ['guid' => $term['id']]);
+    $this->getJson($url)->assertNotFound();
+});

+ 131 - 0
api-v13/tests/Feature/WikiPageTest.php

@@ -0,0 +1,131 @@
+<?php
+
+use App\Models\BookTitle;
+use App\Models\Channel;
+use App\Models\DhammaTerm;
+use App\Models\TermCategory;
+use App\Services\OpenSearchService;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/*
+ * library 百科页(/library/wiki/*)直接查库:分类取 term_categories,质量取 dhamma_terms.quality。
+ * OpenSearch 换成一调用就失败的替身,确保这些页面不再依赖它。
+ */
+
+beforeEach(function () {
+    $this->app->instance(OpenSearchService::class, Mockery::mock(OpenSearchService::class, function ($mock) {
+        $mock->shouldReceive('search', 'get')->never();
+    }));
+});
+
+/** 直接写一条术语(带分类),返回 guid */
+function wikiTerm(string $channel, string $word, array $attrs = [], array $categories = []): string
+{
+    $guid = (string) Str::uuid();
+    (new DhammaTerm)->forceFill($attrs + [
+        'id' => random_int(1, PHP_INT_MAX),
+        'guid' => $guid,
+        'word' => $word,
+        'word_en' => $word,
+        'meaning' => "{$word}-义",
+        'note' => "{$word} 的正文。",
+        'channal' => $channel,
+        'language' => 'zh-Hans',
+        'owner' => Channel::where('uid', $channel)->value('owner_uid'),
+        'editor_id' => 0,
+        'content_type' => 'markdown-e2',
+        'create_time' => time() * 1000,
+        'modify_time' => time() * 1000,
+    ])->save();
+    foreach ($categories as $i => $category) {
+        TermCategory::create(['term_guid' => $guid, 'category' => $category, 'position' => $i]);
+    }
+
+    return $guid;
+}
+
+it('lists the terms of a category and its tags, filtered by quality, public channels only', function () {
+    $owner = makeStudio('owner');
+    $public = makeChannel($owner, 'public');
+    $private = makeChannel($owner, 'private');
+    Channel::where('uid', $private)->update(['status' => Channel::STATUS_PRIVATE]);
+    wikiTerm($public, 'by-sub-label', ['quality' => 'standard'], ['戒条罪类']);
+    wikiTerm($public, 'by-tag', ['quality' => 'draft'], ['学处']);
+    wikiTerm($public, 'pending-one', [], ['学处']);
+    wikiTerm($private, 'zzprivateterm', ['quality' => 'featured'], ['学处']);
+    wikiTerm($public, 'zzothercategory', ['quality' => 'featured'], ['禅修']);
+
+    $html = $this->get('/library/wiki/zh-Hans?category=vinaya&quality=pending')->assertOk()->getContent();
+    expect($html)->toContain('by-sub-label')->toContain('by-tag')->toContain('pending-one')
+        ->not->toContain('zzprivateterm')->not->toContain('zzothercategory');
+
+    $html = $this->get('/library/wiki/zh-Hans?category=vinaya&quality=draft')->assertOk()->getContent();
+    expect($html)->toContain('by-sub-label')->toContain('by-tag')->not->toContain('pending-one');
+});
+
+it('shows a term by word or id with its categories and rendered note', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $guid = wikiTerm($channel, 'dhamma', ['quality' => 'featured', 'summary' => '一句话摘要。', 'note' => "## 小节\n\n正文段落。"], ['法义']);
+    wikiTerm($channel, 'sīla', [], ['法义']);
+
+    foreach (['dhamma', $guid] as $key) {
+        $html = $this->get("/library/wiki/zh-Hans/{$key}")->assertOk()->getContent();
+        expect($html)->toContain('一句话摘要。')->toContain('小节')->toContain('正文段落。')->toContain('法义')
+            ->toContain('sīla'); // 相关条目:共享分类
+    }
+});
+
+it('renders categories in the note as links to the category list, and lists terms by category name', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $guid = wikiTerm($channel, 'vinaya', ['note' => "正文。\n\n{{category|律学}} {{category|学处}}", 'quality' => 'standard'], ['律学', '学处']);
+    wikiTerm($channel, 'zzothercat', ['quality' => 'standard'], ['禅修']);
+
+    $html = $this->get("/library/wiki/zh-Hans/{$guid}")->assertOk()->getContent();
+    $url = e(route('library.wiki.index', ['lang' => 'zh-Hans', 'category' => '学处']));
+    expect($html)->toContain('<a class="tpl-category" href="'.$url.'">学处</a>')
+        ->not->toContain('class="wiki-tags"');
+
+    // 分类名(不是分类树里的 id)也能列出词条
+    $list = $this->get('/library/wiki/zh-Hans?category='.urlencode('学处').'&quality=pending')->assertOk()->getContent();
+    expect($list)->toContain('vinaya')->not->toContain('zzothercat');
+});
+
+it('puts each reference of {{ref}} on its own line', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    // 文献名取自 book_titles:两处引用落在两本书里,各成一条
+    BookTitle::query()->insert([
+        ['book' => 207, 'paragraph' => 1, 'title' => 'kaṅkhāvitaraṇī', 'sn' => 0],
+        ['book' => 200, 'paragraph' => 1, 'title' => 'vinayavinicchayo', 'sn' => 0],
+    ]);
+    $guid = wikiTerm($channel, 'refs', ['note' => "甲。{{para|id=207-1331|title=a 1331|style=reference}}乙。{{para|id=200-9955|title=b 9955|style=reference}}\n\n## 参考文献\n\n{{ref}}"]);
+
+    $html = $this->get("/library/wiki/zh-Hans/{$guid}")->assertOk()->getContent();
+    expect(substr_count($html, 'class="tpl-reference-item"'))->toBe(2)
+        ->and($html)->toContain('</span><br /><span class="tpl-reference-item">');
+});
+
+it('follows a redirect to the target term in the same channel', function () {
+    $owner = makeStudio('owner');
+    $channel = makeChannel($owner);
+    $target = wikiTerm($channel, 'nibbāna', ['tag' => '涅槃']);
+    wikiTerm($channel, 'nirvāṇa', ['redirect' => 'nibbāna@涅槃']);
+
+    $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 () {
+    $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/secret')->assertNotFound();
+    $this->get('/library/wiki/zh-Hans/no-such-word')->assertNotFound();
+});

+ 1 - 0
api-v13/vite.config.ts

@@ -22,6 +22,7 @@ export default defineConfig({
                 'resources/js/reader.js',
                 'resources/js/reader.js',
                 'resources/js/modules/term-tooltip.js',
                 'resources/js/modules/term-tooltip.js',
                 'resources/js/modules/share.js',
                 'resources/js/modules/share.js',
+                'resources/js/modules/wiki-share.js',
             ],
             ],
             refresh: true,
             refresh: true,
         }),
         }),

+ 2 - 1
dashboard-test/src/lib/api.ts

@@ -37,11 +37,12 @@ export async function call(
   path: string,
   path: string,
   data?: object,
   data?: object,
   who: Account = 'user',
   who: Account = 'user',
+  headers: Record<string, string> = {},
 ) {
 ) {
   const res = await request.fetch(`${API}${path}`, {
   const res = await request.fetch(`${API}${path}`, {
     method,
     method,
     data,
     data,
-    headers: { Authorization: `Bearer ${token(who)}`, Accept: 'application/json' },
+    headers: { Authorization: `Bearer ${token(who)}`, Accept: 'application/json', ...headers },
   });
   });
   return { status: res.status(), body: await res.json().catch(() => null) };
   return { status: res.status(), body: await res.json().catch(() => null) };
 }
 }

+ 25 - 0
dashboard-test/src/tests/glossary.spec.ts

@@ -0,0 +1,25 @@
+import { test, expect } from '@playwright/test';
+import { collect } from '../lib/collect.js';
+
+/**
+ * 术语词汇表(v3 /glossaries,取代 v2 term-vocabulary):应用启动时整表拉取语法术语表与社区译名表。
+ */
+test('启动时拉取两张 v3 词汇表,不再请求 v2 term-vocabulary', async ({ page }) => {
+  const log = collect(page);
+  const v2: string[] = [];
+  page.on('request', (r) => r.url().includes('/api/v2/term-vocabulary') && v2.push(r.url()));
+  const grammar = page.waitForResponse((r) => r.url().includes('/api/v3/glossaries/grammar'));
+  const community = page.waitForResponse((r) => r.url().includes('/api/v3/glossaries/community'));
+
+  await page.goto('workspace/channel', { waitUntil: 'networkidle' });
+
+  for (const res of [await grammar, await community]) {
+    expect(res.status()).toBe(200);
+    const body = await res.json();
+    expect(Array.isArray(body.data)).toBe(true);
+    expect(body.meta).toHaveProperty('lang');
+    console.log(`>>> ${new URL(res.url()).pathname}${new URL(res.url()).search}:${body.meta.total} 条(${body.meta.lang})`);
+  }
+  expect(v2).toEqual([]);
+  log.dump('启动加载词汇表');
+});

+ 37 - 0
dashboard-test/src/tests/grammar-pop.spec.ts

@@ -0,0 +1,37 @@
+import { test, expect } from '@playwright/test';
+import { collect } from '../lib/collect.js';
+
+/**
+ * 词典词卡里的语法点悬停说明(GrammarPop,v3,取代 v2 grammar-guide):
+ * 语法术语表里有的词 → /v3/terms/{id};没有的 → 退回按词查 /v3/terms?word=,都找不到显示「暂无…的语法说明」。
+ */
+test('词典词卡的语法点:悬停显示 v3 的语法说明,不再请求 v2 grammar-guide', async ({ page }) => {
+  const log = collect(page);
+  const v2: string[] = [];
+  const v3: string[] = [];
+  page.on('request', (r) => {
+    if (r.url().includes('/api/v2/grammar-guide')) v2.push(r.url());
+    if (/\/api\/v3\/terms(\/|\?)/.test(r.url())) v3.push(decodeURIComponent(new URL(r.url()).pathname + new URL(r.url()).search));
+  });
+
+  // 词典释义正文里嵌的 grammar-pop 模板(如【阳】→ m)渲染成 GrammarPop
+  await page.goto('workspace/dictionary/buddha', { waitUntil: 'networkidle' });
+  const grammarLinks = page.locator('a.ant-typography').filter({ hasText: /^【.+】$/ });
+  await expect(grammarLinks.first()).toBeVisible({ timeout: 15_000 });
+  const count = await grammarLinks.count();
+
+  for (let i = 0; i < Math.min(count, 3); i++) {
+    const link = grammarLinks.nth(i);
+    await link.hover();
+    const popover = page.locator('.ant-popover:visible').last();
+    await expect(popover).toBeVisible();
+    await expect(popover.locator('.ant-skeleton')).toHaveCount(0, { timeout: 10_000 });
+    console.log(`>>> 悬停「${(await link.innerText()).trim()}」→ ${(await popover.innerText()).replace(/\s+/g, " ").trim().slice(0, 60)}`);
+    await page.mouse.move(0, 0);
+    await page.waitForTimeout(300);
+  }
+  console.log('>>> v3 请求:', v3.join(' | '));
+  expect(v2).toEqual([]);
+  expect(v3.length).toBeGreaterThan(0);
+  log.dump('语法点悬停');
+});

+ 13 - 3
dashboard-test/src/tests/teamspace.spec.ts

@@ -77,9 +77,9 @@ test.describe('团队空间切换', () => {
     });
     });
 
 
     await test.step('2. 主导航:可团队化与个人专属的模块置灰,全局模块照常', async () => {
     await test.step('2. 主导航:可团队化与个人专属的模块置灰,全局模块照常', async () => {
-      // channel 已迁 v3,团队空间里可用(看团队名下的与共享给团队的)
+      // channel、术语已迁 v3,团队空间里可用(看团队名下的与共享给团队的)
       await expect(menuItem(page, '版本风格')).not.toHaveClass(/ant-menu-item-disabled/);
       await expect(menuItem(page, '版本风格')).not.toHaveClass(/ant-menu-item-disabled/);
-      await expect(menuItem(page, '术语')).toHaveClass(/ant-menu-item-disabled/);
+      await expect(menuItem(page, '术语')).not.toHaveClass(/ant-menu-item-disabled/);
       await expect(menuItem(page, '最近')).toHaveClass(/ant-menu-item-disabled/);
       await expect(menuItem(page, '最近')).toHaveClass(/ant-menu-item-disabled/);
       await expect(menuItem(page, '主页')).not.toHaveClass(/ant-menu-item-disabled/);
       await expect(menuItem(page, '主页')).not.toHaveClass(/ant-menu-item-disabled/);
       // 我加入的团队列表属于个人身份;管理本团队走「成员管理」
       // 我加入的团队列表属于个人身份;管理本团队走「成员管理」
@@ -118,8 +118,18 @@ test.describe('团队空间切换', () => {
       await expect(badge(page)).toContainText(TEAM);
       await expect(badge(page)).toContainText(TEAM);
     });
     });
 
 
-    await test.step('3. 直接输入地址也进不去(还没迁 v3 的术语)', async () => {
+    await test.step('3a. 已迁 v3 的术语在团队空间可用,列的是团队的术语', async () => {
+      const listed = page.waitForResponse(
+        (r) => r.url().includes(`/api/v3/studios/${teamId}/terms`) && r.request().method() === 'GET',
+      );
       await page.goto('workspace/term', { waitUntil: 'networkidle' });
       await page.goto('workspace/term', { waitUntil: 'networkidle' });
+      expect((await listed).status()).toBe(200);
+      await expect(page.getByTestId('teamspace-blocked')).toHaveCount(0);
+      await shot(page, '03a-term');
+    });
+
+    await test.step('3. 直接输入地址也进不去(还没迁 v3 的文章)', async () => {
+      await page.goto('workspace/article', { waitUntil: 'networkidle' });
       await expect(page.getByTestId('teamspace-blocked')).toContainText('该模块暂不支持团队空间');
       await expect(page.getByTestId('teamspace-blocked')).toContainText('该模块暂不支持团队空间');
       await expect(page.locator('.ant-table')).toHaveCount(0);
       await expect(page.locator('.ant-table')).toHaveCount(0);
       await shot(page, '03-blocked');
       await shot(page, '03-blocked');

+ 189 - 0
dashboard-test/src/tests/term.spec.ts

@@ -0,0 +1,189 @@
+import { test, expect, type Page } from '@playwright/test';
+import { call } from '../lib/api.js';
+import { collect } from '../lib/collect.js';
+import { DESTRUCTIVE, shotDir } from '../lib/env.js';
+
+/**
+ * 术语(v3):channel 详情页的 term 页签——新建、编辑(词头不可改、质量字段)、
+ * 并发修改的 412 提示、删除;以及术语页列表。
+ * 用 e2e-tmp-* 临时 channel,测完软删(术语也是软删)。
+ */
+const SHOT = shotDir('term');
+const shot = (page: Page, name: string) =>
+  page.screenshot({ path: `${SHOT}/${name}.png`, fullPage: true });
+
+const modal = (page: Page) => page.locator('.ant-modal:visible');
+/** channel 详情页有多个页签,各有表格;只看 term 页签 */
+const pane = (page: Page) => page.getByRole('tabpanel', { name: 'term' });
+const field = (page: Page, label: string) =>
+  modal(page).locator('.ant-form-item').filter({ has: page.locator('label', { hasText: new RegExp(`^${label}$`) }) });
+
+const submit = async (page: Page, method: 'POST' | 'PATCH') => {
+  const saved = page.waitForResponse(
+    (r) => /\/api\/v3\/(channels\/[^/]+\/terms|terms\/[^/?]+)$/.test(new URL(r.url()).pathname) && r.request().method() === method,
+  );
+  await modal(page).getByRole('button', { name: /提 *交/ }).click();
+  return saved;
+};
+
+test('channel 的术语:新建、编辑、并发修改提示、删除', async ({ page, request }) => {
+  test.skip(!DESTRUCTIVE, 'E2E_DESTRUCTIVE=0');
+  const log = collect(page);
+  const me = (await call(request, 'GET', '/v3/me')).body.data;
+  const stamp = Date.now();
+  const created = await call(request, 'POST', `/v3/studios/${me.id}/channels`, {
+    name: `e2e-tmp-term-${stamp}`, type: 'translation', lang: 'zh-Hans',
+  });
+  expect(created.status).toBe(201);
+  const channel = created.body.data.id as string;
+  const word = `e2e${stamp}`;
+  let termId = '';
+
+  try {
+    await test.step('1. 打开 channel 的 term 页签,列表为空', async () => {
+      await page.goto(`workspace/channel/${channel}`, { waitUntil: 'networkidle' });
+      const listed = page.waitForResponse((r) => r.url().includes(`/api/v3/channels/${channel}/terms`));
+      await page.getByRole('tab', { name: 'term' }).click();
+      expect((await listed).status()).toBe(200);
+      await expect(pane(page).locator('.ant-table-placeholder')).toBeVisible();
+      log.dump('1. term 页签');
+    });
+
+    await test.step('2. 新建术语(质量:草稿,正文带分类)', async () => {
+      await pane(page).getByRole('button', { name: /新\s*建|创\s*建/ }).first().click();
+      await expect(modal(page)).toBeVisible();
+      await field(page, '词头').locator('input').fill(word);
+      await field(page, '意思').locator('input').fill('测试释义');
+      await field(page, '所属版本').count(); // 版本下拉已预选本版本
+      await field(page, '质量').locator('.ant-select').click();
+      await page.locator('.ant-select-dropdown:visible .ant-select-item-option').filter({ hasText: '草稿' }).click();
+      await field(page, '注解').locator('textarea').fill('第一段。\n\n{{category|e2e分类}}');
+      const res = await submit(page, 'POST');
+      expect(res.status()).toBe(201);
+      const data = (await res.json()).data;
+      termId = data.id;
+      expect(data.channel_id).toBe(channel);
+      expect(data.quality).toBe('draft');
+      expect(data.content_type).toBe('markdown-e2');
+      expect(data.categories).toEqual(['e2e分类']);
+      await expect(pane(page).locator('.ant-table-row').filter({ hasText: word })).toBeVisible();
+      await shot(page, '02-created');
+      log.dump('2. 新建');
+    });
+
+    await test.step('3. 编辑:词头不可改,改释义后保存', async () => {
+      await pane(page).locator('.ant-table-row').filter({ hasText: word }).getByText('编辑').click();
+      await expect(field(page, '词头').locator('input')).toBeDisabled();
+      await expect(field(page, '意思').locator('input')).toHaveValue('测试释义');
+      await field(page, '意思').locator('input').fill('改过的释义');
+      const res = await submit(page, 'PATCH');
+      expect(res.status()).toBe(200);
+      expect(res.request().headers()['if-match']).toBeTruthy();
+      await expect(pane(page).locator('.ant-table-row').filter({ hasText: '改过的释义' })).toBeVisible();
+      await shot(page, '03-edited');
+    });
+
+    await test.step('4. 编辑期间被别人改过:提示 412,不覆盖', async () => {
+      await pane(page).locator('.ant-table-row').filter({ hasText: word }).getByText('编辑').click();
+      await expect(field(page, '意思').locator('input')).toHaveValue('改过的释义');
+      // 别人(这里用同一账号的另一个请求)先改了一次
+      const fresh = (await call(request, 'GET', `/v3/terms/${termId}`)).body.data;
+      const other = await call(request, 'PATCH', `/v3/terms/${termId}`, { meaning: '别人改的' }, 'user', { 'If-Match': fresh.etag });
+      expect(other.status).toBe(200);
+
+      await field(page, '意思').locator('input').fill('我的修改');
+      const res = await submit(page, 'PATCH');
+      expect(res.status()).toBe(412);
+      await expect(page.getByText(/被别人改过/).first()).toBeVisible();
+      expect((await call(request, 'GET', `/v3/terms/${termId}`)).body.data.meaning).toBe('别人改的');
+      await shot(page, '04-conflict');
+      await page.keyboard.press('Escape');
+      await expect(modal(page)).toHaveCount(0);
+    });
+
+    await test.step('4b. 导出 xlsx,再原样导入:全部「未变」', async () => {
+      await page.reload({ waitUntil: 'networkidle' });
+      await page.getByRole('tab', { name: 'term' }).click();
+      await expect(pane(page).locator('.ant-table-row').filter({ hasText: word })).toBeVisible();
+      const download = page.waitForEvent('download');
+      const exported = page.waitForResponse((r) => r.url().includes(`/api/v3/channels/${channel}/terms`) && r.request().headers()['accept']?.includes('spreadsheetml'));
+      await pane(page).getByRole('button', { name: /导\s*出/ }).click();
+      expect((await exported).status()).toBe(200);
+      const file = await (await download).path();
+
+      const imported = page.waitForResponse((r) => r.url().endsWith(`/api/v3/channels/${channel}/terms/imports`));
+      await pane(page).locator('input[type=file]').setInputFiles({ name: 'terms.xlsx', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', buffer: (await import('node:fs')).readFileSync(file) });
+      const res = await imported;
+      expect(res.status()).toBe(200);
+      const data = (await res.json()).data;
+      expect(data).toMatchObject({ created: 0, updated: 0, unchanged: 1, errors: [] });
+      await expect(page.locator('.ant-modal:visible')).toContainText('未变 1 条');
+      await shot(page, '04b-import-result');
+      await page.keyboard.press('Escape');
+      log.dump('4b. 导出导入');
+    });
+
+    await test.step('5. 删除', async () => {
+      await page.reload({ waitUntil: 'networkidle' });
+      await page.getByRole('tab', { name: 'term' }).click();
+      const row = pane(page).locator('.ant-table-row').filter({ hasText: word });
+      await row.locator('.ant-dropdown-trigger').click();
+      await page.locator('.ant-dropdown:visible .ant-dropdown-menu-item').filter({ hasText: '删除' }).click();
+      const deleted = page.waitForResponse((r) => r.url().endsWith(`/api/v3/terms/${termId}`) && r.request().method() === 'DELETE');
+      await page.locator('.ant-modal-confirm .ant-btn-dangerous').click();
+      expect((await deleted).status()).toBe(200);
+      await expect(row).toHaveCount(0);
+      log.dump('5. 删除');
+    });
+  } finally {
+    await call(request, 'DELETE', `/v3/channels/${channel}`);
+  }
+});
+
+test('术语页:列出当前身份名下的术语', async ({ page }) => {
+  const log = collect(page);
+  const listed = page.waitForResponse((r) => /\/api\/v3\/studios\/[^/]+\/terms/.test(r.url()));
+  await page.goto('workspace/term', { waitUntil: 'networkidle' });
+  expect((await listed).status()).toBe(200);
+  await expect(page.locator('.ant-table')).toBeVisible();
+  await shot(page, '06-studio-list');
+  log.dump('6. 术语页');
+});
+
+test('术语详情页:显示摘要与正文(v3 渲染)', async ({ page }) => {
+  const log = collect(page);
+  const id = 'b7ede292-dc78-4138-a13c-3cf1a26cad62';
+  const loaded = page.waitForResponse((r) => r.url().includes(`/api/v3/terms/${id}`));
+  await page.goto(`workspace/term/${id}`, { waitUntil: 'networkidle' });
+  const term = (await (await loaded).json()).data;
+  test.skip(!term?.summary, '开发库里这条术语没有摘要');
+  await expect(page.locator('.pcd_article').first()).toContainText('是律学“十七特征”的第五项');
+  await expect(page.locator('.pcd_article').first()).toContainText('词源与定义');
+  // 质量标签(空按 pending,显示本地化文字)
+  const quality = (term.quality ?? 'pending') as string;
+  const label = { featured: '特色', standard: '标准', draft: '草稿', pending: '待审' }[quality];
+  await expect(page.locator('.ant-tag').filter({ hasText: label })).toBeVisible();
+  await shot(page, '07-term-show');
+  log.dump('7. 术语详情页');
+});
+
+test('术语详情页:点正文里的术语,在当前页打开那条术语', async ({ page }) => {
+  const log = collect(page);
+  const id = 'b7ede292-dc78-4138-a13c-3cf1a26cad62';
+  await page.goto(`workspace/term/${id}`, { waitUntil: 'networkidle' });
+  await expect(page.locator('.pcd_article').first()).toBeVisible();
+  const link = page.locator('.pcd_article .term + a').first();
+  test.skip((await link.count()) === 0, '这条术语的正文里没有术语链接');
+  const text = (await link.innerText()).trim();
+
+  const next = page.waitForResponse((r) => /\/api\/v3\/terms\/[0-9a-f-]{36}\?/.test(r.url()) && !r.url().includes(id));
+  await link.click();
+  const loaded = (await (await next).json()).data;
+  await expect(page).toHaveURL(new RegExp(`/workspace/term/${loaded.id}`));
+  expect(loaded.id).not.toBe(id);
+  // 标题换成新术语的释义(新术语可能没有正文,不能拿正文判断)
+  await expect(page.getByRole('heading', { name: loaded.meaning, level: 4 }).first()).toBeVisible();
+  console.log(`>>> 点「${text}」→ ${loaded.word}(${loaded.meaning})`);
+  await shot(page, '08-term-navigate');
+  log.dump('8. 点术语跳转');
+});

+ 0 - 5
dashboard-v6/src/api/Guide.ts

@@ -1,5 +0,0 @@
-export interface IGuideResponse {
-  ok: boolean;
-  message: string;
-  data: string;
-}

+ 191 - 93
dashboard-v6/src/api/Term.ts

@@ -1,7 +1,191 @@
 import type { IStudio, IUser, TRole } from "./Auth";
 import type { IStudio, IUser, TRole } from "./Auth";
 import type { IChannel } from "./channel";
 import type { IChannel } from "./channel";
-import { get } from "../request";
 import type { LoaderFunctionArgs } from "react-router";
 import type { LoaderFunctionArgs } from "react-router";
+import { api, unwrap, unwrapQuiet } from "./client";
+import type { paths } from "./schema";
+
+/* ─── v3(术语本身已迁 v3,取代 v2 terms 的 show / view=channel|studio|word / store / update / destroy)───
+ * 词汇表已迁到 v3(`api/glossary.ts`),导入导出也已迁到 v3(见本文件下方)。
+ */
+
+type TermSingle =
+  paths["/v3/terms/{term}"]["get"]["responses"][200]["content"]["application/json"];
+
+/** v3 的一条术语:带 abilities、etag(修改时放进 If-Match) */
+export type Term = NonNullable<TermSingle["data"]>;
+export type TermLookupQuery = NonNullable<
+  paths["/v3/terms"]["get"]["parameters"]["query"]
+>;
+export type TermListQuery = NonNullable<
+  paths["/v3/channels/{channel}/terms"]["get"]["parameters"]["query"]
+>;
+export type StudioTermListQuery = NonNullable<
+  paths["/v3/studios/{studio}/terms"]["get"]["parameters"]["query"]
+>;
+export type NewChannelTermInput =
+  paths["/v3/channels/{channel}/terms"]["post"]["requestBody"]["content"]["application/json"];
+export type NewStudioTermInput =
+  paths["/v3/studios/{studio}/terms"]["post"]["requestBody"]["content"]["application/json"];
+export type TermPatch = NonNullable<
+  paths["/v3/terms/{term}"]["patch"]["requestBody"]
+>["content"]["application/json"];
+
+/** 词条质量 */
+export const TERM_QUALITIES = [
+  "featured",
+  "standard",
+  "draft",
+  "pending",
+] as const;
+/** 正文方言:markdown 是旧方言,v3 新建默认 markdown-e2 */
+export const TERM_CONTENT_TYPES = ["markdown-e2", "markdown"] as const;
+
+export type TermShowQuery = NonNullable<
+  paths["/v3/terms/{term}"]["get"]["parameters"]["query"]
+>;
+
+/**
+ * 单条,带渲染后的「摘要 + 正文」(body)。query 可指定按哪些 channel 渲染、read / edit 模式。
+ * quiet=true 时失败不弹提示(悬停浮层这类轻量调用用),只抛出。
+ */
+export const fetchTerm = async (
+  term: string,
+  query: TermShowQuery = {},
+  quiet = false,
+) =>
+  (quiet ? unwrapQuiet : unwrap)(
+    await api.GET("/v3/terms/{term}", { params: { path: { term }, query } }),
+  ).data;
+
+/** 按词查(只列看得见的);with_body 时每条都带渲染后的正文。quiet=true 时失败不弹提示 */
+export const lookupTerms = async (query: TermLookupQuery, quiet = false) =>
+  (quiet ? unwrapQuiet : unwrap)(
+    await api.GET("/v3/terms", { params: { query } }),
+  );
+
+export const fetchChannelTerms = async (
+  channel: string,
+  query: TermListQuery = {},
+) =>
+  unwrap(
+    await api.GET("/v3/channels/{channel}/terms", {
+      params: { path: { channel }, query },
+    }),
+  );
+
+export const fetchStudioTerms = async (
+  studio: string,
+  query: StudioTermListQuery = {},
+) =>
+  unwrap(
+    await api.GET("/v3/studios/{studio}/terms", {
+      params: { path: { studio }, query },
+    }),
+  );
+
+export const createChannelTerm = async (
+  channel: string,
+  body: NewChannelTermInput,
+) =>
+  unwrap(
+    await api.POST("/v3/channels/{channel}/terms", {
+      params: { path: { channel } },
+      body,
+    }),
+  ).data;
+
+export const createStudioTerm = async (
+  studio: string,
+  body: NewStudioTermInput,
+) =>
+  unwrap(
+    await api.POST("/v3/studios/{studio}/terms", {
+      params: { path: { studio } },
+      body,
+    }),
+  ).data;
+
+/**
+ * 改术语。etag 取自读到的那一份(`term.etag`):这条在你编辑期间被别人改过时返回 412,
+ * unwrap 会弹出后端的提示并抛出,调用方不要静默重试(那会覆盖别人的修改)。
+ */
+export const updateTerm = async (term: string, etag: string, body: TermPatch) =>
+  unwrap(
+    await api.PATCH("/v3/terms/{term}", {
+      params: { path: { term } },
+      headers: { "If-Match": etag },
+      body,
+    }),
+  ).data;
+
+/** 软删除,返回被删的术语 */
+export const deleteTerm = async (term: string) =>
+  unwrap(await api.DELETE("/v3/terms/{term}", { params: { path: { term } } }))
+    .data;
+
+/* ─── 导入 / 导出(xlsx,取代 v2 terms-import / terms-export)─── */
+
+export const TERM_XLSX =
+  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
+
+/** 导入到哪里:某个 channel,或某个 studio(用户或团队的 uuid) */
+export type TermExchangeTarget = { channelId: string } | { studioId: string };
+
+type TermImportResponse =
+  paths["/v3/channels/{channel}/terms/imports"]["post"]["responses"][200]["content"]["application/json"];
+export type TermImportResult = NonNullable<TermImportResponse["data"]>;
+
+/** 导出成 xlsx:列表接口带 Accept: xlsx,整表返回(过滤同列表) */
+export const exportTerms = async (
+  target: TermExchangeTarget,
+): Promise<Blob> => {
+  const options = {
+    headers: { Accept: TERM_XLSX },
+    parseAs: "blob" as const,
+  };
+  const result =
+    "channelId" in target
+      ? await api.GET("/v3/channels/{channel}/terms", {
+          params: { path: { channel: target.channelId } },
+          ...options,
+        })
+      : await api.GET("/v3/studios/{studio}/terms", {
+          params: { path: { studio: target.studioId } },
+          ...options,
+        });
+  return unwrap(result) as unknown as Blob;
+};
+
+/**
+ * 导入 xlsx。部分成功:出错的行跳过,`errors` 逐行给出原因(`row` 是表格行号)。
+ */
+export const importTerms = async (
+  target: TermExchangeTarget,
+  file: File,
+): Promise<TermImportResult | undefined> => {
+  const options = {
+    // 规格里文件是 binary 字符串;实际以 FormData 上传
+    body: { file: file as unknown as string },
+    bodySerializer: (body: { file: string }) => {
+      const form = new FormData();
+      form.append("file", body.file as unknown as Blob);
+      return form;
+    },
+  };
+  const result =
+    "channelId" in target
+      ? await api.POST("/v3/channels/{channel}/terms/imports", {
+          params: { path: { channel: target.channelId } },
+          ...options,
+        })
+      : await api.POST("/v3/studios/{studio}/terms/imports", {
+          params: { path: { studio: target.studioId } },
+          ...options,
+        });
+  return unwrap(result).data;
+};
+
+/* ─── v2(仍在用的部分,见上方说明)─── */
 
 
 export interface ITerm {
 export interface ITerm {
   id?: string;
   id?: string;
@@ -22,24 +206,6 @@ export interface ITerm {
   pr?: boolean;
   pr?: boolean;
 }
 }
 
 
-export interface ITermDataRequest {
-  id?: string;
-  word: string;
-  tag?: string;
-  meaning: string;
-  other_meaning?: string;
-  note?: string;
-  channel?: string;
-  studioName?: string;
-  studioId?: string;
-  language?: string;
-  parent_channel_id?: string;
-  save_as?: boolean;
-  copy_channel?: string;
-  copy_lang?: string;
-  pr?: boolean;
-}
-
 export interface ITermDataResponse {
 export interface ITermDataResponse {
   id: number;
   id: number;
   guid: string;
   guid: string;
@@ -63,86 +229,18 @@ export interface ITermDataResponse {
   updated_at: string;
   updated_at: string;
 }
 }
 
 
-export interface ITermResponse {
-  ok: boolean;
-  message: string;
-  data: ITermDataResponse;
-}
-
-export interface ITermListResponse {
-  ok: boolean;
-  message: string;
-  data: {
-    rows: ITermDataResponse[];
-    count: number;
-  };
-}
-
-interface IMeaningCount {
-  meaning: string;
-  count: number;
-}
-
-interface IStudioChannel {
-  name: string;
-  uid: string;
-}
-
-export interface ITermCreate {
-  word: string;
-  meaningCount: IMeaningCount[];
-  studioChannels: IStudioChannel[];
-  language: string;
-  studio: IStudio;
-}
-
-export interface ITermCreateResponse {
-  ok: boolean;
-  message: string;
-  data: ITermCreate;
-}
-
-export interface ITermDeleteRequest {
-  uuid: boolean;
-  id: string[];
-}
-
-// ---------- API ----------
-
-export interface IGetTermParams {
-  id: string;
-  mode?: "read" | "edit";
-  channelsId?: string | null;
-}
-
-export function getTerm({
-  id,
-  mode,
-  channelsId,
-}: IGetTermParams): Promise<ITermResponse> {
-  let url = `/api/v2/terms/${id}?a=a`;
-  if (mode) {
-    url += `&mode=${mode}`;
-  }
-  if (channelsId) {
-    url += `&channel=${channelsId}`;
-  }
-
-  return get<ITermResponse>(url);
-}
-
+/** 路由 loader:面包屑只要 word */
 export async function termLoader({ params }: LoaderFunctionArgs) {
 export async function termLoader({ params }: LoaderFunctionArgs) {
   const termId = params.id;
   const termId = params.id;
 
 
   if (!termId) {
   if (!termId) {
     throw new Response("Missing termId", { status: 400 });
     throw new Response("Missing termId", { status: 400 });
   }
   }
-
-  const res = await getTerm({ id: termId });
-
-  if (!res.ok) {
+  try {
+    return unwrapQuiet(
+      await api.GET("/v3/terms/{term}", { params: { path: { term: termId } } }),
+    ).data;
+  } catch {
     throw new Response("term not found", { status: 404 });
     throw new Response("term not found", { status: 404 });
   }
   }
-
-  return res.data;
 }
 }

+ 34 - 0
dashboard-v6/src/api/glossary.ts

@@ -0,0 +1,34 @@
+// src/api/glossary.ts
+import { api, unwrapQuiet } from "./client";
+import type { paths } from "./schema";
+import type { ITerm } from "../reducers/term-vocabulary";
+
+/* ─── v3 术语词汇表(取代 v2 term-vocabulary):语法术语表 / 社区译名表,整表拉取后本地查 ─── */
+
+type GlossaryList =
+  paths["/v3/glossaries/{kind}"]["get"]["responses"][200]["content"]["application/json"];
+export type GlossaryEntry = NonNullable<GlossaryList["data"]>[number];
+export type GlossaryKind =
+  paths["/v3/glossaries/{kind}"]["get"]["parameters"]["path"]["kind"];
+
+/**
+ * 取一张词汇表,转成 store(reducers/term-vocabulary)里的条目形状。
+ * 启动时调用,失败不弹提示(unwrapQuiet),由调用方决定怎么处理。
+ */
+export const fetchGlossary = async (
+  kind: GlossaryKind,
+  lang?: string,
+): Promise<ITerm[]> => {
+  const json = unwrapQuiet(
+    await api.GET("/v3/glossaries/{kind}", {
+      params: { path: { kind }, query: { lang } },
+    }),
+  );
+  return (json.data ?? []).map((item: GlossaryEntry) => ({
+    guid: item.id,
+    word: item.word ?? "",
+    tag: item.tag ?? undefined,
+    meaning: item.meaning ?? "",
+    other_meaning: item.other_meaning ?? undefined,
+  }));
+};

Plik diff jest za duży
+ 736 - 167
dashboard-v6/src/api/schema.d.ts


+ 48 - 8
dashboard-v6/src/components/article/TypeTerm.tsx

@@ -2,7 +2,10 @@ import { Breadcrumb, Button, Space } from "antd";
 import { useIntl } from "react-intl";
 import { useIntl } from "react-intl";
 import { EditOutlined, ShareAltOutlined } from "@ant-design/icons";
 import { EditOutlined, ShareAltOutlined } from "@ant-design/icons";
 import type { ArticleMode } from "../../api/article";
 import type { ArticleMode } from "../../api/article";
+import { useEffect, useState } from "react";
 import { useAppSelector } from "../../hooks";
 import { useAppSelector } from "../../hooks";
+import store from "../../store";
+import { click, clickedTerm } from "../../reducers/term-click";
 import { currentUser } from "../../reducers/current-user";
 import { currentUser } from "../../reducers/current-user";
 
 
 import "./article.css";
 import "./article.css";
@@ -10,6 +13,10 @@ import ArticleHeader from "./components/ArticleHeader";
 import ArticleLayout from "./components/ArticleLayout";
 import ArticleLayout from "./components/ArticleLayout";
 import { useTerm } from "./hooks/useTerm";
 import { useTerm } from "./hooks/useTerm";
 import TermShare from "../term/TermShare";
 import TermShare from "../term/TermShare";
+import { QualityCtl } from "../template/Quality";
+import MarkupView from "../markup/MarkupView";
+import type { MarkupNode } from "../markup/types";
+import type { IUser } from "../../api/Auth";
 
 
 interface IWidget {
 interface IWidget {
   id?: string;
   id?: string;
@@ -17,6 +24,8 @@ interface IWidget {
   channelId?: string | null;
   channelId?: string | null;
   headerExtra?: React.ReactNode;
   headerExtra?: React.ReactNode;
   onEdit?: () => void;
   onEdit?: () => void;
+  /** 点了正文里的某个术语(TermCtl 经 term-click 广播) */
+  onTermClick?: (id: string) => void;
 }
 }
 
 
 const TypeTermWidget = ({
 const TypeTermWidget = ({
@@ -25,15 +34,27 @@ const TypeTermWidget = ({
   mode = "read",
   mode = "read",
   headerExtra,
   headerExtra,
   onEdit,
   onEdit,
+  onTermClick,
 }: IWidget) => {
 }: IWidget) => {
-  const { articleData, term, errorCode, loading } = useTerm({
+  const { term, errorCode, loading } = useTerm({
     id,
     id,
     channelId,
     channelId,
     mode,
     mode,
   });
   });
   const currUser = useAppSelector(currentUser);
   const currUser = useAppSelector(currentUser);
+  const termClicked = useAppSelector(clickedTerm);
+  // 进页面前别处留下、没人接收的点击不算,只响应之后的
+  const [staleClick] = useState(termClicked);
   const intl = useIntl();
   const intl = useIntl();
 
 
+  useEffect(() => {
+    if (!onTermClick || !termClicked?.id || termClicked === staleClick) {
+      return;
+    }
+    store.dispatch(click(null));
+    onTermClick(termClicked.id);
+  }, [termClicked, staleClick, onTermClick]);
+
   const path = [
   const path = [
     { title: currUser?.nickName },
     { title: currUser?.nickName },
     { title: term?.channel?.name ?? "通用" },
     { title: term?.channel?.name ?? "通用" },
@@ -69,13 +90,32 @@ const TypeTermWidget = ({
         }
         }
       />
       />
       <ArticleLayout
       <ArticleLayout
-        title={articleData?.title}
-        subTitle={articleData?.subtitle}
-        content={articleData?.content ?? ""}
-        html={[articleData?.html ?? ""]}
-        editor={articleData?.editor}
-        created_at={articleData?.created_at}
-        updated_at={articleData?.updated_at}
+        title={term?.meaning}
+        subTitle={term?.word}
+        preTitle={
+          term ? (
+            <Space>
+              {/* 质量为空按 pending 显示 */}
+              <QualityCtl
+                value={term.quality ?? "pending"}
+                label={intl.formatMessage({
+                  id: `term.fields.quality.${term.quality ?? "pending"}`,
+                })}
+              />
+            </Space>
+          ) : undefined
+        }
+        html={[]}
+        nodes={[
+          <MarkupView
+            key="body"
+            className="pcd_article"
+            nodes={term?.body as MarkupNode[] | undefined}
+          />,
+        ]}
+        editor={(term?.editor ?? undefined) as IUser | undefined}
+        created_at={term?.created_at}
+        updated_at={term?.updated_at}
         loading={loading}
         loading={loading}
         errorCode={errorCode}
         errorCode={errorCode}
       />
       />

+ 4 - 0
dashboard-v6/src/components/article/components/ArticleLayout.tsx

@@ -18,6 +18,8 @@ export interface IFirstAnthology {
   count: number;
   count: number;
 }
 }
 export interface IArticleLayout {
 export interface IArticleLayout {
+  /** 显示在标题上方(如术语的质量标签) */
+  preTitle?: ReactNode;
   title?: string;
   title?: string;
   subTitle?: string;
   subTitle?: string;
   summary?: string | null;
   summary?: string | null;
@@ -39,6 +41,7 @@ export interface IArticleLayout {
 }
 }
 
 
 const ArticleLayout = ({
 const ArticleLayout = ({
+  preTitle,
   title = "",
   title = "",
   subTitle,
   subTitle,
   summary,
   summary,
@@ -70,6 +73,7 @@ const ArticleLayout = ({
             orientation="vertical"
             orientation="vertical"
             gap="middle"
             gap="middle"
           >
           >
+            {preTitle}
             {!hideTitle && (
             {!hideTitle && (
               <Title level={4}>
               <Title level={4}>
                 <div
                 <div

+ 14 - 36
dashboard-v6/src/components/article/hooks/useTerm.ts

@@ -1,18 +1,22 @@
 import { useEffect, useState, useTransition } from "react";
 import { useEffect, useState, useTransition } from "react";
 
 
-import type { ArticleMode, IArticleDataResponse } from "../../../api/article";
-import { getTerm, type ITermDataResponse } from "../../../api/Term";
-import { message } from "antd";
+import type { ArticleMode } from "../../../api/article";
+import { fetchTerm, type Term } from "../../../api/Term";
+import { ApiError } from "../../../api/error";
 
 
 interface IUseTermOptions {
 interface IUseTermOptions {
   id?: string;
   id?: string;
   mode?: ArticleMode | null;
   mode?: ArticleMode | null;
+  /** 正文按哪些 channel 渲染,多个用下划线分隔(右栏「版本」面板的选择) */
   channelId?: string | null;
   channelId?: string | null;
 }
 }
 
 
+/**
+ * 阅读器里的术语(v3):`body` 是渲染后的「摘要 + 正文」节点树(新渲染器)。
+ * 指定的 channel 后端只认你看得见的;编辑 / 逐词模式按 edit 渲染。
+ */
 export function useTerm({ id, mode = "read", channelId }: IUseTermOptions) {
 export function useTerm({ id, mode = "read", channelId }: IUseTermOptions) {
-  const [articleData, setArticleData] = useState<IArticleDataResponse>();
-  const [term, setTerm] = useState<ITermDataResponse>();
+  const [term, setTerm] = useState<Term>();
   const [errorCode, setErrorCode] = useState<number>();
   const [errorCode, setErrorCode] = useState<number>();
   const [isPending, startTransition] = useTransition();
   const [isPending, startTransition] = useTransition();
 
 
@@ -20,43 +24,17 @@ export function useTerm({ id, mode = "read", channelId }: IUseTermOptions) {
     if (typeof id === "undefined") return;
     if (typeof id === "undefined") return;
 
 
     const queryMode = mode === "edit" || mode === "wbw" ? "edit" : "read";
     const queryMode = mode === "edit" || mode === "wbw" ? "edit" : "read";
+    const channels = channelId ? channelId.split("_").join(",") : undefined;
 
 
     startTransition(async () => {
     startTransition(async () => {
       try {
       try {
-        const json = await getTerm({
-          id: id,
-          mode: queryMode,
-          channelsId: channelId,
-        });
-
-        if (!json.ok) {
-          message.error(json.message);
-          return;
-        }
-
-        const { data } = json;
-
-        setArticleData({
-          uid: data.guid,
-          title: data.meaning,
-          subtitle: data.word,
-          summary: data.note,
-          content: data.note ?? "",
-          content_type: "markdown",
-          html: data.html ?? data.note ?? "<span />",
-          editor: data.editor,
-          status: 30,
-          lang: data.language,
-          created_at: data.created_at,
-          updated_at: data.updated_at,
-        });
-
-        setTerm(data);
+        setErrorCode(undefined);
+        setTerm(await fetchTerm(id, { mode: queryMode, channels }));
       } catch (e) {
       } catch (e) {
-        setErrorCode(e as number);
+        setErrorCode(e instanceof ApiError ? e.status : 500);
       }
       }
     });
     });
   }, [id, channelId, mode]);
   }, [id, channelId, mode]);
 
 
-  return { articleData, term, errorCode, loading: isPending };
+  return { term, errorCode, loading: isPending };
 }
 }

+ 79 - 27
dashboard-v6/src/components/dict/GrammarPop.tsx

@@ -1,51 +1,103 @@
 import { useState } from "react";
 import { useState } from "react";
-import { Popover, Typography } from "antd";
+import { Popover, Skeleton, Typography } from "antd";
+import { useIntl } from "react-intl";
 
 
-import { get } from "../../request";
 import { get as getLang } from "../../locales";
 import { get as getLang } from "../../locales";
-import type { IGuideResponse } from "../../api/Guide";
-import Marked from "../general/Marked";
+import { fetchTerm, lookupTerms, type Term } from "../../api/Term";
+import { useAppSelector } from "../../hooks";
+import { getGrammar } from "../../reducers/term-vocabulary";
+import MarkupView from "../markup/MarkupView";
+import type { MarkupNode } from "../markup/types";
 
 
-const { Link, Paragraph } = Typography;
+const { Link, Paragraph, Title } = Typography;
+
+/** 语法术语所在的系统 channel 名:_System_Grammar_Term_{语言}_ */
+const GRAMMAR_CHANNEL = "_System_Grammar_Term_";
+
+/** 本次会话内的缓存:词_语言 → 术语(找不到记 null) */
+const cache = new Map<string, Term | null>();
+
+/**
+ * 按词找语法术语(v3,取代 v2 grammar-guide):
+ * 1. 启动时已加载的语法术语表(/v3/glossaries/grammar)里按词找到 id,取 /v3/terms/{id}
+ * 2. 表里没有(还没加载完,或表里本就没有)就按词查 /v3/terms?word=,只认语法术语系统 channel 的,
+ *    界面语言的优先、其次英文(与 v2 一样回退到英文)
+ */
+const findGrammarTerm = async (
+  word: string,
+  grammarIds: Map<string, string>,
+): Promise<Term | null> => {
+  const id = grammarIds.get(word);
+  if (id) {
+    return (await fetchTerm(id, {}, true)) ?? null;
+  }
+  const lang = getLang().toLowerCase();
+  const rows =
+    (await lookupTerms({ word, with_body: true, per_page: 50 }, true)).data ??
+    [];
+  const inChannel = (suffix: string) =>
+    rows.find((row) => row.channel?.name === `${GRAMMAR_CHANNEL}${suffix}_`);
+  return inChannel(lang) ?? inChannel("en") ?? null;
+};
 
 
 interface IWidget {
 interface IWidget {
   text: string;
   text: string;
   gid: string;
   gid: string;
 }
 }
 const GrammarPopWidget = ({ text, gid }: IWidget) => {
 const GrammarPopWidget = ({ text, gid }: IWidget) => {
-  const [guide, setGuide] = useState("Loading");
-  const grammarPrefix = "guide-grammar-";
-  const handleMouseMouseEnter = () => {
-    //sessionStorage缓存
-    const value = sessionStorage.getItem(grammarPrefix + gid);
-    if (value === null) {
-      fetchData(gid);
-    } else {
-      const sGuide: string = value ? value : "";
-      setGuide(sGuide);
+  const intl = useIntl();
+  const grammar = useAppSelector(getGrammar);
+  const cacheKey = `${gid}_${getLang()}`;
+  const [term, setTerm] = useState<Term | null | undefined>(
+    cache.get(cacheKey),
+  );
+
+  const handleMouseEnter = () => {
+    if (cache.has(cacheKey)) {
+      setTerm(cache.get(cacheKey));
+      return;
     }
     }
+    const ids = new Map(
+      (grammar ?? [])
+        .filter((item) => item.guid)
+        .map((item) => [item.word, item.guid as string]),
+    );
+    findGrammarTerm(gid, ids)
+      .then((found) => {
+        cache.set(cacheKey, found);
+        setTerm(found);
+      })
+      // 悬停是轻量操作:查询失败不弹全局提示(已用 quiet 调用),浮层里显示「暂无说明」
+      .catch(() => setTerm(null));
   };
   };
 
 
-  function fetchData(key: string) {
-    const uiLang = getLang();
-    const url = `/api/v2/grammar-guide/${key}_${uiLang}`;
-    get<IGuideResponse>(url).then((json) => {
-      if (json.ok) {
-        sessionStorage.setItem(grammarPrefix + key, json.data);
-        setGuide(json.data);
-      }
-    });
-  }
   return (
   return (
     <Popover
     <Popover
       content={
       content={
         <Paragraph style={{ maxWidth: 500, minWidth: 300, margin: 0 }}>
         <Paragraph style={{ maxWidth: 500, minWidth: 300, margin: 0 }}>
-          <Marked text={guide} />
+          {term === undefined ? (
+            <Skeleton active title={false} paragraph={{ rows: 2 }} />
+          ) : term === null ? (
+            <Typography.Text type="secondary">
+              {intl.formatMessage(
+                { id: "term.grammar.not_found" },
+                { word: gid },
+              )}
+            </Typography.Text>
+          ) : (
+            <>
+              <Title level={5}>{term.meaning}</Title>
+              <MarkupView
+                className="pcd_article"
+                nodes={term.body as MarkupNode[] | undefined}
+              />
+            </>
+          )}
         </Paragraph>
         </Paragraph>
       }
       }
       placement="bottom"
       placement="bottom"
     >
     >
-      <Link onMouseEnter={handleMouseMouseEnter}>{text}</Link>
+      <Link onMouseEnter={handleMouseEnter}>{text}</Link>
     </Popover>
     </Popover>
   );
   );
 };
 };

+ 2 - 1
dashboard-v6/src/components/markup/MarkupTemplate.tsx

@@ -62,7 +62,8 @@ const TEMPLATES: Record<string, TemplateRenderer> = {
   para: (p) => <ParaCtl {...as<typeof ParaCtl>(p)} />,
   para: (p) => <ParaCtl {...as<typeof ParaCtl>(p)} />,
   quality: (p) => <QualityCtl {...as<typeof QualityCtl>(p)} />,
   quality: (p) => <QualityCtl {...as<typeof QualityCtl>(p)} />,
   article: (p) => <ArticleCtl {...as<typeof ArticleCtl>(p)} />,
   article: (p) => <ArticleCtl {...as<typeof ArticleCtl>(p)} />,
-  category: (p) => <Tag>{p.name as string}</Tag>,
+  // antd 6 的 Tag 默认是无边框的浅灰填充,在灰底页面上看不出是标签,给个颜色
+  category: (p) => <Tag color="blue">{p.name as string}</Tag>,
   toggle: (_, children) => <ToggleCtl>{children}</ToggleCtl>,
   toggle: (_, children) => <ToggleCtl>{children}</ToggleCtl>,
   // 目录:自带一行标题(不是正文的一节),children 是链到各标题的嵌套列表
   // 目录:自带一行标题(不是正文的一节),children 是链到各标题的嵌套列表
   toc: (p, children) => (
   toc: (p, children) => (

+ 4 - 2
dashboard-v6/src/components/template/Quality.tsx

@@ -16,15 +16,17 @@ const QUALITY_COLORS: Record<string, string> = {
 
 
 interface IQualityCtl {
 interface IQualityCtl {
   value?: string;
   value?: string;
+  /** 显示的文字,默认显示取值本身 */
+  label?: string;
 }
 }
 
 
 /**
 /**
  * 渲染单个质量标签
  * 渲染单个质量标签
  * 非法取值回退为默认的 pending,保证样式始终可预期
  * 非法取值回退为默认的 pending,保证样式始终可预期
  */
  */
-export const QualityCtl = ({ value = "pending" }: IQualityCtl) => {
+export const QualityCtl = ({ value = "pending", label }: IQualityCtl) => {
   const color = QUALITY_COLORS[value] ?? QUALITY_COLORS.pending;
   const color = QUALITY_COLORS[value] ?? QUALITY_COLORS.pending;
-  return <Tag color={color}>{value}</Tag>;
+  return <Tag color={color}>{label ?? value}</Tag>;
 };
 };
 
 
 interface IWidget {
 interface IWidget {

+ 8 - 18
dashboard-v6/src/components/term/TermCommunity.tsx

@@ -10,9 +10,7 @@ import {
 import { DownOutlined } from "@ant-design/icons";
 import { DownOutlined } from "@ant-design/icons";
 import { useState, useEffect } from "react";
 import { useState, useEffect } from "react";
 import { useIntl } from "react-intl";
 import { useIntl } from "react-intl";
-import { get } from "../../request";
-
-import type { ITermListResponse } from "../../api/Term";
+import { lookupTerms } from "../../api/Term";
 import { Link } from "react-router";
 import { Link } from "react-router";
 import type { IUser } from "../../api/Auth";
 import type { IUser } from "../../api/Auth";
 
 
@@ -41,24 +39,16 @@ const TermCommunityWidget = ({ word }: IWidget) => {
     if (typeof word === "undefined") {
     if (typeof word === "undefined") {
       return;
       return;
     }
     }
-    const url = `/api/v2/terms?view=word&word=${word}&exp=1`;
-    console.log("url", url);
-    get<ITermListResponse>(url)
+    // v3 没有 v2 的 exp(编辑者经验值):每条按同样的分数计
+    lookupTerms({ word, per_page: 200 })
       .then((json) => {
       .then((json) => {
-        if (json.ok === false) {
-          return;
-        }
         const meaning = new Map<string, number>();
         const meaning = new Map<string, number>();
         const note = new Map<string, number>();
         const note = new Map<string, number>();
         const editorId = new Map<string, number>();
         const editorId = new Map<string, number>();
         const editor = new Map<string, IUser>();
         const editor = new Map<string, IUser>();
-        for (const it of json.data.rows) {
+        for (const it of json.data ?? []) {
           let score: number | undefined;
           let score: number | undefined;
-          let currScore = 100;
-          if (it.exp) {
-            //分数计算
-            currScore = Math.floor(it.exp / 3600);
-          }
+          const currScore = 100;
           if (it.meaning) {
           if (it.meaning) {
             score = meaning.get(it.meaning);
             score = meaning.get(it.meaning);
             meaning.set(it.meaning, score ? score + currScore : currScore);
             meaning.set(it.meaning, score ? score + currScore : currScore);
@@ -70,10 +60,10 @@ const TermCommunityWidget = ({ word }: IWidget) => {
             note.set(it.note, score ? score + noteScore : noteScore);
             note.set(it.note, score ? score + noteScore : noteScore);
           }
           }
 
 
-          if (it.editor) {
+          if (it.editor?.id) {
             score = editorId.get(it.editor.id);
             score = editorId.get(it.editor.id);
             editorId.set(it.editor.id, score ? score + currScore : currScore);
             editorId.set(it.editor.id, score ? score + currScore : currScore);
-            editor.set(it.editor.id, it.editor);
+            editor.set(it.editor.id, it.editor as IUser);
           }
           }
         }
         }
         const _data: IWord = {
         const _data: IWord = {
@@ -124,7 +114,7 @@ const TermCommunityWidget = ({ word }: IWidget) => {
   };
   };
 
 
   const meaningLow = wordData?.meaning.filter(
   const meaningLow = wordData?.meaning.filter(
-    (value, index: number) => !isShow(value.score, index)
+    (value, index: number) => !isShow(value.score, index),
   );
   );
   const meaningExtra = meaningLow?.map((item, id) => {
   const meaningExtra = meaningLow?.map((item, id) => {
     return <span key={id}>{item.value}</span>;
     return <span key={id}>{item.value}</span>;

+ 24 - 34
dashboard-v6/src/components/term/TermCtl.tsx

@@ -7,7 +7,7 @@ import { SearchOutlined, EditOutlined } from "@ant-design/icons";
 import store from "../../store";
 import store from "../../store";
 import TermModal from "../term/TermModal";
 import TermModal from "../term/TermModal";
 
 
-import type { ITerm, ITermDataResponse, ITermResponse } from "../../api/Term";
+import { fetchTerm, type ITerm, type Term } from "../../api/Term";
 import {
 import {
   changedTerm,
   changedTerm,
   refresh,
   refresh,
@@ -15,7 +15,6 @@ import {
   upgrade,
   upgrade,
 } from "../../reducers/term-change";
 } from "../../reducers/term-change";
 import { useAppSelector } from "../../hooks";
 import { useAppSelector } from "../../hooks";
-import { get } from "../../request";
 import { fullUrl } from "../../utils";
 import { fullUrl } from "../../utils";
 import lodash from "lodash";
 import lodash from "lodash";
 import { order, push } from "../../reducers/term-order";
 import { order, push } from "../../reducers/term-order";
@@ -23,16 +22,15 @@ import { click } from "../../reducers/term-click";
 
 
 const { Text, Title } = Typography;
 const { Text, Title } = Typography;
 
 
-const dataMap = (input?: ITermDataResponse): ITerm => {
+const dataMap = (input?: Term): ITerm => {
   return {
   return {
-    id: input?.guid,
+    id: input?.id,
     word: input?.word,
     word: input?.word,
     meaning: input?.meaning,
     meaning: input?.meaning,
-    meaning2: input?.other_meaning?.split(","),
-    summary: input?.summary ?? "",
-    channelId: input?.channal,
-    studioId: input?.studio.id,
-    summary_is_community: input?.summary_is_community,
+    meaning2: input?.other_meaning ? input.other_meaning.split(",") : undefined,
+    summary: input?.summary_text ?? "",
+    channelId: input?.channel_id ?? undefined,
+    studioId: input?.owner_id,
   };
   };
 };
 };
 
 
@@ -58,7 +56,7 @@ interface ITermState {
 }
 }
 
 
 type TermAction =
 type TermAction =
-  | { type: "UPDATE_TERM"; payload: ITermDataResponse }
+  | { type: "UPDATE_TERM"; payload: Term }
   | { type: "SET_TERM_DATA"; payload: ITerm };
   | { type: "SET_TERM_DATA"; payload: ITerm };
 
 
 function termReducer(state: ITermState, action: TermAction): ITermState {
 function termReducer(state: ITermState, action: TermAction): ITermState {
@@ -122,11 +120,11 @@ export const TermCtl = ({
 
 
   const [loading, setLoading] = useState(false);
   const [loading, setLoading] = useState(false);
 
 
-  const newTerm: ITermDataResponse | undefined = useAppSelector(changedTerm);
+  const newTerm: Term | undefined = useAppSelector(changedTerm);
   const cache = useAppSelector(termCache);
   const cache = useAppSelector(termCache);
 
 
   const [uid] = useState<string>(
   const [uid] = useState<string>(
-    lodash.times(20, () => lodash.random(35).toString(36)).join("")
+    lodash.times(20, () => lodash.random(35).toString(36)).join(""),
   );
   );
   const termOrder = useAppSelector(order);
   const termOrder = useAppSelector(order);
 
 
@@ -137,7 +135,7 @@ export const TermCtl = ({
       (value) =>
       (value) =>
         value.word === word &&
         value.word === word &&
         value.channelId === parentChannelId &&
         value.channelId === parentChannelId &&
-        value.first === uid
+        value.first === uid,
     );
     );
     return index !== -1;
     return index !== -1;
   }, [termOrder, word, parentChannelId, uid]);
   }, [termOrder, word, parentChannelId, uid]);
@@ -153,10 +151,10 @@ export const TermCtl = ({
     if (
     if (
       newTerm && // 收窄掉 undefined
       newTerm && // 收窄掉 undefined
       newTerm.word === word &&
       newTerm.word === word &&
-      parentStudioId === newTerm.studio.id
+      parentStudioId === newTerm.owner_id
     ) {
     ) {
       console.debug("Term studio 匹配", newTerm);
       console.debug("Term studio 匹配", newTerm);
-      dispatch({ type: "UPDATE_TERM", payload: newTerm }); // 此时 newTerm: ITermDataResponse ✅
+      dispatch({ type: "UPDATE_TERM", payload: newTerm });
     }
     }
   }, [newTerm, parentStudioId, word]);
   }, [newTerm, parentStudioId, word]);
 
 
@@ -169,20 +167,17 @@ export const TermCtl = ({
   const onPopoverOpen = (visible: boolean) => {
   const onPopoverOpen = (visible: boolean) => {
     setOpenPopover(visible);
     setOpenPopover(visible);
     if (visible && isInit && typeof id !== "undefined") {
     if (visible && isInit && typeof id !== "undefined") {
-      const term = cache?.find((value) => value.guid === id);
+      const term = cache?.find((value) => value.id === id);
       if (term) {
       if (term) {
-        // term 已收窄为 ITermDataResponse,非 undefined ✅
         dispatch({ type: "SET_TERM_DATA", payload: dataMap(term) });
         dispatch({ type: "SET_TERM_DATA", payload: dataMap(term) });
         return;
         return;
       } else {
       } else {
-        const url = `/api/v2/terms/${id}?community_summary=1`;
-        console.info("api request", url);
         setLoading(true);
         setLoading(true);
-        get<ITermResponse>(url)
-          .then((json) => {
-            if (json.ok) {
-              dispatch({ type: "UPDATE_TERM", payload: json.data });
-              store.dispatch(upgrade(json.data));
+        fetchTerm(id)
+          .then((data) => {
+            if (data) {
+              dispatch({ type: "UPDATE_TERM", payload: data });
+              store.dispatch(upgrade(data));
             }
             }
           })
           })
           .finally(() => setLoading(false));
           .finally(() => setLoading(false));
@@ -206,7 +201,7 @@ export const TermCtl = ({
                   onClick={() => {
                   onClick={() => {
                     window.open(
                     window.open(
                       fullUrl(`/term/list/${termData.word}`),
                       fullUrl(`/term/list/${termData.word}`),
-                      "_blank"
+                      "_blank",
                     );
                     );
                   }}
                   }}
                   type="link"
                   type="link"
@@ -214,9 +209,9 @@ export const TermCtl = ({
                   icon={<SearchOutlined />}
                   icon={<SearchOutlined />}
                 />
                 />
                 <TermModal
                 <TermModal
-                  onUpdate={(value: ITermDataResponse) => {
+                  onUpdate={(value: Term) => {
                     onModalClose();
                     onModalClose();
-                    sessionStorage.removeItem(`term/summary/${value.guid}`);
+                    sessionStorage.removeItem(`term/summary/${value.id}`);
                     store.dispatch(refresh(value));
                     store.dispatch(refresh(value));
                   }}
                   }}
                   onClose={() => {
                   onClose={() => {
@@ -258,12 +253,7 @@ export const TermCtl = ({
                   active
                   active
                 />
                 />
               ) : (
               ) : (
-                <>
-                  <div>{termData.summary}</div>
-                  <div style={{ textAlign: "right" }}>
-                    {termData.summary_is_community ? "社区解释" : ""}
-                  </div>
-                </>
+                <div>{termData.summary}</div>
               )}
               )}
             </div>
             </div>
           }
           }
@@ -290,7 +280,7 @@ export const TermCtl = ({
   } else {
   } else {
     return (
     return (
       <TermModal
       <TermModal
-        onUpdate={(value: ITermDataResponse) => {
+        onUpdate={(value: Term) => {
           onModalClose();
           onModalClose();
           store.dispatch(refresh(value));
           store.dispatch(refresh(value));
         }}
         }}

+ 266 - 251
dashboard-v6/src/components/term/TermEdit.tsx

@@ -11,20 +11,24 @@ import {
 
 
 import LangSelect from "../general/LangSelect";
 import LangSelect from "../general/LangSelect";
 import ChannelSelect from "../channel/ChannelSelect";
 import ChannelSelect from "../channel/ChannelSelect";
-import { Alert, App, AutoComplete, Button, Form, Space, Tag } from "antd";
+import { Alert, App, AutoComplete, Form, Space, Tag } from "antd";
 import { useEffect, useRef, useState } from "react";
 import { useEffect, useRef, useState } from "react";
-import type {
-  ITerm,
-  ITermCreateResponse,
-  ITermDataRequest,
-  ITermDataResponse,
-  ITermListResponse,
-  ITermResponse,
+import {
+  createChannelTerm,
+  createStudioTerm,
+  fetchTerm,
+  lookupTerms,
+  TERM_CONTENT_TYPES,
+  TERM_QUALITIES,
+  updateTerm,
+  type Term,
+  type TermPatch,
 } from "../../api/Term";
 } from "../../api/Term";
-import { get, post, put } from "../../request";
+import { fetchChannel } from "../../api/channel";
 import MDEditor from "@uiw/react-md-editor";
 import MDEditor from "@uiw/react-md-editor";
 import { useAppSelector } from "../../hooks";
 import { useAppSelector } from "../../hooks";
 import { currentUser as _currentUser } from "../../reducers/current-user";
 import { currentUser as _currentUser } from "../../reducers/current-user";
+import { useActiveStudio } from "../../hooks/useActiveStudio";
 import store from "../../store";
 import store from "../../store";
 import { push } from "../../reducers/term-vocabulary";
 import { push } from "../../reducers/term-vocabulary";
 
 
@@ -34,23 +38,53 @@ interface ValueType {
   value: string | number;
   value: string | number;
 }
 }
 
 
+/** 表单字段 */
+interface IFormValues {
+  id?: string;
+  word?: string;
+  tag?: string;
+  meaning?: string;
+  meaning2?: string[];
+  note?: string;
+  summary?: string;
+  quality?: string | null;
+  content_type?: string;
+  redirect?: string;
+  channelId?: string;
+  lang?: string;
+  save_as?: boolean;
+  copy_channel?: string[];
+  copy_lang?: string;
+  pr?: boolean;
+}
+
 interface IWidget {
 interface IWidget {
   id?: string;
   id?: string;
   word?: string;
   word?: string;
   tags?: string[];
   tags?: string[];
+  /** TermModal 用来显示「在 Studio 中打开」,本组件不用 */
   studioName?: string;
   studioName?: string;
   channelId?: string;
   channelId?: string;
   parentChannelId?: string;
   parentChannelId?: string;
   parentStudioId?: string;
   parentStudioId?: string;
   community?: boolean;
   community?: boolean;
-  onUpdate?: (data: ITermDataResponse) => void;
+  onUpdate?: (data: Term) => void;
 }
 }
+
+/**
+ * 术语编辑 / 新建(v3)。
+ *
+ * - 编辑:读到的 `etag` 随修改一起提交(If-Match)。这条在编辑期间被别人改过时后端返回 412,
+ *   unwrap 弹出提示;不自动重试,避免覆盖别人的修改
+ * - 词头与标签建立后不能改(引用方写 `[[word@tag]]`);要改就新建一条,把旧的重定向过去
+ * - 新建:选了版本就建在版本里(语言跟版本),选「通用于此 studio」就建 studio 级术语(要选语言)
+ * - 分类写在正文的 `{{category|…}}` 里,由后端抽取
+ */
 const TermEditWidget = ({
 const TermEditWidget = ({
   id,
   id,
   word,
   word,
   tags,
   tags,
   channelId,
   channelId,
-  studioName,
   parentChannelId,
   parentChannelId,
   parentStudioId,
   parentStudioId,
   community = false,
   community = false,
@@ -61,56 +95,62 @@ const TermEditWidget = ({
   const [readonly, setReadonly] = useState(false);
   const [readonly, setReadonly] = useState(false);
   const [isSaveAs, setIsSaveAs] = useState(false);
   const [isSaveAs, setIsSaveAs] = useState(false);
   const [currChannel, setCurrChannel] = useState<ValueType[]>([]);
   const [currChannel, setCurrChannel] = useState<ValueType[]>([]);
+  const [etag, setEtag] = useState<string>();
+  const [isGeneral, setIsGeneral] = useState(false);
   const user = useAppSelector(_currentUser);
   const user = useAppSelector(_currentUser);
+  const { studioId: activeStudioId } = useActiveStudio();
   const { message } = App.useApp();
   const { message } = App.useApp();
 
 
-  const [form] = Form.useForm<ITerm>();
+  const [form] = Form.useForm<IFormValues>();
   const formRef = useRef<ProFormInstance | undefined>(undefined);
   const formRef = useRef<ProFormInstance | undefined>(undefined);
+  const isEdit = typeof id !== "undefined" && !community;
+  const label = (key: string) => intl.formatMessage({ id: key });
+
   useEffect(() => {
   useEffect(() => {
-    if (word) {
-      const url = `/api/v2/terms?view=word&word=${word}`;
-      console.info("api request", url);
-      get<ITermListResponse>(url).then((json) => {
-        const meaning = json.data.rows.map((item) => item.meaning);
-        const meaningMap = new Map<string, number>();
-        for (const it of meaning) {
-          const count = meaningMap.get(it);
-          if (typeof count === "undefined") {
-            meaningMap.set(it, 1);
-          } else {
-            meaningMap.set(it, count + 1);
-          }
+    if (!word) {
+      return;
+    }
+    // 同词在各版本里的释义,按出现次数给出候选
+    lookupTerms({ word, per_page: 200 }).then((json) => {
+      const meaningMap = new Map<string, number>();
+      for (const item of json.data ?? []) {
+        if (item.meaning) {
+          meaningMap.set(item.meaning, (meaningMap.get(item.meaning) ?? 0) + 1);
         }
         }
-        const meaningList: ValueType[] = [];
-        meaningMap.forEach((value, key) => {
-          meaningList.push({
-            value: key,
-            label: (
-              <Space
-                style={{ display: "flex", justifyContent: "space-between" }}
-              >
-                {key}
-                <Tag>{value}</Tag>
-              </Space>
-            ),
-          });
+      }
+      const meaningList: ValueType[] = [];
+      meaningMap.forEach((value, key) => {
+        meaningList.push({
+          value: key,
+          label: (
+            <Space style={{ display: "flex", justifyContent: "space-between" }}>
+              {key}
+              <Tag>{value}</Tag>
+            </Space>
+          ),
         });
         });
-
-        setMeaningOptions(meaningList);
       });
       });
-    }
+      setMeaningOptions(meaningList);
+    });
   }, [word]);
   }, [word]);
 
 
-  let channelDisable = false;
-  if (community) {
-    channelDisable = true;
-  }
-  if (readonly) {
-    channelDisable = true;
-  }
-  if (id) {
-    channelDisable = true;
-  }
+  const channelDisable = community || readonly || typeof id !== "undefined";
+
+  /** 新建:建在版本里,或建成 studio 级术语 */
+  const create = async (
+    target: string,
+    language: string | undefined,
+    body: TermPatch & { word: string; tag?: string | null; meaning: string },
+  ): Promise<Term | undefined> => {
+    if (target) {
+      return createChannelTerm(target, body);
+    }
+    const studio = parentStudioId ?? activeStudioId ?? user?.id;
+    if (!studio) {
+      return undefined;
+    }
+    return createStudioTerm(studio, { ...body, language: language ?? "" });
+  };
 
 
   return (
   return (
     <>
     <>
@@ -119,184 +159,149 @@ const TermEditWidget = ({
           title="该资源为社区数据,您可以修改并保存到一个您有修改权限的版本中。"
           title="该资源为社区数据,您可以修改并保存到一个您有修改权限的版本中。"
           type="info"
           type="info"
           closable
           closable
-          action={
-            <Button disabled size="small" type="text">
-              详情
-            </Button>
-          }
         />
         />
       ) : readonly ? (
       ) : readonly ? (
         <Alert
         <Alert
           title="该资源为只读,如果需要修改,请联络拥有者分配权限。或者您可以在下面的版本选择中选择另一个版本,将该术语保存到一个您有修改权限的版本中。"
           title="该资源为只读,如果需要修改,请联络拥有者分配权限。或者您可以在下面的版本选择中选择另一个版本,将该术语保存到一个您有修改权限的版本中。"
           type="warning"
           type="warning"
           closable
           closable
-          action={
-            <Button disabled size="small" type="text">
-              详情
-            </Button>
-          }
         />
         />
       ) : undefined}
       ) : undefined}
-      <ProForm<ITerm>
+      <ProForm<IFormValues>
         form={form}
         form={form}
         formRef={formRef}
         formRef={formRef}
         autoFocusFirstInput={true}
         autoFocusFirstInput={true}
-        onFinish={async (values: ITerm) => {
-          console.log("term submit", values);
-          if (
-            typeof values.word === "undefined" ||
-            typeof values.meaning === "undefined"
-          ) {
+        onFinish={async (values: IFormValues) => {
+          if (!values.word || !values.meaning) {
             return;
             return;
           }
           }
-          let copy_channel = "";
-          if (values.copy_channel && values.copy_channel.length > 0) {
-            copy_channel = values.copy_channel[values.copy_channel.length - 1];
-          }
-          const newValue = {
-            id: values.id,
-            word: values.word,
-            tag: values.tag,
+          const content: TermPatch = {
             meaning: values.meaning,
             meaning: values.meaning,
-            other_meaning: values.meaning2?.join(),
-            note: values.note,
-            channel: values.save_as ? copy_channel : values.channelId,
-            parent_channel_id: parentChannelId,
-            studioName: studioName,
-            studioId: parentStudioId,
-            language: values.save_as ? values.copy_lang : values.lang,
-            pr: values.save_as ? values.pr : undefined,
+            other_meaning: values.meaning2?.join() || null,
+            note: values.note || null,
+            summary: values.summary || null,
+            quality: (values.quality || null) as TermPatch["quality"],
+            content_type: values.content_type as TermPatch["content_type"],
+            redirect: values.redirect || null,
           };
           };
-          console.log("value", newValue);
-          let res: ITermResponse;
-          if (typeof values.id === "undefined" || community || values.save_as) {
-            const url = `/api/v2/terms?community_summary=1`;
-            console.info("api request", url, newValue);
-            res = await post<ITermDataRequest, ITermResponse>(url, newValue);
-          } else {
-            const url = `/api/v2/terms/${values.id}?community_summary=1`;
-            console.info("api request", url, newValue);
-            res = await put<ITermDataRequest, ITermResponse>(url, newValue);
-          }
-          console.debug("api response", res);
 
 
-          if (res.ok) {
-            message.success("提交成功");
-            store.dispatch(
-              push({ word: res.data.word, meaning: res.data.meaning })
+          let saved: Term | undefined;
+          if (isEdit && !values.save_as && id) {
+            if (!etag) {
+              return;
+            }
+            saved = await updateTerm(
+              id,
+              etag,
+              isGeneral && values.lang
+                ? { ...content, language: values.lang }
+                : content,
             );
             );
-            onUpdate?.(res.data);
           } else {
           } else {
-            message.error(res.message);
+            const target = values.save_as
+              ? (values.copy_channel?.[values.copy_channel.length - 1] ?? "")
+              : (values.channelId ?? "");
+            saved = await create(
+              target,
+              values.save_as ? values.copy_lang : values.lang,
+              {
+                ...content,
+                meaning: values.meaning,
+                word: values.word,
+                tag: values.tag || null,
+              },
+            );
           }
           }
-
+          if (!saved) {
+            return;
+          }
+          message.success("提交成功");
+          setEtag(saved.etag);
+          store.dispatch(
+            push({ word: saved.word ?? "", meaning: saved.meaning ?? "" }),
+          );
+          onUpdate?.(saved);
           return true;
           return true;
         }}
         }}
         request={async () => {
         request={async () => {
-          let url: string;
-          let data: ITerm = {
+          let data: IFormValues = {
             word: word ? word : "",
             word: word ? word : "",
             tag: tags?.join(),
             tag: tags?.join(),
             meaning: "",
             meaning: "",
             meaning2: [],
             meaning2: [],
             note: "",
             note: "",
+            summary: "",
+            quality: null,
+            content_type: TERM_CONTENT_TYPES[0],
+            redirect: "",
             lang: "",
             lang: "",
             copy_channel: [],
             copy_channel: [],
           };
           };
           if (typeof id !== "undefined") {
           if (typeof id !== "undefined") {
-            // 如果是编辑,就从服务器拉取数据。
-            url = "/api/v2/terms/" + id;
-            console.info("TermEdit is edit api request", url);
-            const res = await get<ITermResponse>(url);
-            console.debug("TermEdit is edit api response", res);
-            if (res.ok) {
-              let meaning2: string[] = [];
-              if (res.data.other_meaning) {
-                meaning2 = res.data.other_meaning.split(",");
-              }
-
-              let realChannelId: string | undefined = "";
-              if (parentStudioId) {
-                if (user?.id === parentStudioId) {
-                  if (community) {
-                    realChannelId = "";
-                  } else {
-                    realChannelId = res.data.channel?.id;
-                  }
-                } else {
-                  realChannelId = parentChannelId;
-                }
-              } else {
-                if (res.data.channel) {
-                  realChannelId = res.data.channel?.id;
-                  setCurrChannel([
-                    {
-                      label: res.data.channel?.name,
-                      value: res.data.channel?.id,
-                    },
-                  ]);
-                }
-              }
-              let copyToChannel: string[] = [];
-              if (parentChannelId) {
-                if (user?.roles?.includes("basic")) {
-                  copyToChannel = [parentChannelId];
-                } else {
-                  copyToChannel = [""];
-                }
-              }
-
-              data = {
-                id: res.data.guid,
-                word: res.data.word,
-                tag: res.data.tag,
-                meaning: res.data.meaning,
-                meaning2: meaning2,
-                note: res.data.note ? res.data.note : "",
-                lang: res.data.language,
-                channelId: realChannelId,
-                copy_channel: copyToChannel,
-              };
-              if (res.data.role === "reader" || res.data.role === "unknown") {
-                setReadonly(true);
-              }
+            // 编辑:从服务器拉取
+            const term = await fetchTerm(id);
+            if (!term) {
+              return data;
+            }
+            setEtag(term.etag);
+            setIsGeneral(!term.channel_id);
+            if (term.channel) {
+              setCurrChannel([
+                { label: term.channel.name, value: term.channel.id ?? "" },
+              ]);
+            }
+            let copyToChannel: string[] = [];
+            if (parentChannelId) {
+              copyToChannel = user?.roles?.includes("basic")
+                ? [parentChannelId]
+                : [""];
+            }
+            data = {
+              id: community ? undefined : term.id,
+              word: term.word,
+              tag: term.tag ?? undefined,
+              meaning: term.meaning,
+              meaning2: term.other_meaning ? term.other_meaning.split(",") : [],
+              note: term.note ?? "",
+              summary: term.summary ?? "",
+              quality: term.quality ?? null,
+              content_type: term.content_type,
+              redirect: term.redirect ?? "",
+              lang: term.language,
+              channelId: community
+                ? (parentChannelId ?? "")
+                : (term.channel_id ?? ""),
+              copy_channel: copyToChannel,
+            };
+            if (!community && !term.abilities?.update) {
+              setReadonly(true);
             }
             }
           } else if (typeof parentChannelId !== "undefined") {
           } else if (typeof parentChannelId !== "undefined") {
             /**
             /**
-             * 在channel新建
-             * basic:仅保存在这个版本
-             * pro: 默认studio通用
+             * 在 channel 里新建
+             * basic:只能建在这个版本
+             * pro:在自己的 studio 里默认建成通用术语,在别人的版本里建在版本里
              */
              */
-            url = `/api/v2/terms?view=create-by-channel&channel=${parentChannelId}&word=${word}`;
-            console.info("api request 在channel新建", url);
-            const res = await get<ITermCreateResponse>(url);
-            console.debug("api response", res);
-            let channelId = "";
+            const channel = await fetchChannel(parentChannelId);
+            let target = "";
             let copyToChannel: string[] = [];
             let copyToChannel: string[] = [];
             if (user?.roles?.includes("basic")) {
             if (user?.roles?.includes("basic")) {
-              channelId = parentChannelId;
+              target = parentChannelId;
               copyToChannel = [parentChannelId];
               copyToChannel = [parentChannelId];
             } else {
             } else {
-              channelId = user?.id === parentStudioId ? "" : parentChannelId;
-              copyToChannel = [res.data.studio.id, parentChannelId];
+              target = user?.id === parentStudioId ? "" : parentChannelId;
+              copyToChannel = [channel?.owner?.id ?? "", parentChannelId];
             }
             }
             data = {
             data = {
-              word: word ? word : "",
-              tag: tags?.join(),
-              meaning: "",
-              meaning2: [],
-              note: "",
-              lang: res.data.language,
-              channelId: channelId,
+              ...data,
+              lang: channel?.lang ?? "",
+              channelId: target,
               copy_channel: copyToChannel,
               copy_channel: copyToChannel,
             };
             };
-          } else if (typeof studioName !== "undefined") {
-            //在studio新建
-
-            url = `/api/v2/terms?view=create-by-studio&studio=${studioName}&word=${word}`;
-            console.debug("在 studio 新建", url);
+          } else if (channelId) {
+            // 从版本的术语列表新建
+            data = { ...data, channelId };
           }
           }
-
           return data;
           return data;
         }}
         }}
       >
       >
@@ -308,42 +313,33 @@ const TermEditWidget = ({
             name="word"
             name="word"
             initialValue={word}
             initialValue={word}
             required
             required
-            label={intl.formatMessage({
-              id: "term.fields.word.label",
-            })}
-            rules={[
-              {
-                required: true,
-              },
-            ]}
-            fieldProps={{
-              showCount: true,
-              maxLength: 128,
-            }}
+            disabled={isEdit}
+            tooltip={
+              isEdit ? label("term.fields.immutable.tooltip") : undefined
+            }
+            label={label("term.fields.word.label")}
+            rules={[{ required: true }]}
+            fieldProps={{ showCount: true, maxLength: 128 }}
           />
           />
           <ProFormText
           <ProFormText
             width="md"
             width="md"
             name="tag"
             name="tag"
-            tooltip={intl.formatMessage({
-              id: "term.fields.description.tooltip",
-            })}
-            label={intl.formatMessage({
-              id: "term.fields.description.label",
-            })}
+            disabled={isEdit}
+            tooltip={
+              isEdit
+                ? label("term.fields.immutable.tooltip")
+                : label("term.fields.description.tooltip")
+            }
+            label={label("term.fields.description.label")}
+            rules={[{ pattern: /^[^@]*$/, message: "@" }]}
           />
           />
         </ProForm.Group>
         </ProForm.Group>
         <ProForm.Group>
         <ProForm.Group>
           <ProForm.Item
           <ProForm.Item
             width="md"
             width="md"
             name="meaning"
             name="meaning"
-            label={intl.formatMessage({
-              id: "term.fields.meaning.label",
-            })}
-            rules={[
-              {
-                required: true,
-              },
-            ]}
+            label={label("term.fields.meaning.label")}
+            rules={[{ required: true }]}
           >
           >
             <AutoComplete
             <AutoComplete
               options={meaningOptions}
               options={meaningOptions}
@@ -356,19 +352,10 @@ const TermEditWidget = ({
           <ProFormSelect
           <ProFormSelect
             width="md"
             width="md"
             name="meaning2"
             name="meaning2"
-            label={intl.formatMessage({
-              id: "term.fields.meaning2.label",
-            })}
-            fieldProps={{
-              mode: "tags",
-              tokenSeparators: [",", ","],
-            }}
+            label={label("term.fields.meaning2.label")}
+            fieldProps={{ mode: "tags", tokenSeparators: [",", ","] }}
             placeholder="Please select other meanings"
             placeholder="Please select other meanings"
-            rules={[
-              {
-                type: "array",
-              },
-            ]}
+            rules={[{ type: "array" }]}
           />
           />
         </ProForm.Group>
         </ProForm.Group>
         <ProForm.Group>
         <ProForm.Group>
@@ -377,49 +364,83 @@ const TermEditWidget = ({
             allowClear
             allowClear
             label="版本(已经建立的术语,版本不可修改。可以选择另存为复制到另一个版本。)"
             label="版本(已经建立的术语,版本不可修改。可以选择另存为复制到另一个版本。)"
             width="md"
             width="md"
-            placeholder={intl.formatMessage({
-              id: "term.general-in-studio",
-            })}
+            placeholder={label("term.general-in-studio")}
             disabled={channelDisable}
             disabled={channelDisable}
             options={[
             options={[
               {
               {
                 value: "",
                 value: "",
-                label: intl.formatMessage({
-                  id: "term.general-in-studio",
-                }),
+                label: label("term.general-in-studio"),
                 disabled:
                 disabled:
-                  user?.id !== parentStudioId || user?.roles?.includes("basic"),
-              },
-              {
-                value: parentChannelId ?? channelId,
-                label: "仅用于此版本",
-                disabled: !community && readonly,
+                  (parentStudioId !== undefined &&
+                    user?.id !== parentStudioId) ||
+                  user?.roles?.includes("basic"),
               },
               },
+              ...((parentChannelId ?? channelId)
+                ? [
+                    {
+                      value: parentChannelId ?? channelId ?? "",
+                      label: "仅用于此版本",
+                      disabled: !community && readonly,
+                    },
+                  ]
+                : []),
               ...currChannel,
               ...currChannel,
             ]}
             ]}
           />
           />
 
 
           <ProFormDependency name={["channelId"]}>
           <ProFormDependency name={["channelId"]}>
             {({ channelId }) => {
             {({ channelId }) => {
-              const hasChannel = channelId
-                ? channelId === ""
-                  ? false
-                  : true
-                : false;
+              const hasChannel = !!channelId;
               return (
               return (
                 <LangSelect
                 <LangSelect
-                  disabled={hasChannel || channelDisable}
+                  disabled={hasChannel || (channelDisable && !isGeneral)}
                   required={!hasChannel}
                   required={!hasChannel}
                 />
                 />
               );
               );
             }}
             }}
           </ProFormDependency>
           </ProFormDependency>
         </ProForm.Group>
         </ProForm.Group>
+        <ProForm.Group>
+          <ProFormSelect
+            width="sm"
+            name="quality"
+            allowClear
+            label={label("term.fields.quality.label")}
+            placeholder={label("term.fields.quality.pending")}
+            options={TERM_QUALITIES.map((q) => ({
+              value: q,
+              label: label(`term.fields.quality.${q}`),
+            }))}
+          />
+          <ProFormSelect
+            width="sm"
+            name="content_type"
+            label={label("term.fields.content_type.label")}
+            allowClear={false}
+            options={TERM_CONTENT_TYPES.map((t) => ({ value: t, label: t }))}
+          />
+          <ProFormText
+            width="md"
+            name="redirect"
+            label={label("term.fields.redirect.label")}
+            tooltip={label("term.fields.redirect.tooltip")}
+          />
+        </ProForm.Group>
+        <ProForm.Group>
+          <Form.Item
+            style={{ width: "100%" }}
+            name="summary"
+            label={label("term.fields.summary.label")}
+            tooltip={label("term.fields.summary.tooltip")}
+          >
+            <MDEditor height={120} preview="edit" />
+          </Form.Item>
+        </ProForm.Group>
         <ProForm.Group>
         <ProForm.Group>
           <Form.Item
           <Form.Item
             style={{ width: "100%" }}
             style={{ width: "100%" }}
             name="note"
             name="note"
-            label={intl.formatMessage({ id: "forms.fields.note.label" })}
+            label={label("forms.fields.note.label")}
           >
           >
             <MDEditor />
             <MDEditor />
           </Form.Item>
           </Form.Item>
@@ -442,16 +463,10 @@ const TermEditWidget = ({
             parentStudioId={parentStudioId}
             parentStudioId={parentStudioId}
             width="md"
             width="md"
             name="copy_channel"
             name="copy_channel"
-            placeholder={intl.formatMessage({
-              id: "term.general-in-studio",
-            })}
+            placeholder={label("term.general-in-studio")}
             allowClear={user?.roles?.includes("basic") ? false : true}
             allowClear={user?.roles?.includes("basic") ? false : true}
-            tooltip={intl.formatMessage({
-              id: "term.fields.channel.tooltip",
-            })}
-            label={intl.formatMessage({
-              id: "term.fields.channel.label",
-            })}
+            tooltip={label("term.fields.channel.tooltip")}
+            label={label("term.fields.channel.label")}
           />
           />
           <ProFormDependency name={["copy_channel"]}>
           <ProFormDependency name={["copy_channel"]}>
             {({ copy_channel }) => {
             {({ copy_channel }) => {

+ 21 - 47
dashboard-v6/src/components/term/TermExport.tsx

@@ -1,65 +1,39 @@
 import { useState } from "react";
 import { useState } from "react";
 import { useIntl } from "react-intl";
 import { useIntl } from "react-intl";
-import { Button, message } from "antd";
+import { Button } from "antd";
 import { ExportOutlined } from "@ant-design/icons";
 import { ExportOutlined } from "@ant-design/icons";
-import modal from "antd/lib/modal";
 
 
-import { get } from "../../request";
+import { exportTerms, type TermExchangeTarget } from "../../api/Term";
 
 
-interface IExportResponse {
-  ok: boolean;
-  message: string;
-  data: {
-    uuid: string;
-    filename: string;
-    type: string;
-  };
-}
 interface IWidget {
 interface IWidget {
-  channelId?: string;
-  studioName?: string;
+  target?: TermExchangeTarget;
 }
 }
-const TermExportWidget = ({ channelId, studioName }: IWidget) => {
+
+/** 导出术语为 xlsx(v3:列表接口带 Accept: xlsx,直接下载,取代 v2 terms-export 的两步下载) */
+const TermExportWidget = ({ target }: IWidget) => {
   const intl = useIntl();
   const intl = useIntl();
   const [loading, setLoading] = useState(false);
   const [loading, setLoading] = useState(false);
   return (
   return (
     <Button
     <Button
       loading={loading}
       loading={loading}
+      disabled={!target}
       icon={<ExportOutlined />}
       icon={<ExportOutlined />}
-      onClick={() => {
-        let url = `/api/v2/terms-export?view=`;
-        if (typeof channelId !== "undefined") {
-          url += `channel&id=${channelId}`;
-        } else if (typeof studioName !== "undefined") {
-          url += `studio&name=${studioName}`;
+      onClick={async () => {
+        if (!target) {
+          return;
         }
         }
         setLoading(true);
         setLoading(true);
-        get<IExportResponse>(url)
-          .then((json) => {
-            if (json.ok) {
-              const link = `${import.meta.env.BASE_URL}/api/api/v2/terms-export/${json.data.uuid}`;
-              modal.info({
-                title: intl.formatMessage({ id: "buttons.download" }),
-                content: (
-                  <>
-                    <a
-                      href={link}
-                      target="_blank"
-                      key="export"
-                      rel="noreferrer"
-                    >
-                      {intl.formatMessage({ id: "buttons.download.link" })}
-                    </a>
-                  </>
-                ),
-              });
-            } else {
-              message.error(json.message);
-            }
-          })
-          .finally(() => {
-            setLoading(false);
-          });
+        try {
+          const blob = await exportTerms(target);
+          const url = URL.createObjectURL(blob);
+          const link = document.createElement("a");
+          link.href = url;
+          link.download = "terms.xlsx";
+          link.click();
+          URL.revokeObjectURL(url);
+        } finally {
+          setLoading(false);
+        }
       }}
       }}
     >
     >
       {intl.formatMessage({ id: "buttons.export" })}
       {intl.formatMessage({ id: "buttons.export" })}

+ 100 - 0
dashboard-v6/src/components/term/TermImport.tsx

@@ -0,0 +1,100 @@
+import { useState } from "react";
+import { useIntl } from "react-intl";
+import { Alert, Button, Modal, Space, Table, Typography, Upload } from "antd";
+import { ImportOutlined } from "@ant-design/icons";
+
+import {
+  importTerms,
+  type TermExchangeTarget,
+  type TermImportResult,
+} from "../../api/Term";
+
+interface IWidget {
+  target?: TermExchangeTarget;
+  onSuccess?: () => void;
+}
+
+/**
+ * 导入术语(xlsx,v3)。可以直接用导出的表格改完传回。部分成功:出错的行跳过,弹窗里逐行列出原因。
+ */
+const TermImportWidget = ({ target, onSuccess }: IWidget) => {
+  const intl = useIntl();
+  const [loading, setLoading] = useState(false);
+  const [result, setResult] = useState<TermImportResult>();
+  const label = (id: string) => intl.formatMessage({ id });
+
+  return (
+    <>
+      <Upload
+        accept=".xlsx"
+        showUploadList={false}
+        disabled={!target || loading}
+        customRequest={async ({ file }) => {
+          if (!target) {
+            return;
+          }
+          setLoading(true);
+          try {
+            const data = await importTerms(target, file as File);
+            setResult(data);
+            onSuccess?.();
+          } finally {
+            setLoading(false);
+          }
+        }}
+      >
+        <Button icon={<ImportOutlined />} loading={loading} disabled={!target}>
+          {label("buttons.import")}
+        </Button>
+      </Upload>
+      <Modal
+        open={!!result}
+        title={label("term.import.result")}
+        footer={null}
+        width={640}
+        onCancel={() => setResult(undefined)}
+      >
+        {result && (
+          <Space orientation="vertical" style={{ width: "100%" }}>
+            <Typography.Text>
+              {intl.formatMessage(
+                { id: "term.import.summary" },
+                {
+                  created: result.created,
+                  updated: result.updated,
+                  unchanged: result.unchanged,
+                  failed: result.errors?.length ?? 0,
+                },
+              )}
+            </Typography.Text>
+            {!result.reindexed && (
+              <Alert
+                type="info"
+                showIcon
+                title={label("term.import.reindex_later")}
+              />
+            )}
+            {(result.errors?.length ?? 0) > 0 && (
+              <Table
+                size="small"
+                rowKey="row"
+                pagination={{ pageSize: 10 }}
+                dataSource={result.errors}
+                columns={[
+                  {
+                    title: label("term.import.row"),
+                    dataIndex: "row",
+                    width: 80,
+                  },
+                  { title: label("term.import.reason"), dataIndex: "message" },
+                ]}
+              />
+            )}
+          </Space>
+        )}
+      </Modal>
+    </>
+  );
+};
+
+export default TermImportWidget;

+ 11 - 12
dashboard-v6/src/components/term/TermItem.tsx

@@ -5,12 +5,11 @@ import {
   TranslationOutlined,
   TranslationOutlined,
 } from "@ant-design/icons";
 } from "@ant-design/icons";
 
 
-import type { ITerm, ITermDataResponse } from "../../api/Term";
+import type { ITerm, Term } from "../../api/Term";
 
 
 import TimeShow from "../general/TimeShow";
 import TimeShow from "../general/TimeShow";
 import TermModal from "./TermModal";
 import TermModal from "./TermModal";
 import { useEffect, useState } from "react";
 import { useEffect, useState } from "react";
-import StudioName from "../auth/Studio";
 import { Link, useNavigate } from "react-router";
 import { Link, useNavigate } from "react-router";
 import { useAppSelector } from "../../hooks";
 import { useAppSelector } from "../../hooks";
 import { click, clickedTerm } from "../../reducers/term-click";
 import { click, clickedTerm } from "../../reducers/term-click";
@@ -19,13 +18,14 @@ import "../article/article.css";
 import Discussion from "../discussion/Discussion";
 import Discussion from "../discussion/Discussion";
 import { useIntl } from "react-intl";
 import { useIntl } from "react-intl";
 import User from "../auth/User";
 import User from "../auth/User";
-import MdView from "../general/MdView";
+import MarkupView from "../markup/MarkupView";
+import type { MarkupNode } from "../markup/types";
 import { articlePath } from "../../utils";
 import { articlePath } from "../../utils";
 
 
 const { Text } = Typography;
 const { Text } = Typography;
 
 
 interface IWidget {
 interface IWidget {
-  data?: ITermDataResponse;
+  data?: Term;
   onTermClick?: (clicked: ITerm) => void;
   onTermClick?: (clicked: ITerm) => void;
 }
 }
 const TermItemWidget = ({ data, onTermClick }: IWidget) => {
 const TermItemWidget = ({ data, onTermClick }: IWidget) => {
@@ -40,7 +40,7 @@ const TermItemWidget = ({ data, onTermClick }: IWidget) => {
     if (!termClicked) {
     if (!termClicked) {
       return;
       return;
     }
     }
-    if (termClicked?.channelId === data?.channel?.id) {
+    if (termClicked?.channelId === (data?.channel_id ?? undefined)) {
       store.dispatch(click(null));
       store.dispatch(click(null));
       onTermClick?.(termClicked);
       onTermClick?.(termClicked);
     }
     }
@@ -53,20 +53,19 @@ const TermItemWidget = ({ data, onTermClick }: IWidget) => {
         title={
         title={
           <Space orientation="vertical" size={3}>
           <Space orientation="vertical" size={3}>
             <Space>
             <Space>
-              <Link to={`/term/show/${data?.guid}`}>
+              <Link to={`/term/show/${data?.id}`}>
                 <Text strong>{data?.meaning}</Text>
                 <Text strong>{data?.meaning}</Text>
               </Link>
               </Link>
               <Text type="secondary">{data?.other_meaning}</Text>
               <Text type="secondary">{data?.other_meaning}</Text>
             </Space>
             </Space>
             <Space style={{ fontSize: "80%" }}>
             <Space style={{ fontSize: "80%" }}>
-              <StudioName data={data?.studio} />
               {data?.channel
               {data?.channel
                 ? data.channel.name
                 ? data.channel.name
                 : intl.formatMessage({
                 : intl.formatMessage({
                     id: "term.general-in-studio",
                     id: "term.general-in-studio",
                   })}
                   })}
               <Text type="secondary">
               <Text type="secondary">
-                <User {...data?.editor} showAvatar={false} />
+                <User {...(data?.editor ?? {})} showAvatar={false} />
               </Text>
               </Text>
               <TimeShow type="secondary" updatedAt={data?.updated_at} />
               <TimeShow type="secondary" updatedAt={data?.updated_at} />
             </Space>
             </Space>
@@ -96,7 +95,7 @@ const TermItemWidget = ({ data, onTermClick }: IWidget) => {
                     setOpenTermModal(true);
                     setOpenTermModal(true);
                     break;
                     break;
                   case "translate":
                   case "translate":
-                    navigate(articlePath("term", data?.guid ?? ""));
+                    navigate(articlePath("term", data?.id ?? ""));
                     break;
                     break;
                   default:
                   default:
                     break;
                     break;
@@ -114,10 +113,10 @@ const TermItemWidget = ({ data, onTermClick }: IWidget) => {
         }
         }
       >
       >
         <div className="pcd_article">
         <div className="pcd_article">
-          <MdView html={data?.html} />
+          <MarkupView nodes={data?.body as MarkupNode[] | undefined} />
         </div>
         </div>
         {showDiscussion ? (
         {showDiscussion ? (
-          <Discussion resType="term" resId={data?.guid} />
+          <Discussion resType="term" resId={data?.id} />
         ) : (
         ) : (
           <div style={{ textAlign: "right" }}>
           <div style={{ textAlign: "right" }}>
             <Button type="link" onClick={() => setShowDiscussion(true)}>
             <Button type="link" onClick={() => setShowDiscussion(true)}>
@@ -127,7 +126,7 @@ const TermItemWidget = ({ data, onTermClick }: IWidget) => {
         )}
         )}
       </Card>
       </Card>
       <TermModal
       <TermModal
-        id={data?.guid}
+        id={data?.id}
         open={openTermModal}
         open={openTermModal}
         onClose={() => setOpenTermModal(false)}
         onClose={() => setOpenTermModal(false)}
       />
       />

+ 68 - 77
dashboard-v6/src/components/term/TermList.tsx

@@ -4,22 +4,23 @@ import { Button, Space, Table, Dropdown, Modal, message } from "antd";
 import {
 import {
   ExclamationCircleOutlined,
   ExclamationCircleOutlined,
   DeleteOutlined,
   DeleteOutlined,
-  ImportOutlined,
   PlusOutlined,
   PlusOutlined,
 } from "@ant-design/icons";
 } from "@ant-design/icons";
 
 
-import type { ITermDeleteRequest, ITermListResponse } from "../../api/Term";
-import { delete_2, get } from "../../request";
-import type { IDeleteResponse } from "../../api/article";
+import {
+  deleteTerm,
+  fetchChannelTerms,
+  fetchStudioTerms,
+  type TermExchangeTarget,
+  type TermListQuery,
+} from "../../api/Term";
 import { useRef } from "react";
 import { useRef } from "react";
 import TermExport from "./TermExport";
 import TermExport from "./TermExport";
+import TermImport from "./TermImport";
 
 
 import TermModal from "./TermModal";
 import TermModal from "./TermModal";
-import { getSorterUrl } from "../../utils";
 import { useAppSelector } from "../../hooks";
 import { useAppSelector } from "../../hooks";
 import { currentUser } from "../../reducers/current-user";
 import { currentUser } from "../../reducers/current-user";
-import type { IChannel } from "../../api/channel";
-import DataImport from "../general/DataImport";
 import { Link } from "react-router";
 import { Link } from "react-router";
 
 
 interface IItem {
 interface IItem {
@@ -27,7 +28,7 @@ interface IItem {
   id: string;
   id: string;
   word: string;
   word: string;
   tag: string;
   tag: string;
-  channel?: IChannel;
+  channel?: string;
   meaning: string;
   meaning: string;
   meaning2: string;
   meaning2: string;
   note: string | null;
   note: string | null;
@@ -35,10 +36,13 @@ interface IItem {
 }
 }
 
 
 interface IWidget {
 interface IWidget {
+  /** v3 列表用:用户或团队的 uuid */
+  studioId?: string;
+  /** TermModal 的「在 Studio 中打开」用 */
   studioName?: string;
   studioName?: string;
   channelId?: string;
   channelId?: string;
 }
 }
-const TermListWidget = ({ studioName, channelId }: IWidget) => {
+const TermListWidget = ({ studioId, studioName, channelId }: IWidget) => {
   const intl = useIntl();
   const intl = useIntl();
   const currUser = useAppSelector(currentUser);
   const currUser = useAppSelector(currentUser);
 
 
@@ -61,29 +65,25 @@ const TermListWidget = ({ studioName, channelId }: IWidget) => {
       cancelText: intl.formatMessage({
       cancelText: intl.formatMessage({
         id: "buttons.no",
         id: "buttons.no",
       }),
       }),
-      onOk() {
-        console.log("delete", id);
-        return delete_2<ITermDeleteRequest, IDeleteResponse>(
-          `/api/v2/terms/${id}`,
-          {
-            uuid: true,
-            id: id,
-          }
-        )
-          .then((json) => {
-            if (json.ok) {
-              message.success("删除成功");
-              ref.current?.reload();
-            } else {
-              message.error(json.message);
-            }
-          })
-          .catch((e: unknown) => console.log("Oops errors!", e));
+      async onOk() {
+        // v3 一条一条软删;没有删除权限的那条会弹出提示并中止
+        for (const termId of id) {
+          await deleteTerm(termId);
+        }
+        message.success("删除成功");
+        ref.current?.reload();
       },
       },
     });
     });
   };
   };
 
 
   const ref = useRef<ActionType | null>(null);
   const ref = useRef<ActionType | null>(null);
+  // 导入 / 导出的范围:channel 详情页按 channel,术语页按当前身份的 studio
+  const exchangeTarget: TermExchangeTarget | undefined =
+    typeof channelId === "string"
+      ? { channelId }
+      : studioId
+        ? { studioId }
+        : undefined;
 
 
   return (
   return (
     <>
     <>
@@ -128,7 +128,10 @@ const TermListWidget = ({ studioName, channelId }: IWidget) => {
             dataIndex: "channel",
             dataIndex: "channel",
             key: "channel",
             key: "channel",
             render(_dom, entity) {
             render(_dom, entity) {
-              return entity.channel?.name;
+              return (
+                entity.channel ??
+                intl.formatMessage({ id: "term.general-in-studio" })
+              );
             },
             },
           },
           },
           {
           {
@@ -243,7 +246,7 @@ const TermListWidget = ({ studioName, channelId }: IWidget) => {
                   console.log(selectedRowKeys);
                   console.log(selectedRowKeys);
                   showDeleteConfirm(
                   showDeleteConfirm(
                     selectedRowKeys.map((item) => item.toString()),
                     selectedRowKeys.map((item) => item.toString()),
-                    selectedRowKeys.length + "个单词"
+                    selectedRowKeys.length + "个单词",
                   );
                   );
                   onCleanSelected();
                   onCleanSelected();
                 }}
                 }}
@@ -253,40 +256,39 @@ const TermListWidget = ({ studioName, channelId }: IWidget) => {
             </Space>
             </Space>
           );
           );
         }}
         }}
-        request={async (params = {}, sorter, filter) => {
-          console.log(params, sorter, filter);
-          const offset =
-            ((params.current ? params.current : 1) - 1) *
-            (params.pageSize ? params.pageSize : 20);
-          let url = `/api/v2/terms?`;
-          if (typeof channelId === "string") {
-            url += `view=channel&id=${channelId}`;
-          } else {
-            url += `view=studio&name=${studioName}`;
-          }
-
-          url += `&limit=${params.pageSize}&offset=${offset}`;
-          if (typeof params.keyword !== "undefined") {
-            url += "&search=" + (params.keyword ? params.keyword : "");
+        request={async (params = {}, sorter) => {
+          const page = params.current ?? 1;
+          const perPage = params.pageSize ?? 20;
+          const query: TermListQuery = {
+            page,
+            per_page: perPage,
+            search: params.keyword || undefined,
+          };
+          const sort = sorter?.updated_at;
+          if (sort) {
+            query.order = "updated_at";
+            query.dir = sort === "ascend" ? "asc" : "desc";
           }
           }
-          url += getSorterUrl(sorter);
-          const res = await get<ITermListResponse>(url);
-          console.log(res);
-          const items: IItem[] = res.data.rows.map((item, id) => {
-            return {
-              sn: id + offset + 1,
-              id: item.guid,
-              word: item.word,
-              tag: item.tag,
-              channel: item.channel,
-              meaning: item.meaning,
-              meaning2: item.other_meaning,
-              note: item.note,
-              updated_at: item.updated_at,
-            };
-          });
+          const res =
+            typeof channelId === "string"
+              ? await fetchChannelTerms(channelId, query)
+              : studioId
+                ? await fetchStudioTerms(studioId, query)
+                : undefined;
+          const offset = (page - 1) * perPage;
+          const items: IItem[] = (res?.data ?? []).map((item, index) => ({
+            sn: index + offset + 1,
+            id: item.id ?? "",
+            word: item.word ?? "",
+            tag: item.tag ?? "",
+            channel: item.channel?.name,
+            meaning: item.meaning ?? "",
+            meaning2: item.other_meaning ?? "",
+            note: item.summary_text ?? "",
+            updated_at: item.updated_at ?? "",
+          }));
           return {
           return {
-            total: res.data.count,
+            total: res?.meta?.total ?? 0,
             success: true,
             success: true,
             data: items,
             data: items,
           };
           };
@@ -298,23 +300,12 @@ const TermListWidget = ({ studioName, channelId }: IWidget) => {
           showSizeChanger: true,
           showSizeChanger: true,
         }}
         }}
         toolBarRender={() => [
         toolBarRender={() => [
-          <DataImport
-            url="/api/v2/terms-import"
-            urlExtra={
-              channelId
-                ? `view=channel&id=${channelId}`
-                : `view=studio&name=${studioName}`
-            }
-            trigger={
-              <Button icon={<ImportOutlined />}>
-                {intl.formatMessage({ id: "buttons.import" })}
-              </Button>
-            }
-            onSuccess={() => {
-              ref.current?.reload();
-            }}
+          <TermImport
+            key="import"
+            target={exchangeTarget}
+            onSuccess={() => ref.current?.reload()}
           />,
           />,
-          <TermExport channelId={channelId} studioName={studioName} />,
+          <TermExport key="export" target={exchangeTarget} />,
           <TermModal
           <TermModal
             trigger={
             trigger={
               <Button
               <Button

+ 3 - 3
dashboard-v6/src/components/term/TermModal.tsx

@@ -1,7 +1,7 @@
 import { Modal, Space } from "antd";
 import { Modal, Space } from "antd";
 import { Link } from "react-router";
 import { Link } from "react-router";
 import TermEdit from "./TermEdit";
 import TermEdit from "./TermEdit";
-import type { ITermDataResponse } from "../../api/Term";
+import type { Term } from "../../api/Term";
 import useMergedState from "../../hooks/useMergedState"; // 确保路径正确
 import useMergedState from "../../hooks/useMergedState"; // 确保路径正确
 
 
 interface IWidget {
 interface IWidget {
@@ -15,7 +15,7 @@ interface IWidget {
   parentChannelId?: string;
   parentChannelId?: string;
   parentStudioId?: string;
   parentStudioId?: string;
   community?: boolean;
   community?: boolean;
-  onUpdate?: (value: ITermDataResponse) => void;
+  onUpdate?: (value: Term) => void;
   onClose?: () => void;
   onClose?: () => void;
 }
 }
 
 
@@ -70,7 +70,7 @@ const TermModalWidget = (props: IWidget) => {
         <TermEdit
         <TermEdit
           {...restEditProps}
           {...restEditProps}
           studioName={studioName}
           studioName={studioName}
-          onUpdate={(value: ITermDataResponse) => {
+          onUpdate={(value: Term) => {
             close();
             close();
             onUpdate?.(value);
             onUpdate?.(value);
           }}
           }}

+ 15 - 23
dashboard-v6/src/components/term/TermSearch.tsx

@@ -1,13 +1,7 @@
 import { useEffect, useState } from "react";
 import { useEffect, useState } from "react";
 import { Col, Row, Skeleton, Typography } from "antd";
 import { Col, Row, Skeleton, Typography } from "antd";
 
 
-import { get } from "../../request";
-import type {
-  ITerm,
-  ITermDataResponse,
-  ITermListResponse,
-  ITermResponse,
-} from "../../api/Term";
+import { fetchTerm, lookupTerms, type ITerm, type Term } from "../../api/Term";
 import TermItem from "./TermItem";
 import TermItem from "./TermItem";
 
 
 const { Title } = Typography;
 const { Title } = Typography;
@@ -25,7 +19,7 @@ const TermSearchWidget = ({
   compact = false,
   compact = false,
   onIdChange,
   onIdChange,
 }: IWidget) => {
 }: IWidget) => {
-  const [tableData, setTableData] = useState<ITermDataResponse[]>([]);
+  const [tableData, setTableData] = useState<Term[]>([]);
   const [loading, setLoading] = useState(false);
   const [loading, setLoading] = useState(false);
 
 
   useEffect(() => {
   useEffect(() => {
@@ -38,22 +32,18 @@ const TermSearchWidget = ({
 
 
       try {
       try {
         if (word && word.length > 0) {
         if (word && word.length > 0) {
-          const url = `/api/v2/terms?view=word&word=${word}`;
-          console.info("term url", url);
-
-          const json = await get<ITermListResponse>(url);
-
+          const json = await lookupTerms({
+            word,
+            with_body: true,
+            per_page: 100,
+          });
           if (!cancelled) {
           if (!cancelled) {
-            setTableData(json.data.rows);
+            setTableData(json.data ?? []);
           }
           }
         } else if (wordId && wordId.length > 0) {
         } else if (wordId && wordId.length > 0) {
-          const url = `/api/v2/terms/${wordId}`;
-          console.info("term url", url);
-
-          const json = await get<ITermResponse>(url);
-
-          if (!cancelled) {
-            setTableData([json.data]);
+          const term = await fetchTerm(wordId);
+          if (!cancelled && term) {
+            setTableData([term]);
           }
           }
         }
         }
       } catch (error) {
       } catch (error) {
@@ -80,8 +70,10 @@ const TermSearchWidget = ({
       (async () => {
       (async () => {
         setLoading(true);
         setLoading(true);
         try {
         try {
-          const json = await get<ITermResponse>(`/api/v2/terms/${value.id}`);
-          setTableData([json.data]);
+          const term = await fetchTerm(value.id ?? "");
+          if (term) {
+            setTableData([term]);
+          }
         } finally {
         } finally {
           setLoading(false);
           setLoading(false);
         }
         }

+ 16 - 17
dashboard-v6/src/components/term/TermTest.tsx

@@ -21,7 +21,7 @@ import {
 // ─── 导入被测试的真实组件 ──────────────────────────────────────────────────────
 // ─── 导入被测试的真实组件 ──────────────────────────────────────────────────────
 import TermModal from "./TermModal";
 import TermModal from "./TermModal";
 import TermEdit from "./TermEdit";
 import TermEdit from "./TermEdit";
-import type { ITermDataResponse } from "../../api/Term";
+import type { ITermDataResponse, Term } from "../../api/Term";
 import type { IChannel } from "../../api/channel";
 import type { IChannel } from "../../api/channel";
 
 
 const { Title, Text, Paragraph } = Typography;
 const { Title, Text, Paragraph } = Typography;
@@ -121,7 +121,7 @@ interface ILogEntry {
   time: string;
   time: string;
   scene: string;
   scene: string;
   type: "onUpdate" | "onClose";
   type: "onUpdate" | "onClose";
-  data?: ITermDataResponse;
+  data?: Term;
 }
 }
 
 
 // ─── TermTest ─────────────────────────────────────────────────────────────────
 // ─── TermTest ─────────────────────────────────────────────────────────────────
@@ -134,11 +134,7 @@ const TermTest: React.FC = () => {
   // 日志
   // 日志
   const [logs, setLogs] = useState<ILogEntry[]>([]);
   const [logs, setLogs] = useState<ILogEntry[]>([]);
 
 
-  const pushLog = (
-    scene: string,
-    type: ILogEntry["type"],
-    data?: ITermDataResponse
-  ) => {
+  const pushLog = (scene: string, type: ILogEntry["type"], data?: Term) => {
     setLogs((prev) => [
     setLogs((prev) => [
       { time: new Date().toLocaleTimeString("zh-CN"), scene, type, data },
       { time: new Date().toLocaleTimeString("zh-CN"), scene, type, data },
       ...prev.slice(0, 19),
       ...prev.slice(0, 19),
@@ -148,17 +144,20 @@ const TermTest: React.FC = () => {
   // 场景三:词条列表(onUpdate 同步更新本地数据)
   // 场景三:词条列表(onUpdate 同步更新本地数据)
   const [terms, setTerms] = useState<ITermDataResponse[]>(MOCK_TERMS);
   const [terms, setTerms] = useState<ITermDataResponse[]>(MOCK_TERMS);
 
 
-  const handleTermUpdate = (scene: string) => (value: ITermDataResponse) => {
+  // 保存后返回的是 v3 的 Term,这里只把释义同步回演示用的假数据
+  const handleTermUpdate = (scene: string) => (value: Term) => {
     pushLog(scene, "onUpdate", value);
     pushLog(scene, "onUpdate", value);
-    setTerms((prev) => {
-      const idx = prev.findIndex((t) => t.id === value.id);
-      if (idx >= 0) {
-        const next = [...prev];
-        next[idx] = value;
-        return next;
-      }
-      return [value, ...prev];
-    });
+    setTerms((prev) =>
+      prev.map((t) =>
+        t.guid === value.id
+          ? {
+              ...t,
+              meaning: value.meaning ?? t.meaning,
+              other_meaning: value.other_meaning ?? "",
+            }
+          : t,
+      ),
+    );
   };
   };
 
 
   // 场景三:表格列
   // 场景三:表格列

+ 2 - 0
dashboard-v6/src/features/editor/Term.tsx

@@ -40,6 +40,7 @@ export default function TermEditor({
   anthologyId,
   anthologyId,
   mode = "read",
   mode = "read",
   channelId,
   channelId,
+  onTermSelect,
   onChannelSelect,
   onChannelSelect,
   onEdit,
   onEdit,
 }: ArticleEditorProps) {
 }: ArticleEditorProps) {
@@ -81,6 +82,7 @@ export default function TermEditor({
           channelId={channelId}
           channelId={channelId}
           headerExtra={expandButton}
           headerExtra={expandButton}
           onEdit={onEdit}
           onEdit={onEdit}
+          onTermClick={onTermSelect}
         />
         />
       )}
       )}
     </Editor>
     </Editor>

+ 0 - 1
dashboard-v6/src/features/teamspace/scope.ts

@@ -24,7 +24,6 @@ const PERSONAL_ONLY = [
 const NOT_YET_SUPPORTED = [
 const NOT_YET_SUPPORTED = [
   "workspace.article",
   "workspace.article",
   "workspace.anthology",
   "workspace.anthology",
-  "workspace.term",
   "workspace.course",
   "workspace.course",
   "workspace.task",
   "workspace.task",
   "workspace.tag",
   "workspace.tag",

+ 12 - 32
dashboard-v6/src/load.ts

@@ -1,11 +1,7 @@
 //import { Empty } from "google-protobuf/google/protobuf/empty_pb";
 //import { Empty } from "google-protobuf/google/protobuf/empty_pb";
 //import { Duration } from "google-protobuf/google/protobuf/duration_pb";
 //import { Duration } from "google-protobuf/google/protobuf/duration_pb";
 
 
-import {
-  get as getToken,
-  guest,
-  signIn,
-} from "./reducers/current-user";
+import { get as getToken, guest, signIn } from "./reducers/current-user";
 import { remove as removeToken } from "./reducers/session";
 import { remove as removeToken } from "./reducers/session";
 import { fetchMe } from "./api/session";
 import { fetchMe } from "./api/session";
 import { ApiError } from "./api/error";
 import { ApiError } from "./api/error";
@@ -20,7 +16,8 @@ import { get } from "./request";
 import { get as getLang } from "./locales";
 import { get as getLang } from "./locales";
 
 
 import store from "./store";
 import store from "./store";
-import { grammar, type ITerm, update } from "./reducers/term-vocabulary";
+import { grammar, update } from "./reducers/term-vocabulary";
+import { fetchGlossary } from "./api/glossary";
 import { push as nissayaEndingPush } from "./reducers/nissaya-ending-vocabulary";
 import { push as nissayaEndingPush } from "./reducers/nissaya-ending-vocabulary";
 
 
 import { pushRelation } from "./reducers/relation";
 import { pushRelation } from "./reducers/relation";
@@ -39,14 +36,6 @@ export interface ISiteInfoResponse {
   subhead: string;
   subhead: string;
   models?: ISettingModels;
   models?: ISettingModels;
 }
 }
-interface ITermResponse {
-  ok: boolean;
-  message: string;
-  data: {
-    rows: ITerm[];
-    count: number;
-  };
-}
 interface INissayaEnding {
 interface INissayaEnding {
   ending: string;
   ending: string;
 }
 }
@@ -61,14 +50,9 @@ interface INissayaEndingResponse {
 
 
 export const grammarTermFetch = () => {
 export const grammarTermFetch = () => {
   //获取语法术语表
   //获取语法术语表
-  get<ITermResponse>(
-    `/api/v2/term-vocabulary?view=grammar&lang=` + getLang()
-  ).then((json) => {
-    if (json.ok) {
-      console.debug("grammar dispatch", json.data.rows);
-      store.dispatch(grammar(json.data.rows));
-    }
-  });
+  fetchGlossary("grammar", getLang())
+    .then((rows) => store.dispatch(grammar(rows)))
+    .catch((e: unknown) => console.warn("fetch grammar glossary failed", e));
 };
 };
 
 
 const init = () => {
 const init = () => {
@@ -93,7 +77,7 @@ const init = () => {
 
 
     // 团队列表取不到不影响使用:账户列表里只剩个人,团队空间沿用 localStorage 里的,下次启动再校验
     // 团队列表取不到不影响使用:账户列表里只剩个人,团队空间沿用 localStorage 里的,下次启动再校验
     refreshMyGroups(store.dispatch).catch((e: unknown) =>
     refreshMyGroups(store.dispatch).catch((e: unknown) =>
-      console.warn("fetch my groups failed", e)
+      console.warn("fetch my groups failed", e),
     );
     );
   } else {
   } else {
     console.log("no token");
     console.log("no token");
@@ -110,14 +94,10 @@ const init = () => {
   //获取语法术语表
   //获取语法术语表
   grammarTermFetch();
   grammarTermFetch();
 
 
-  //获取术语表
-  get<ITermResponse>(
-    `/api/v2/term-vocabulary?view=community&lang=` + getLang()
-  ).then((json) => {
-    if (json.ok) {
-      store.dispatch(update(json.data.rows));
-    }
-  });
+  //获取术语表(社区译名)
+  fetchGlossary("community", getLang())
+    .then((rows) => store.dispatch(update(rows)))
+    .catch((e: unknown) => console.warn("fetch community glossary failed", e));
 
 
   //获取nissaya ending 表
   //获取nissaya ending 表
   get<INissayaEndingResponse>(`/api/v2/nissaya-ending-vocabulary?lang=my`).then(
   get<INissayaEndingResponse>(`/api/v2/nissaya-ending-vocabulary?lang=my`).then(
@@ -126,7 +106,7 @@ const init = () => {
         const nissayaEnding = json.data.rows.map((item) => item.ending);
         const nissayaEnding = json.data.rows.map((item) => item.ending);
         store.dispatch(nissayaEndingPush(nissayaEnding));
         store.dispatch(nissayaEndingPush(nissayaEnding));
       }
       }
-    }
+    },
   );
   );
 
 
   //获取 relation 表
   //获取 relation 表

+ 26 - 1
dashboard-v6/src/locales/en-US/label.ts

@@ -140,6 +140,30 @@ const items = {
   "term.fields.meaning.tooltip": "单词的首选意思",
   "term.fields.meaning.tooltip": "单词的首选意思",
   "term.fields.meaning2.label": "other meanings",
   "term.fields.meaning2.label": "other meanings",
   "term.fields.meaning2.tooltip": "其他意思将出现在后面的括号里",
   "term.fields.meaning2.tooltip": "其他意思将出现在后面的括号里",
+  "term.fields.quality.label": "Quality",
+  "term.fields.quality.featured": "Featured",
+  "term.fields.quality.standard": "Standard",
+  "term.fields.quality.draft": "Draft",
+  "term.fields.quality.pending": "Pending",
+  "term.fields.summary.label": "Summary",
+  "term.fields.summary.tooltip":
+    "Shown before the note. Leave empty to use the first paragraph of the note",
+  "term.fields.content_type.label": "Format",
+  "term.fields.redirect.label": "Redirect to",
+  "term.fields.redirect.tooltip":
+    "word or word@tag. For alternative spellings of the same entry: readers are sent to the target",
+  "term.fields.immutable.tooltip":
+    "The word and tag cannot be changed once created. Create a new term and redirect this one to it",
+  "term.message.modified":
+    "Someone else changed this term while you were editing. Reload it and try again",
+  "term.import.result": "Import result",
+  "term.import.summary":
+    "{created} created, {updated} updated, {unchanged} unchanged, {failed} rows skipped",
+  "term.import.reindex_later":
+    "Many changes: the search index will be updated by the weekly rebuild",
+  "term.import.row": "Row",
+  "term.import.reason": "Reason skipped",
+  "term.grammar.not_found": "No grammar note for {word}",
   "term.fields.note.label": "note",
   "term.fields.note.label": "note",
   "term.general-in-studio": "general in studio",
   "term.general-in-studio": "general in studio",
   "labels.resources": "Resources",
   "labels.resources": "Resources",
@@ -149,7 +173,8 @@ const items = {
   "labels.channel.select": "Select version",
   "labels.channel.select": "Select version",
   "labels.teamspace": "Teamspaces",
   "labels.teamspace": "Teamspaces",
   "labels.teamspace.current": "Teamspace: {name}",
   "labels.teamspace.current": "Teamspace: {name}",
-  "labels.teamspace.personal-only": "Personal only — not available in a teamspace",
+  "labels.teamspace.personal-only":
+    "Personal only — not available in a teamspace",
   "labels.teamspace.unsupported": "This module does not support teamspaces yet",
   "labels.teamspace.unsupported": "This module does not support teamspaces yet",
   "labels.group.role.owner": "Owner",
   "labels.group.role.owner": "Owner",
   "labels.group.role.manager": "Manager",
   "labels.group.role.manager": "Manager",

+ 23 - 1
dashboard-v6/src/locales/zh-Hans/label.ts

@@ -14,7 +14,8 @@ const items = {
   "labels.tools": "工具",
   "labels.tools": "工具",
   "labels.link": "链接",
   "labels.link": "链接",
   "labels.library.access.link": "藏经阁访问链接",
   "labels.library.access.link": "藏经阁访问链接",
-  "labels.library.access.tip": "任何获得此链接的人,都可以在藏经阁中阅读该术语。",
+  "labels.library.access.tip":
+    "任何获得此链接的人,都可以在藏经阁中阅读该术语。",
   "labels.studio.access.link": "译经楼访问链接",
   "labels.studio.access.link": "译经楼访问链接",
   "labels.upload": "上传",
   "labels.upload": "上传",
   "labels.first-term": "第一个术语",
   "labels.first-term": "第一个术语",
@@ -147,6 +148,27 @@ const items = {
   "term.fields.meaning.tooltip": "单词的首选意思",
   "term.fields.meaning.tooltip": "单词的首选意思",
   "term.fields.meaning2.label": "其他意思",
   "term.fields.meaning2.label": "其他意思",
   "term.fields.meaning2.tooltip": "其他意思将出现在后面的括号里",
   "term.fields.meaning2.tooltip": "其他意思将出现在后面的括号里",
+  "term.fields.quality.label": "质量",
+  "term.fields.quality.featured": "特色",
+  "term.fields.quality.standard": "标准",
+  "term.fields.quality.draft": "草稿",
+  "term.fields.quality.pending": "待审",
+  "term.fields.summary.label": "摘要",
+  "term.fields.summary.tooltip": "显示在正文前面;不填就用正文第一段",
+  "term.fields.content_type.label": "正文格式",
+  "term.fields.redirect.label": "重定向到",
+  "term.fields.redirect.tooltip":
+    "写成 word 或 word@标签。用于同一词条的不同拼写:读者打开本条时转到目标词条",
+  "term.fields.immutable.tooltip":
+    "词头与标签建立后不能修改。要改请新建一条,再把这一条重定向过去",
+  "term.message.modified": "这条术语在你编辑期间被别人改过了,请重新加载后再改",
+  "term.import.result": "导入结果",
+  "term.import.summary":
+    "新建 {created} 条,修改 {updated} 条,未变 {unchanged} 条,跳过 {failed} 行",
+  "term.import.reindex_later": "改动较多,搜索索引会在每周的全量重建里更新",
+  "term.import.row": "行号",
+  "term.import.reason": "跳过原因",
+  "term.grammar.not_found": "暂无「{word}」的语法说明",
   "term.fields.note.label": "注释",
   "term.fields.note.label": "注释",
   "term.general-in-studio": "通用于本Studio",
   "term.general-in-studio": "通用于本Studio",
   "labels.resources": "资源",
   "labels.resources": "资源",

+ 23 - 1
dashboard-v6/src/locales/zh-Hant/label.ts

@@ -14,7 +14,8 @@ const items = {
   "labels.tools": "工具",
   "labels.tools": "工具",
   "labels.link": "連結",
   "labels.link": "連結",
   "labels.library.access.link": "藏經閣訪問連結",
   "labels.library.access.link": "藏經閣訪問連結",
-  "labels.library.access.tip": "任何獲得此連結的人,都可以在藏經閣中閱讀該術語。",
+  "labels.library.access.tip":
+    "任何獲得此連結的人,都可以在藏經閣中閱讀該術語。",
   "labels.studio.access.link": "譯經樓訪問連結",
   "labels.studio.access.link": "譯經樓訪問連結",
   "labels.upload": "上傳",
   "labels.upload": "上傳",
   "labels.first-term": "第一個術語",
   "labels.first-term": "第一個術語",
@@ -147,6 +148,27 @@ const items = {
   "term.fields.meaning.tooltip": "單詞的首選意思",
   "term.fields.meaning.tooltip": "單詞的首選意思",
   "term.fields.meaning2.label": "其他意思",
   "term.fields.meaning2.label": "其他意思",
   "term.fields.meaning2.tooltip": "其他意思將出現在後面的括號裡",
   "term.fields.meaning2.tooltip": "其他意思將出現在後面的括號裡",
+  "term.fields.quality.label": "品質",
+  "term.fields.quality.featured": "特色",
+  "term.fields.quality.standard": "標準",
+  "term.fields.quality.draft": "草稿",
+  "term.fields.quality.pending": "待審",
+  "term.fields.summary.label": "摘要",
+  "term.fields.summary.tooltip": "顯示在正文前面;不填就用正文第一段",
+  "term.fields.content_type.label": "正文格式",
+  "term.fields.redirect.label": "重新導向到",
+  "term.fields.redirect.tooltip":
+    "寫成 word 或 word@標籤。用於同一詞條的不同拼寫:讀者打開本條時轉到目標詞條",
+  "term.fields.immutable.tooltip":
+    "詞頭與標籤建立後不能修改。要改請新建一條,再把這一條重新導向過去",
+  "term.message.modified": "這條術語在你編輯期間被別人改過了,請重新載入後再改",
+  "term.import.result": "匯入結果",
+  "term.import.summary":
+    "新建 {created} 條,修改 {updated} 條,未變 {unchanged} 條,跳過 {failed} 行",
+  "term.import.reindex_later": "改動較多,搜尋索引會在每週的全量重建裡更新",
+  "term.import.row": "行號",
+  "term.import.reason": "跳過原因",
+  "term.grammar.not_found": "暫無「{word}」的語法說明",
   "term.fields.note.label": "註釋",
   "term.fields.note.label": "註釋",
   "term.general-in-studio": "通用於本Studio",
   "term.general-in-studio": "通用於本Studio",
   "labels.resources": "資源",
   "labels.resources": "資源",

+ 2 - 2
dashboard-v6/src/pages/workspace/term/list.tsx

@@ -3,13 +3,13 @@ import TermList from "../../../components/term/TermList";
 import { useActiveStudio } from "../../../hooks/useActiveStudio";
 import { useActiveStudio } from "../../../hooks/useActiveStudio";
 
 
 const Widget = () => {
 const Widget = () => {
-  const { studioName } = useActiveStudio();
+  const { studioId, studioName } = useActiveStudio();
   const intl = useIntl();
   const intl = useIntl();
 
 
   return (
   return (
     <>
     <>
       <title>{intl.formatMessage({ id: "columns.studio.term.title" })}</title>
       <title>{intl.formatMessage({ id: "columns.studio.term.title" })}</title>
-      <TermList studioName={studioName} />
+      <TermList key={studioId} studioId={studioId} studioName={studioName} />
     </>
     </>
   );
   );
 };
 };

+ 11 - 1
dashboard-v6/src/pages/workspace/term/show.tsx

@@ -1,4 +1,9 @@
-import { useMatches, useNavigate, useParams, useSearchParams } from "react-router";
+import {
+  useMatches,
+  useNavigate,
+  useParams,
+  useSearchParams,
+} from "react-router";
 import { useIntl } from "react-intl";
 import { useIntl } from "react-intl";
 
 
 import TermEditor from "../../../features/editor/Term";
 import TermEditor from "../../../features/editor/Term";
@@ -28,6 +33,11 @@ const Widget = () => {
           newParams.set("channel", channelsParams);
           newParams.set("channel", channelsParams);
           setSearchParams(newParams);
           setSearchParams(newParams);
         }}
         }}
+        onTermSelect={(termId) => {
+          // 点正文里的术语:在当前页打开那条术语,保留所选版本
+          const query = searchParams.toString();
+          navigate(`/workspace/term/${termId}${query ? `?${query}` : ""}`);
+        }}
         onEdit={() => {
         onEdit={() => {
           navigate(`/workspace/term/${id}/edit`);
           navigate(`/workspace/term/${id}/edit`);
         }}
         }}

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików