TermV3Test.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. <?php
  2. use App\Models\AiModel;
  3. use App\Models\Channel;
  4. use App\Models\DhammaTerm;
  5. use App\Models\TermCategory;
  6. use App\Services\AuthService;
  7. use Illuminate\Foundation\Testing\RefreshDatabase;
  8. use Illuminate\Support\Facades\DB;
  9. use Illuminate\Support\Str;
  10. uses(RefreshDatabase::class);
  11. /*
  12. * v3 术语:/v3/terms、/v3/channels/{c}/terms、/v3/studios/{s}/terms。
  13. * 这里断言的是形状而非契约(spectator 未安装,见 v3-resource skill 第 3 步)。
  14. */
  15. /** 在 channel 里经 API 建一条术语,返回响应 data */
  16. function newTerm(string $channel, string $as, array $body = []): array
  17. {
  18. return test()->postJson("/api/v3/channels/{$channel}/terms", $body + [
  19. 'word' => 'dhamma', 'meaning' => '法', 'note' => "正文第一段。\n\n第二段。{{category|法义}} {{category|基本教义}}",
  20. ], authHeader($as))->assertCreated()->json('data');
  21. }
  22. function termGrant(string $human, AiModel $model, string $channel, int $book = 0): string
  23. {
  24. return test()->postJson('/api/v3/agent-grants', [
  25. 'ai_model' => $model->uid, 'target_type' => 'channel', 'target_id' => $channel, 'book' => $book,
  26. ], authHeader($human))->assertCreated()->json('data.token');
  27. }
  28. function modelAuth(AiModel $model, ?string $grant = null): array
  29. {
  30. return array_filter([
  31. 'Authorization' => 'Bearer '.AuthService::getUserToken($model->uid),
  32. 'X-Agent-Grant' => $grant,
  33. ]);
  34. }
  35. /* ------------------------------------------------------------------ 建 */
  36. it('creates a term in a channel, extracting categories and defaulting to markdown-e2', function () {
  37. $owner = makeStudio('owner');
  38. $channel = makeChannel($owner);
  39. $data = newTerm($channel, $owner, ['tag' => '十七特征', 'quality' => 'draft', 'summary' => '一句话摘要。']);
  40. expect($data)
  41. ->word->toBe('dhamma')
  42. ->tag->toBe('十七特征')
  43. ->channel_id->toBe($channel)
  44. ->owner_id->toBe($owner)
  45. ->language->toBe('zh-Hans')
  46. ->content_type->toBe('markdown-e2')
  47. ->quality->toBe('draft')
  48. ->categories->toBe(['法义', '基本教义'])
  49. ->summary_text->toBe('一句话摘要。')
  50. ->co_editor->toBeNull()
  51. ->abilities->toBe(['update' => true, 'delete' => true]);
  52. expect($data['editor']['id'])->toBe($owner);
  53. expect($data['body'])->toBeArray()->not->toBeEmpty();
  54. expect(DhammaTerm::find($data['id']))->version->toBe(1)->editor_id->toBeGreaterThan(0);
  55. });
  56. it('never exposes the auto-increment id of term_categories', function () {
  57. $owner = makeStudio('owner');
  58. $channel = makeChannel($owner);
  59. $term = newTerm($channel, $owner);
  60. $ids = TermCategory::where('term_guid', $term['id'])->pluck('id')->all();
  61. expect($ids)->toHaveCount(2);
  62. $responses = [
  63. $this->getJson("/api/v3/terms/{$term['id']}")->json('data'),
  64. $this->getJson("/api/v3/channels/{$channel}/terms")->json('data.0'),
  65. $this->getJson('/api/v3/terms?word=dhamma&with_body=1')->json('data.0'),
  66. ];
  67. foreach ($responses as $data) {
  68. // 分类只以名字出现,没有对象、没有 id
  69. expect($data['categories'])->toBe(['法义', '基本教义']);
  70. foreach ($ids as $id) {
  71. expect(json_encode($data))->not->toMatch('/"id":\s*'.$id.'\b/');
  72. }
  73. }
  74. });
  75. it('rejects a duplicate word@tag in the same channel, treating an empty tag as none', function () {
  76. $owner = makeStudio('owner');
  77. $channel = makeChannel($owner);
  78. newTerm($channel, $owner);
  79. $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'dhamma', 'tag' => '', 'meaning' => '又一个'], authHeader($owner))
  80. ->assertStatus(409)
  81. ->assertJsonPath('type', fn ($type) => str_contains($type, 'term-exists'));
  82. $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'dhamma', 'tag' => '另一义', 'meaning' => '又一个'], authHeader($owner))
  83. ->assertCreated();
  84. });
  85. it('validates term input', function () {
  86. $owner = makeStudio('owner');
  87. $channel = makeChannel($owner);
  88. $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x'], authHeader($owner))
  89. ->assertUnprocessable()->assertJsonValidationErrors('meaning');
  90. $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x', 'meaning' => 'y', 'tag' => 'a@b'], authHeader($owner))
  91. ->assertUnprocessable()->assertJsonValidationErrors('tag');
  92. $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x', 'meaning' => 'y', 'quality' => 'great'], authHeader($owner))
  93. ->assertUnprocessable()->assertJsonValidationErrors('quality');
  94. $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x', 'meaning' => 'y', 'language' => 'en'], authHeader($owner))
  95. ->assertUnprocessable()->assertJsonValidationErrors('language');
  96. $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x', 'meaning' => 'y', 'redirect' => 'x'], authHeader($owner))
  97. ->assertUnprocessable()->assertJsonValidationErrors('redirect');
  98. $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x', 'meaning' => 'y'])->assertUnauthorized();
  99. });
  100. it('lets team editors and above create terms in a team channel', function () {
  101. [$team, $users] = makeTeam();
  102. $channel = makeChannel($team);
  103. foreach (['owner', 'manager', 'editor'] as $role) {
  104. newTerm($channel, $users[$role], ['word' => "w-{$role}"]);
  105. }
  106. foreach (['reader', 'outsider'] as $role) {
  107. $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'x', 'meaning' => 'y'], authHeader($users[$role]))
  108. ->assertForbidden();
  109. }
  110. expect(DhammaTerm::where('channal', $channel)->value('owner'))->toBe($team);
  111. });
  112. it('creates studio-level terms for owners and managers, and lets editors update them', function () {
  113. [$team, $users] = makeTeam();
  114. $body = ['word' => 'sīla', 'meaning' => '戒', 'language' => 'zh-Hans'];
  115. $this->postJson("/api/v3/studios/{$team}/terms", $body, authHeader($users['editor']))->assertForbidden();
  116. $created = $this->postJson("/api/v3/studios/{$team}/terms", $body, authHeader($users['manager']))
  117. ->assertCreated()
  118. ->assertJsonPath('data.channel_id', null)
  119. ->json('data');
  120. $this->patchJson("/api/v3/terms/{$created['id']}", ['meaning' => '戒律'], authHeader($users['editor']) + ['If-Match' => $created['etag']])
  121. ->assertOk()->assertJsonPath('data.meaning', '戒律');
  122. $this->patchJson("/api/v3/terms/{$created['id']}", ['meaning' => 'x'], authHeader($users['reader']) + ['If-Match' => 'x'])
  123. ->assertForbidden();
  124. });
  125. /* ------------------------------------------------------------------ 读 */
  126. it('shows a term with ETag, and hides terms of private channels', function () {
  127. $owner = makeStudio('owner');
  128. $channel = makeChannel($owner);
  129. $term = newTerm($channel, $owner);
  130. $res = $this->getJson("/api/v3/terms/{$term['id']}")->assertOk();
  131. expect($res->headers->get('ETag'))->toBe($term['etag']);
  132. expect($res->json('data.abilities'))->toBe(['update' => false, 'delete' => false]);
  133. expect($res->json('data.summary_text'))->toBe('正文第一段。');
  134. Channel::where('uid', $channel)->update(['status' => Channel::STATUS_PRIVATE]);
  135. $this->getJson("/api/v3/terms/{$term['id']}")->assertForbidden();
  136. $this->getJson("/api/v3/terms/{$term['id']}", authHeader($owner))->assertOk();
  137. $this->getJson('/api/v3/terms/'.Str::uuid())->assertNotFound();
  138. });
  139. it('renders the body against the requested channels, ignoring those the viewer cannot see', function () {
  140. $owner = makeStudio('owner');
  141. $home = makeChannel($owner, 'home');
  142. $other = makeChannel($owner, 'other');
  143. $private = makeChannel($owner, 'private');
  144. Channel::where('uid', $private)->update(['status' => Channel::STATUS_PRIVATE]);
  145. newTerm($home, $owner, ['word' => 'citta', 'meaning' => '本版心']);
  146. newTerm($other, $owner, ['word' => 'citta', 'meaning' => '他版心']);
  147. newTerm($private, $owner, ['word' => 'citta', 'meaning' => '私有心']);
  148. $term = newTerm($home, $owner, ['word' => 'host', 'note' => '见[[citta]]。']);
  149. $text = fn (array $res) => json_encode($res['data']['body'], JSON_UNESCAPED_UNICODE);
  150. expect($text($this->getJson("/api/v3/terms/{$term['id']}")->json()))->toContain('本版心');
  151. expect($text($this->getJson("/api/v3/terms/{$term['id']}?channels={$other}")->json()))->toContain('他版心');
  152. // 看不见的 channel 被忽略,退回术语所在 channel
  153. expect($text($this->getJson("/api/v3/terms/{$term['id']}?channels={$private}")->json()))->toContain('本版心');
  154. expect($text($this->getJson("/api/v3/terms/{$term['id']}?channels={$private}", authHeader($owner))->json()))->toContain('私有心');
  155. $this->getJson("/api/v3/terms/{$term['id']}?mode=edit")->assertOk();
  156. // format=html:正文换成新渲染器的 HTML 字符串
  157. $html = $this->getJson("/api/v3/terms/{$term['id']}?format=html")->assertOk()->json('data');
  158. expect($html)->not->toHaveKey('body');
  159. expect($html['html'])->toContain('class="term-ref"')->toContain('本版心');
  160. $this->getJson("/api/v3/terms/{$term['id']}?format=pdf")->assertUnprocessable()->assertJsonValidationErrors('format');
  161. $this->getJson("/api/v3/terms/{$term['id']}?mode=write")->assertUnprocessable()->assertJsonValidationErrors('mode');
  162. $this->getJson("/api/v3/terms/{$term['id']}?channels=nope")->assertUnprocessable()->assertJsonValidationErrors('channels');
  163. });
  164. it('lists the terms of a channel with filters', function () {
  165. $owner = makeStudio('owner');
  166. $channel = makeChannel($owner);
  167. newTerm($channel, $owner, ['word' => 'a', 'quality' => 'featured']);
  168. newTerm($channel, $owner, ['word' => 'b', 'note' => '{{category|律学}}']);
  169. $this->getJson("/api/v3/channels/{$channel}/terms?order=word")
  170. ->assertOk()->assertJsonPath('meta.total', 2)->assertJsonPath('data.*.word', ['a', 'b']);
  171. $this->getJson("/api/v3/channels/{$channel}/terms?quality=featured")->assertJsonPath('data.*.word', ['a']);
  172. $this->getJson("/api/v3/channels/{$channel}/terms?quality=pending")->assertJsonPath('data.*.word', ['b']);
  173. $this->getJson("/api/v3/channels/{$channel}/terms?category=".urlencode('律学'))->assertJsonPath('data.*.word', ['b']);
  174. $this->getJson("/api/v3/channels/{$channel}/terms?search=A")->assertJsonPath('data.*.word', ['a']);
  175. $this->getJson("/api/v3/channels/{$channel}/terms?quality=great")->assertUnprocessable();
  176. Channel::where('uid', $channel)->update(['status' => Channel::STATUS_PRIVATE]);
  177. $this->getJson("/api/v3/channels/{$channel}/terms")->assertForbidden();
  178. });
  179. it('lists the terms of a studio for its members only', function () {
  180. [$team, $users] = makeTeam();
  181. newTerm(makeChannel($team), $users['owner'], ['word' => 'in-channel']);
  182. $this->postJson("/api/v3/studios/{$team}/terms", ['word' => 'general', 'meaning' => 'g', 'language' => 'zh-Hans'], authHeader($users['owner']))->assertCreated();
  183. $this->getJson("/api/v3/studios/{$team}/terms?order=word", authHeader($users['reader']))
  184. ->assertOk()->assertJsonPath('data.*.word', ['general', 'in-channel']);
  185. $this->getJson("/api/v3/studios/{$team}/terms?general=1", authHeader($users['reader']))
  186. ->assertJsonPath('data.*.word', ['general']);
  187. $this->getJson("/api/v3/studios/{$team}/terms?general=true", authHeader($users['reader']))
  188. ->assertJsonPath('data.*.word', ['general']);
  189. $this->getJson("/api/v3/studios/{$team}/terms?general=false&order=word", authHeader($users['reader']))
  190. ->assertJsonPath('data.*.word', ['general', 'in-channel']);
  191. $this->getJson("/api/v3/studios/{$team}/terms", authHeader($users['outsider']))->assertForbidden();
  192. $this->getJson("/api/v3/studios/{$team}/terms")->assertUnauthorized();
  193. });
  194. it('looks terms up by word across visible channels only', function () {
  195. $owner = makeStudio('owner');
  196. $public = makeChannel($owner, 'public');
  197. $private = makeChannel($owner, 'private');
  198. Channel::where('uid', $private)->update(['status' => Channel::STATUS_PRIVATE]);
  199. newTerm($public, $owner, ['word' => 'citta', 'meaning' => '心']);
  200. newTerm($private, $owner, ['word' => 'citta', 'meaning' => '心(私有)']);
  201. newTerm($public, $owner, ['word' => 'citta', 'tag' => '十七特征', 'meaning' => '心(特征)']);
  202. $this->getJson('/api/v3/terms?word=citta')->assertOk()->assertJsonPath('meta.total', 2);
  203. $this->getJson('/api/v3/terms?word=citta', authHeader($owner))->assertJsonPath('meta.total', 3);
  204. $this->getJson('/api/v3/terms?word=citta&tag='.urlencode('十七特征'))->assertJsonPath('data.*.meaning', ['心(特征)']);
  205. $this->getJson('/api/v3/terms?word=citta&tag=')->assertJsonPath('data.*.meaning', ['心']);
  206. $this->getJson('/api/v3/terms')->assertUnprocessable()->assertJsonValidationErrors('word');
  207. // 默认不带正文;with_body 时每条都带,并带上 channel 名字
  208. expect($this->getJson('/api/v3/terms?word=citta')->json('data.0'))->not->toHaveKey('body');
  209. // 查询串里的 true / false(v6 发的就是它们),不能 422,false 也不能当真
  210. expect($this->getJson('/api/v3/terms?word=citta&with_body=false')->assertOk()->json('data.0'))->not->toHaveKey('body');
  211. $this->getJson('/api/v3/terms?word=citta&with_body=true')->assertOk()->assertJsonPath('data.0.body', fn ($body) => is_array($body) && $body !== []);
  212. $this->getJson('/api/v3/terms?word=citta&with_body=1')
  213. ->assertJsonPath('data.0.body', fn ($body) => is_array($body) && $body !== [])
  214. ->assertJsonPath('data.0.channel.name', 'public');
  215. });
  216. it('loads a page of terms with a constant number of queries', function () {
  217. $owner = makeStudio('owner');
  218. $count = function (int $n) use ($owner) {
  219. $channel = makeChannel($owner, "c{$n}");
  220. foreach (range(1, $n) as $i) {
  221. newTerm($channel, $owner, ['word' => "w{$i}"]);
  222. }
  223. DB::flushQueryLog();
  224. DB::enableQueryLog();
  225. $this->getJson("/api/v3/channels/{$channel}/terms", authHeader($owner))->assertOk();
  226. $queries = count(DB::getQueryLog());
  227. DB::disableQueryLog();
  228. return $queries;
  229. };
  230. expect($count(8))->toBe($count(2));
  231. });
  232. /* ------------------------------------------------------------------ 改:乐观锁、word/tag 不可改 */
  233. it('requires If-Match, rejects a stale one, and bumps the version', function () {
  234. $owner = makeStudio('owner');
  235. $term = newTerm(makeChannel($owner), $owner);
  236. $url = "/api/v3/terms/{$term['id']}";
  237. $this->patchJson($url, ['meaning' => '新释义'], authHeader($owner))->assertStatus(428);
  238. $this->patchJson($url, ['meaning' => '新释义'], authHeader($owner) + ['If-Match' => '"9.9"'])
  239. ->assertStatus(412)->assertJsonPath('etag', $term['etag']);
  240. $updated = $this->patchJson($url, ['meaning' => '新释义'], authHeader($owner) + ['If-Match' => $term['etag']])
  241. ->assertOk()->assertJsonPath('data.meaning', '新释义')->json('data');
  242. expect($updated['etag'])->not->toBe($term['etag']);
  243. expect(DhammaTerm::find($term['id'])->version)->toBe(2);
  244. // 用旧的 etag 再改一次:412
  245. $this->patchJson($url, ['meaning' => '再改'], authHeader($owner) + ['If-Match' => $term['etag']])->assertStatus(412);
  246. });
  247. it('notices changes made through v2, which only touch modify_time', function () {
  248. $owner = makeStudio('owner');
  249. $term = newTerm(makeChannel($owner), $owner);
  250. DhammaTerm::where('guid', $term['id'])->update(['modify_time' => DB::raw('modify_time + 1'), 'meaning' => 'v2 改的']);
  251. $this->patchJson("/api/v3/terms/{$term['id']}", ['meaning' => 'v3'], authHeader($owner) + ['If-Match' => $term['etag']])
  252. ->assertStatus(412);
  253. });
  254. it('never lets word or tag change, and re-extracts categories when the note changes', function () {
  255. $owner = makeStudio('owner');
  256. $term = newTerm(makeChannel($owner), $owner);
  257. $url = "/api/v3/terms/{$term['id']}";
  258. $this->patchJson($url, ['word' => 'other'], authHeader($owner) + ['If-Match' => $term['etag']])
  259. ->assertUnprocessable()->assertJsonValidationErrors('word');
  260. $this->patchJson($url, ['tag' => 'x'], authHeader($owner) + ['If-Match' => $term['etag']])
  261. ->assertUnprocessable()->assertJsonValidationErrors('tag');
  262. $this->patchJson($url, ['note' => '{{category|律学}}', 'redirect' => 'dhamma@新义'], authHeader($owner) + ['If-Match' => $term['etag']])
  263. ->assertOk()
  264. ->assertJsonPath('data.categories', ['律学'])
  265. ->assertJsonPath('data.redirect', 'dhamma@新义');
  266. expect(TermCategory::where('term_guid', $term['id'])->pluck('category')->all())->toBe(['律学']);
  267. });
  268. it('keeps the language of a channel term tied to the channel', function () {
  269. $owner = makeStudio('owner');
  270. $term = newTerm(makeChannel($owner), $owner);
  271. $this->patchJson("/api/v3/terms/{$term['id']}", ['language' => 'en'], authHeader($owner) + ['If-Match' => $term['etag']])
  272. ->assertUnprocessable()->assertJsonValidationErrors('language');
  273. });
  274. /* ------------------------------------------------------------------ agent 代写 */
  275. it('records the grantor as editor and the model as co-editor, and clears it when a person edits', function () {
  276. $human = makeStudio('owner');
  277. $channel = makeChannel($human);
  278. $model = AiModel::factory()->ownedBy($human)->create();
  279. $grant = termGrant($human, $model, $channel);
  280. $term = $this->postJson("/api/v3/channels/{$channel}/terms", ['word' => 'kamma', 'meaning' => '业'], modelAuth($model, $grant))
  281. ->assertCreated()
  282. ->assertJsonPath('data.editor.id', $human)
  283. ->assertJsonPath('data.co_editor.id', $model->uid)
  284. ->json('data');
  285. $edited = $this->patchJson("/api/v3/terms/{$term['id']}", ['meaning' => '业力'], modelAuth($model, $grant) + ['If-Match' => $term['etag']])
  286. ->assertOk()->assertJsonPath('data.co_editor.id', $model->uid)->json('data');
  287. $this->patchJson("/api/v3/terms/{$term['id']}", ['meaning' => '業'], authHeader($human) + ['If-Match' => $edited['etag']])
  288. ->assertOk()->assertJsonPath('data.co_editor', null);
  289. });
  290. it('rejects agent writes without a covering grant, studio-level agent writes, and agent deletes', function () {
  291. $human = makeStudio('owner');
  292. $channel = makeChannel($human);
  293. $other = makeChannel($human, 'other');
  294. $model = AiModel::factory()->ownedBy($human)->create();
  295. $body = ['word' => 'kamma', 'meaning' => '业'];
  296. $this->postJson("/api/v3/channels/{$channel}/terms", $body, modelAuth($model))->assertForbidden();
  297. $this->postJson("/api/v3/channels/{$channel}/terms", $body, modelAuth($model, termGrant($human, $model, $other)))->assertForbidden();
  298. // 按 book 限定的授权不覆盖术语(术语不属于某本书)
  299. $this->postJson("/api/v3/channels/{$channel}/terms", $body, modelAuth($model, termGrant($human, $model, $channel, 3)))->assertForbidden();
  300. $this->postJson("/api/v3/studios/{$human}/terms", $body + ['language' => 'zh-Hans'], modelAuth($model, termGrant($human, $model, $channel)))
  301. ->assertForbidden();
  302. $term = newTerm($channel, $human);
  303. $this->deleteJson("/api/v3/terms/{$term['id']}", [], modelAuth($model))->assertForbidden();
  304. });
  305. /* ------------------------------------------------------------------ 删 */
  306. it('soft deletes for the owner or team owner only', function () {
  307. [$team, $users] = makeTeam();
  308. $term = newTerm(makeChannel($team), $users['editor']);
  309. $url = "/api/v3/terms/{$term['id']}";
  310. $this->deleteJson($url, [], authHeader($users['editor']))->assertForbidden();
  311. $this->deleteJson($url, [], authHeader($users['manager']))->assertForbidden();
  312. $this->deleteJson($url, [], authHeader($users['owner']))
  313. ->assertOk()->assertJsonPath('data.id', $term['id'])
  314. ->assertJsonPath('data.deleted_at', fn ($at) => $at !== null);
  315. $this->assertSoftDeleted('dhamma_terms', ['guid' => $term['id']]);
  316. $this->getJson($url)->assertNotFound();
  317. });