TermExchangeV3Test.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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 App\Services\V3\TermExchangeService;
  8. use Illuminate\Foundation\Testing\RefreshDatabase;
  9. use Illuminate\Http\UploadedFile;
  10. use PhpOffice\PhpSpreadsheet\IOFactory;
  11. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  12. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  13. uses(RefreshDatabase::class);
  14. /*
  15. * 术语导入 / 导出(xlsx):列表接口带 Accept: xlsx 导出;POST …/terms/imports 导入(部分成功)。
  16. * 这里断言的是形状而非契约(spectator 未安装,见 v3-resource skill 第 3 步)。
  17. */
  18. const XLSX = TermExchangeService::MIME;
  19. /** 生成一个 xlsx 上传文件:第一行是列名 */
  20. function termSheet(array $header, array $rows): UploadedFile
  21. {
  22. $spreadsheet = new Spreadsheet;
  23. $spreadsheet->getActiveSheet()->fromArray([$header, ...$rows], null, 'A1', true);
  24. $path = tempnam(sys_get_temp_dir(), 'terms').'.xlsx';
  25. (new Xlsx($spreadsheet))->save($path);
  26. return new UploadedFile($path, 'terms.xlsx', XLSX, null, true);
  27. }
  28. /** 读回导出的 xlsx:列名 => 值 的行数组 */
  29. function readSheet(string $content): array
  30. {
  31. $path = tempnam(sys_get_temp_dir(), 'export').'.xlsx';
  32. file_put_contents($path, $content);
  33. $rows = IOFactory::load($path)->getActiveSheet()->toArray(null, false, false);
  34. $header = array_shift($rows);
  35. return array_map(fn ($row) => array_combine($header, $row), $rows);
  36. }
  37. function importTo(string $channel, string $as, UploadedFile $file)
  38. {
  39. return test()->post("/api/v3/channels/{$channel}/terms/imports", ['file' => $file], authHeader($as) + ['Accept' => 'application/json']);
  40. }
  41. function existingTerm(string $channel, string $as, array $body = []): array
  42. {
  43. return test()->postJson("/api/v3/channels/{$channel}/terms", $body + ['word' => 'dhamma', 'meaning' => '法'], authHeader($as))
  44. ->assertCreated()->json('data');
  45. }
  46. /* ------------------------------------------------------------------ 导出 */
  47. it('exports the terms of a channel as xlsx with the filters of the list', function () {
  48. $owner = makeStudio('owner');
  49. $channel = makeChannel($owner);
  50. $term = existingTerm($channel, $owner, ['tag' => '义', 'quality' => 'draft', 'note' => '正文 {{category|法义}}']);
  51. existingTerm($channel, $owner, ['word' => 'sīla', 'meaning' => '戒']);
  52. $res = $this->get("/api/v3/channels/{$channel}/terms", ['Accept' => XLSX])->assertOk();
  53. expect($res->headers->get('Content-Type'))->toBe(XLSX);
  54. $rows = readSheet($res->getContent());
  55. expect(array_keys($rows[0]))->toBe(TermExchangeService::COLUMNS)
  56. ->and(array_column($rows, 'word'))->toBe(['dhamma', 'sīla'])
  57. ->and($rows[0])->toMatchArray(['id' => $term['id'], 'tag' => '义', 'quality' => 'draft', 'etag' => $term['etag'], 'channel_id' => $channel]);
  58. $filtered = readSheet($this->get("/api/v3/channels/{$channel}/terms?quality=draft", ['Accept' => XLSX])->getContent());
  59. expect(array_column($filtered, 'word'))->toBe(['dhamma']);
  60. Channel::where('uid', $channel)->update(['status' => Channel::STATUS_PRIVATE]);
  61. $this->get("/api/v3/channels/{$channel}/terms", ['Accept' => XLSX])->assertForbidden();
  62. });
  63. it('exports the terms of a studio for its members only', function () {
  64. [$team, $users] = makeTeam();
  65. existingTerm(makeChannel($team), $users['owner']);
  66. $rows = readSheet($this->get("/api/v3/studios/{$team}/terms", authHeader($users['reader']) + ['Accept' => XLSX])->assertOk()->getContent());
  67. expect(array_column($rows, 'word'))->toBe(['dhamma']);
  68. $this->get("/api/v3/studios/{$team}/terms", authHeader($users['outsider']) + ['Accept' => XLSX])->assertForbidden();
  69. });
  70. /* ------------------------------------------------------------------ 导入 */
  71. it('imports new and changed terms, skipping bad rows with reasons (partial success)', function () {
  72. $owner = makeStudio('owner');
  73. $channel = makeChannel($owner);
  74. $existing = existingTerm($channel, $owner, ['tag' => '义']);
  75. $untouched = existingTerm($channel, $owner, ['word' => 'sīla', 'meaning' => '戒']);
  76. $res = importTo($channel, $owner, termSheet(
  77. ['id', 'word', 'tag', 'meaning', 'note', 'quality', 'etag'],
  78. [
  79. [$existing['id'], 'dhamma', '义', '法(改)', '正文 {{category|律学}}', 'standard', $existing['etag']], // 2 改
  80. [null, 'kamma', null, '业', null, null, null], // 3 新建
  81. [null, 'sīla', null, '戒', null, null, null], // 4 无 id 同 word:内容没变
  82. [null, null, null, '没有词', null, null, null], // 5 word 为空
  83. [$existing['id'], 'dhammā', '义', 'x', null, null, null], // 6 改 word
  84. [null, 'vinaya', null, '律', null, 'great', null], // 7 quality 不对
  85. [null, 'nibbāna', null, null, null, null, null], // 8 新建缺 meaning
  86. ],
  87. ))->assertOk();
  88. expect($res->json('data'))->toMatchArray(['created' => 1, 'updated' => 1, 'unchanged' => 1, 'reindexed' => true])
  89. ->and(array_column($res->json('data.errors'), 'row'))->toBe([5, 6, 7, 8]);
  90. expect(DhammaTerm::find($existing['id']))->meaning->toBe('法(改)')->quality->toBe('standard')->version->toBe(2);
  91. expect(TermCategory::where('term_guid', $existing['id'])->pluck('category')->all())->toBe(['律学']);
  92. expect(DhammaTerm::where('channal', $channel)->where('word', 'kamma')->first())
  93. ->content_type->toBe('markdown-e2')->language->toBe('zh-Hans');
  94. expect(DhammaTerm::find($untouched['id'])->version)->toBe(1);
  95. });
  96. it('skips rows whose term was changed after export (etag)', function () {
  97. $owner = makeStudio('owner');
  98. $channel = makeChannel($owner);
  99. $term = existingTerm($channel, $owner);
  100. $this->patchJson("/api/v3/terms/{$term['id']}", ['meaning' => '别人改的'], authHeader($owner) + ['If-Match' => $term['etag']])->assertOk();
  101. $res = importTo($channel, $owner, termSheet(['id', 'word', 'meaning', 'etag'], [[$term['id'], 'dhamma', '我的', $term['etag']]]));
  102. expect($res->json('data.updated'))->toBe(0)->and($res->json('data.errors.0.row'))->toBe(2);
  103. expect(DhammaTerm::find($term['id'])->meaning)->toBe('别人改的');
  104. // 没有 etag 列(手工做的表)照常覆盖
  105. importTo($channel, $owner, termSheet(['id', 'word', 'meaning'], [[$term['id'], 'dhamma', '覆盖']]))->assertJsonPath('data.updated', 1);
  106. });
  107. it('reads a v2 exported sheet by column names', function () {
  108. $owner = makeStudio('owner');
  109. $channel = makeChannel($owner);
  110. importTo($channel, $owner, termSheet(
  111. ['id', 'word', 'meaning', 'other_meaning', 'note', 'tag', 'language', 'channel_id'],
  112. [[null, 'dhamma', '法', '达摩', '正文', null, 'en', 'ignored']],
  113. ))->assertJsonPath('data.created', 1);
  114. // channel 导入:language / channel_id 列不看,跟随 channel
  115. expect(DhammaTerm::where('channal', $channel)->first())->other_meaning->toBe('达摩')->language->toBe('zh-Hans');
  116. });
  117. it('imports into a studio by channel_id, and needs a language for studio-wide terms', function () {
  118. [$team, $users] = makeTeam();
  119. $channel = makeChannel($team);
  120. $foreign = makeChannel(makeStudio('other'));
  121. $res = $this->post("/api/v3/studios/{$team}/terms/imports", ['file' => termSheet(
  122. ['word', 'meaning', 'language', 'channel_id'],
  123. [
  124. ['in-channel', '甲', null, $channel],
  125. ['general', '乙', 'zh-Hans', null],
  126. ['no-language', '丙', null, null],
  127. ['foreign', '丁', null, $foreign],
  128. ],
  129. )], authHeader($users['owner']) + ['Accept' => 'application/json'])->assertOk();
  130. expect($res->json('data.created'))->toBe(2)->and(array_column($res->json('data.errors'), 'row'))->toBe([4, 5]);
  131. expect(DhammaTerm::where('word', 'in-channel')->value('channal'))->toBe($channel);
  132. expect(DhammaTerm::where('word', 'general')->first())->channal->toBeNull()->owner->toBe($team);
  133. // 团队 editor 不能新建 studio 通用术语,但能写 channel 里的
  134. $res = $this->post("/api/v3/studios/{$team}/terms/imports", ['file' => termSheet(
  135. ['word', 'meaning', 'language', 'channel_id'],
  136. [['by-editor', '戊', null, $channel], ['general-by-editor', '己', 'zh-Hans', null]],
  137. )], authHeader($users['editor']) + ['Accept' => 'application/json'])->assertOk();
  138. expect($res->json('data.created'))->toBe(1)->and($res->json('data.errors.0.row'))->toBe(3);
  139. });
  140. it('rejects importers without write access, AI models, and unreadable files', function () {
  141. $owner = makeStudio('owner');
  142. $channel = makeChannel($owner);
  143. $file = fn () => termSheet(['word', 'meaning'], [['dhamma', '法']]);
  144. $this->post("/api/v3/channels/{$channel}/terms/imports", ['file' => $file()], ['Accept' => 'application/json'])->assertUnauthorized();
  145. importTo($channel, makeStudio('stranger'), $file())->assertForbidden();
  146. $model = AiModel::factory()->ownedBy($owner)->create();
  147. $this->post("/api/v3/channels/{$channel}/terms/imports", ['file' => $file()], [
  148. 'Authorization' => 'Bearer '.AuthService::getUserToken($model->uid), 'Accept' => 'application/json',
  149. ])->assertForbidden();
  150. importTo($channel, $owner, UploadedFile::fake()->createWithContent('terms.xlsx', 'not a spreadsheet'))
  151. ->assertUnprocessable()->assertJsonValidationErrors('file');
  152. importTo($channel, $owner, termSheet(['foo', 'bar'], [['a', 'b']]))
  153. ->assertUnprocessable()->assertJsonValidationErrors('file');
  154. $this->post("/api/v3/channels/{$channel}/terms/imports", [], authHeader($owner) + ['Accept' => 'application/json'])
  155. ->assertUnprocessable()->assertJsonValidationErrors('file');
  156. expect(DhammaTerm::count())->toBe(0);
  157. });