2
0

TermService.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Exceptions\BusinessException;
  4. use App\Facades\RedisCache;
  5. use App\Models\Channel;
  6. use App\Models\DhammaTerm;
  7. use App\Models\TermCategory;
  8. use App\Services\Markup\Format;
  9. use App\Services\Markup\MarkupService;
  10. use App\Services\Markup\RenderOptions;
  11. use App\Services\OpenSearchService;
  12. use App\Services\TermIndexService;
  13. use App\Services\UserService;
  14. use App\Tools\Tools;
  15. use Illuminate\Auth\Access\AuthorizationException;
  16. use Illuminate\Contracts\Pagination\LengthAwarePaginator;
  17. use Illuminate\Database\Eloquent\Builder;
  18. use Illuminate\Database\Eloquent\Collection as EloquentCollection;
  19. use Illuminate\Support\Collection;
  20. use Illuminate\Support\Facades\DB;
  21. use Illuminate\Support\Facades\Log;
  22. use Illuminate\Support\Str;
  23. use Illuminate\Validation\ValidationException;
  24. /**
  25. * 术语 / 百科词条(只给 v3 用):查看、按 channel / studio 列出、按词查、建、改、删。
  26. *
  27. * 取代 v2 `DhammaTermController`(show、index 的 channel / studio / word、store、update、destroy)。
  28. * v2 那份原地保留不动(铁律 2),不共用代码。
  29. *
  30. * 权限:
  31. * - 挂在 channel 下的术语跟 channel 走({@see ChannelAbilityService}):能读 channel 就能读,能写 channel 内容就能建、改
  32. * - studio 级术语(channal 为空,owner 名下所有 channel 共用):谁都能读;建要 owner 的 create,改要 update
  33. * ({@see GroupAbilityService}:团队 owner / manager 能建,editor 也能改)
  34. * - 删:owner 本人或团队 owner(GroupAbilityService 的 delete);只给人类
  35. *
  36. * 写入方(`$actor`)由 {@see AgentGrantService::actor()} 给出:AI 模型凭人类授权代写时 editor 是授权人、
  37. * co_editor 是模型,权限按 editor 判,且只能写授权覆盖的 channel(按 book 限定的授权不覆盖术语)。
  38. *
  39. * 分类不是入参:写入时从正文的 `{{category|…}}` 抽出存进 term_categories(内容多由 LLM 生成,分类不做限制)。
  40. * word + tag 建立后不准改(引用方写 `[[word@tag]]`),要改就新建一条、把旧的 redirect 过去。
  41. * 修改带乐观锁:If-Match 必须等于当前 ETag({@see DhammaTerm::etag()}),否则 412;不带 428。
  42. */
  43. class TermService
  44. {
  45. /** 列表可排序的字段 */
  46. public const ORDERS = ['updated_at', 'created_at', 'word'];
  47. /** 改了这些字段算「改内容」:co_editor 跟着这次写入走(人改清空、AI 改换成该模型) */
  48. private const CONTENT_FIELDS = ['meaning', 'other_meaning', 'note', 'summary', 'quality', 'content_type', 'redirect', 'language'];
  49. /** @var array<string, array<string, bool>> 请求内缓存:用户|owner → 能力 */
  50. private array $groupAbilities = [];
  51. public function __construct(
  52. private readonly ChannelAbilityService $channels,
  53. private readonly GroupAbilityService $groups,
  54. private readonly AgentGrantService $agents,
  55. private readonly MarkupService $markup,
  56. private readonly UserService $users,
  57. ) {}
  58. /* ------------------------------------------------------------------ 读 */
  59. /**
  60. * 单条,带渲染后的正文(摘要 + 正文)。
  61. *
  62. * 正文默认按术语所在 channel 解析模板;$render 可以指定按哪些 channel 解析(阅读器右栏选版本)
  63. * 与 read / edit 模式。指定的 channel 只认查看者看得见的,一个都看不见就退回术语所在 channel。
  64. * format=html 时正文输出 HTML(挂在 html 上,给用 WebView 显示的客户端),否则输出节点树(body)。
  65. *
  66. * @param array{channels?: list<string>, mode?: string, format?: string} $render
  67. *
  68. * @throws AuthorizationException 看不见
  69. */
  70. public function show(DhammaTerm $term, ?string $viewerUid, array $render = []): DhammaTerm
  71. {
  72. $abilities = $this->abilitiesMany(collect([$term]), $viewerUid)[$term->guid];
  73. if (! $abilities['read']) {
  74. throw new AuthorizationException(__('messages.term_forbidden'));
  75. }
  76. $this->loadRelations(new EloquentCollection([$term]));
  77. $this->decorate(collect([$term]), $viewerUid, withBody: true, render: [
  78. 'channels' => $this->readableChannels($render['channels'] ?? [], $viewerUid),
  79. 'mode' => $render['mode'] ?? 'read',
  80. 'format' => $render['format'] ?? 'tree',
  81. ]);
  82. return $term;
  83. }
  84. /**
  85. * 这些 channel 里查看者看得见的,保持传入顺序。
  86. *
  87. * @param list<string> $uids
  88. * @return list<string>
  89. */
  90. private function readableChannels(array $uids, ?string $viewerUid): array
  91. {
  92. if ($uids === []) {
  93. return [];
  94. }
  95. $channels = Channel::whereIn('uid', $uids)->get(['uid', 'owner_uid', 'status', 'is_system']);
  96. $abilities = $this->channels->abilitiesMany($channels, $viewerUid);
  97. return array_values(array_filter($uids, fn (string $uid) => $abilities[$uid]['read'] ?? false));
  98. }
  99. /**
  100. * 某个 channel 的术语。
  101. *
  102. * @param array{search?: string|null, quality?: string, category?: string, order?: string, dir?: string} $filters
  103. * @return LengthAwarePaginator<int, DhammaTerm>
  104. *
  105. * @throws AuthorizationException 看不见这个 channel
  106. */
  107. public function listInChannel(Channel $channel, array $filters, ?string $viewerUid, int $perPage): LengthAwarePaginator
  108. {
  109. return $this->paginate($this->channelQuery($channel, $viewerUid), $filters, $viewerUid, $perPage);
  110. }
  111. /**
  112. * 某个 channel 的术语查询(列表、导出共用)。
  113. *
  114. * @return Builder<DhammaTerm>
  115. *
  116. * @throws AuthorizationException 看不见这个 channel
  117. */
  118. public function channelQuery(Channel $channel, ?string $viewerUid): Builder
  119. {
  120. if (! $this->channels->abilities($channel, $viewerUid)['read']) {
  121. throw new AuthorizationException(__('messages.channel_forbidden'));
  122. }
  123. return DhammaTerm::query()->where('channal', $channel->uid);
  124. }
  125. /**
  126. * 某个 studio(本人或团队)名下的术语:它的 channel 里的与 studio 级的。`general=true` 只要 studio 级的。
  127. *
  128. * @param array{search?: string|null, quality?: string, category?: string, general?: bool, order?: string, dir?: string} $filters
  129. * @return LengthAwarePaginator<int, DhammaTerm>
  130. *
  131. * @throws AuthorizationException 不是本人,也不是这个团队的成员
  132. */
  133. public function listInStudio(string $studioUid, array $filters, string $viewerUid, int $perPage): LengthAwarePaginator
  134. {
  135. return $this->paginate($this->studioQuery($studioUid, $filters, $viewerUid), $filters, $viewerUid, $perPage);
  136. }
  137. /**
  138. * 某个 studio 名下术语的查询(列表、导出共用)。`general=true` 只要 studio 级的。
  139. *
  140. * @param array{general?: bool} $filters
  141. * @return Builder<DhammaTerm>
  142. *
  143. * @throws AuthorizationException 不是本人,也不是这个团队的成员
  144. */
  145. public function studioQuery(string $studioUid, array $filters, string $viewerUid): Builder
  146. {
  147. if (! $this->groups->can($viewerUid, $studioUid, GroupAbilityService::READ)) {
  148. throw new AuthorizationException(__('messages.channel_studio_forbidden'));
  149. }
  150. $query = DhammaTerm::query()->where('owner', $studioUid);
  151. if (! empty($filters['general'])) {
  152. $query->studioLevel();
  153. }
  154. return $query;
  155. }
  156. /**
  157. * 列表的过滤与排序(不分页),导出用。
  158. *
  159. * @param Builder<DhammaTerm> $query
  160. * @param array<string, mixed> $filters
  161. * @return Builder<DhammaTerm>
  162. */
  163. public function filtered(Builder $query, array $filters): Builder
  164. {
  165. $this->applyFilters($query, $filters);
  166. return $query->orderBy('word')->orderBy('guid');
  167. }
  168. /**
  169. * 按词查:这些词在所有看得见的 channel 与 studio 级术语里的词条(编辑时看同词的其它义项、社区译法)。
  170. *
  171. * `with_body` 时每条都带渲染后的正文(同一个词通常只有几条)。
  172. *
  173. * @param array{word: string, tag?: string|null, channel?: string, language?: string, with_body?: bool} $filters
  174. * @return LengthAwarePaginator<int, DhammaTerm>
  175. */
  176. public function lookup(array $filters, ?string $viewerUid, int $perPage): LengthAwarePaginator
  177. {
  178. $words = array_values(array_filter(array_map('trim', explode(',', $filters['word']))));
  179. $query = DhammaTerm::query()->whereIn('word', $words);
  180. if (array_key_exists('tag', $filters)) {
  181. $this->whereTag($query, $filters['tag']);
  182. }
  183. if (! empty($filters['channel'])) {
  184. $query->where('channal', $filters['channel']);
  185. }
  186. if (! empty($filters['language'])) {
  187. $query->where('language', $filters['language']);
  188. }
  189. // 看得见的:studio 级术语,或所在 channel 会被列出给查看者
  190. $query->where(function (Builder $q) use ($viewerUid) {
  191. $q->studioLevel()->orWhereIn('channal', function ($sub) use ($viewerUid) {
  192. $sub->selectRaw('uid::text')->from('channels')->whereNull('deleted_at');
  193. $this->channels->scopeListable($sub, $viewerUid);
  194. });
  195. });
  196. return $this->paginate($query, ['order' => 'updated_at'] + $filters, $viewerUid, $perPage, ! empty($filters['with_body']));
  197. }
  198. /* ------------------------------------------------------------------ 写 */
  199. /**
  200. * 在 channel 里新建。owner 与语言跟 channel。
  201. *
  202. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  203. * @param array<string, mixed> $data
  204. *
  205. * @throws AuthorizationException
  206. * @throws BusinessException 同一 channel 里已有这个 word@tag(409)
  207. */
  208. public function createInChannel(Channel $channel, array $actor, array $data): DhammaTerm
  209. {
  210. if (! $this->agents->covers($actor['scope'], $channel->uid, null)
  211. || ! $this->channels->abilities($channel, $actor['editor'])['write']) {
  212. throw new AuthorizationException(__('messages.term_forbidden'));
  213. }
  214. $this->guardUnique(DhammaTerm::query()->where('channal', $channel->uid), $data);
  215. return $this->create($actor, $data + [
  216. 'channel' => $channel->uid,
  217. 'owner' => $channel->owner_uid,
  218. 'language' => $channel->lang,
  219. ]);
  220. }
  221. /**
  222. * 在 studio 名下新建 studio 级术语(不属于任何 channel)。只给人类:agent 授权只覆盖 channel。
  223. *
  224. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  225. * @param array<string, mixed> $data
  226. *
  227. * @throws AuthorizationException
  228. * @throws BusinessException 同一 studio、同一语言已有这个 word@tag(409)
  229. */
  230. public function createInStudio(string $studioUid, array $actor, array $data): DhammaTerm
  231. {
  232. if ($actor['scope'] !== null || ! $this->groups->can($actor['editor'], $studioUid, GroupAbilityService::CREATE)) {
  233. throw new AuthorizationException(__('messages.term_forbidden'));
  234. }
  235. $this->guardUnique(
  236. DhammaTerm::query()->where('owner', $studioUid)->studioLevel()->where('language', $data['language']),
  237. $data,
  238. );
  239. return $this->create($actor, $data + ['channel' => null, 'owner' => $studioUid]);
  240. }
  241. /**
  242. * 改(只改传了的字段)。word / tag 不准改(FormRequest 已拦)。带乐观锁:$ifMatch 必须等于当前 ETag。
  243. *
  244. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  245. * @param array<string, mixed> $data
  246. *
  247. * @throws AuthorizationException
  248. * @throws BusinessException 428 没带 If-Match;412 这条在你编辑期间被改过
  249. * @throws ValidationException
  250. */
  251. public function update(DhammaTerm $term, array $actor, array $data, ?string $ifMatch): DhammaTerm
  252. {
  253. if (! $this->agents->covers($actor['scope'], $term->channelUid(), null) || ! $this->can($term, $actor['editor'], 'update')) {
  254. throw new AuthorizationException(__('messages.term_forbidden'));
  255. }
  256. if ($ifMatch === null || $ifMatch === '') {
  257. throw new BusinessException(__('messages.term_if_match_required'), 428, 'precondition-required', [], 'Precondition Required');
  258. }
  259. if ($term->channelUid() !== null && array_key_exists('language', $data)) {
  260. throw ValidationException::withMessages(['language' => __('messages.term_language_follows_channel')]);
  261. }
  262. $this->guardRedirect($term->word, $term->tag, $data);
  263. $changes = array_intersect_key($data, array_flip(self::CONTENT_FIELDS));
  264. if (array_key_exists('note', $changes) || array_key_exists('content_type', $changes)) {
  265. $changes['content_type'] ??= $term->effectiveContentType();
  266. }
  267. $etag = $term->etag();
  268. if ($ifMatch !== $etag) {
  269. throw $this->modified($term);
  270. }
  271. if (! $this->applyChanges($term, $actor, $changes)) {
  272. throw $this->modified($term->fresh() ?? $term);
  273. }
  274. return $this->show($term->fresh(), $actor['editor']);
  275. }
  276. /**
  277. * 写入修改(比较并交换:版本与 modify_time 都没变才写),改了 note 就重抽分类,写完清缓存。
  278. * 不查权限、不渲染——由调用方负责(单条修改、导入共用)。$index=false 时不立即重建搜索索引。
  279. *
  280. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  281. * @param array<string, mixed> $changes 只含要改的内容字段
  282. * @return bool 在别人之后写的(期间被改过)返回 false,什么都没写
  283. */
  284. public function applyChanges(DhammaTerm $term, array $actor, array $changes, bool $index = true): bool
  285. {
  286. $changed = DB::transaction(function () use ($term, $actor, $changes) {
  287. $updates = $changes + [
  288. 'editor_uid' => $actor['editor'],
  289. 'editor_id' => $this->users->intIdByUuid($actor['editor']) ?? 0,
  290. 'co_editor_uid' => $actor['co_editor'],
  291. 'modify_time' => time() * 1000,
  292. 'version' => (int) $term->version + 1,
  293. 'updated_at' => now(),
  294. ];
  295. // 比较并交换:版本与 modify_time 都没变才写(v2 的修改只动 modify_time)
  296. $affected = DhammaTerm::query()
  297. ->where('guid', $term->guid)
  298. ->where('version', (int) $term->version)
  299. ->where('modify_time', (int) $term->modify_time)
  300. ->update($updates);
  301. if ($affected === 0) {
  302. return false;
  303. }
  304. if (array_key_exists('note', $changes)) {
  305. $this->syncCategories($term->guid, $changes['note']);
  306. }
  307. return true;
  308. });
  309. if ($changed) {
  310. $this->afterWrite($term->fresh(), $index);
  311. }
  312. return $changed;
  313. }
  314. /**
  315. * 软删除,返回被删的术语(AIP-164)。分类留着,恢复时还在。
  316. *
  317. * @throws AuthorizationException
  318. */
  319. public function delete(DhammaTerm $term, string $actorUid): DhammaTerm
  320. {
  321. $this->agents->assertHuman($actorUid);
  322. if (! $this->can($term, $actorUid, 'delete')) {
  323. throw new AuthorizationException(__('messages.term_forbidden'));
  324. }
  325. $term->delete();
  326. $this->forgetCache($term);
  327. try {
  328. app(OpenSearchService::class)->delete("term_{$term->guid}");
  329. } catch (\Throwable $e) {
  330. Log::warning('Failed to remove deleted term from index', ['guid' => $term->guid, 'error' => $e->getMessage()]);
  331. }
  332. $this->loadRelations(new EloquentCollection([$term]));
  333. $this->decorate(collect([$term]), $actorUid, withBody: false);
  334. return $term;
  335. }
  336. /* ------------------------------------------------------------------ 权限 */
  337. /**
  338. * 本人对这批术语能做什么。channel 的能力整批算一次;studio 级与删除按 owner 算,同一 owner 只查一次。
  339. *
  340. * @param Collection<int, DhammaTerm> $terms
  341. * @return array<string, array{read: bool, update: bool, delete: bool}>
  342. */
  343. public function abilitiesMany(Collection $terms, ?string $userUid): array
  344. {
  345. $channelUids = $terms->pluck('channal')->filter()->unique()->values();
  346. $channelModels = $channelUids->isEmpty()
  347. ? collect()
  348. : Channel::whereIn('uid', $channelUids)->get(['uid', 'owner_uid', 'status', 'is_system']);
  349. $channelAbilities = $this->channels->abilitiesMany($channelModels, $userUid);
  350. $result = [];
  351. foreach ($terms as $term) {
  352. if ($term->channelUid() !== null) {
  353. $ch = $channelAbilities[$term->channelUid()] ?? ['read' => false, 'write' => false];
  354. $read = $ch['read'];
  355. $update = $userUid !== null && $ch['write'];
  356. } else {
  357. $read = true;
  358. $update = $userUid !== null && $this->groupCan($userUid, $term->owner, GroupAbilityService::UPDATE);
  359. }
  360. $delete = $userUid !== null && $this->groupCan($userUid, $term->owner, GroupAbilityService::DELETE);
  361. $result[$term->guid] = ['read' => $read, 'update' => $update, 'delete' => $delete];
  362. }
  363. return $result;
  364. }
  365. private function can(DhammaTerm $term, string $userUid, string $ability): bool
  366. {
  367. return $this->abilitiesMany(collect([$term]), $userUid)[$term->guid][$ability];
  368. }
  369. private function groupCan(string $userUid, string $ownerUid, string $ability): bool
  370. {
  371. return $this->groupAbilities["{$userUid}|{$ownerUid}"][$ability]
  372. ??= $this->groups->can($userUid, $ownerUid, $ability);
  373. }
  374. /* ------------------------------------------------------------------ 内部 */
  375. /**
  376. * @param Builder<DhammaTerm> $query
  377. * @param array<string, mixed> $filters
  378. * @return LengthAwarePaginator<int, DhammaTerm>
  379. */
  380. private function paginate(Builder $query, array $filters, ?string $viewerUid, int $perPage, bool $withBody = false): LengthAwarePaginator
  381. {
  382. $this->applyFilters($query, $filters);
  383. $order = $filters['order'] ?? 'updated_at';
  384. $dir = $filters['dir'] ?? ($order === 'word' ? 'asc' : 'desc');
  385. $page = $query
  386. ->orderBy($order, $dir)
  387. ->orderBy('guid')
  388. ->paginate($perPage);
  389. $this->loadRelations($page->getCollection());
  390. $this->decorate($page->getCollection(), $viewerUid, withBody: $withBody);
  391. return $page;
  392. }
  393. /**
  394. * @param Builder<DhammaTerm> $query
  395. * @param array<string, mixed> $filters
  396. */
  397. private function applyFilters(Builder $query, array $filters): void
  398. {
  399. if (! empty($filters['search'])) {
  400. $like = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $filters['search']).'%';
  401. $query->where(fn (Builder $q) => $q->where('word', 'ilike', $like)
  402. ->orWhere('word_en', 'ilike', $like)
  403. ->orWhere('meaning', 'ilike', $like)
  404. ->orWhere('other_meaning', 'ilike', $like));
  405. }
  406. if (! empty($filters['quality'])) {
  407. $filters['quality'] === 'pending'
  408. ? $query->where(fn (Builder $q) => $q->where('quality', 'pending')->orWhereNull('quality'))
  409. : $query->where('quality', $filters['quality']);
  410. }
  411. if (! empty($filters['category'])) {
  412. // term_categories.term_guid 是 uuid,dhamma_terms.guid 是 varchar
  413. $query->whereIn('guid', TermCategory::query()->selectRaw('term_guid::text')->where('category', $filters['category']));
  414. }
  415. }
  416. /**
  417. * @return list<string>
  418. */
  419. private function relations(): array
  420. {
  421. return [
  422. ...UserService::eagerLoadActor(),
  423. UserService::eagerLoadAssistant('coEditor'),
  424. // 只取分类名(与外键、排序);term_categories.id 不对外,也用不到
  425. 'categories:term_guid,category,position',
  426. ];
  427. }
  428. /**
  429. * 预加载 {@see self::relations()} 与所属 channel。
  430. *
  431. * channel 只给真属于某个 channel 的加载:studio 级的老数据 channal 是空串,
  432. * 统一 `with('channel')` 会拿空串去比 uuid 列,PostgreSQL 直接报错。
  433. *
  434. * @param EloquentCollection<int, DhammaTerm> $terms
  435. */
  436. private function loadRelations(EloquentCollection $terms): void
  437. {
  438. $terms->load($this->relations());
  439. $terms->filter(fn (DhammaTerm $term) => $term->channelUid() !== null)->load('channel:uid,name');
  440. $terms->each(function (DhammaTerm $term) {
  441. if ($term->channelUid() === null) {
  442. $term->setRelation('channel', null);
  443. }
  444. });
  445. }
  446. /**
  447. * 挂上 abilities、摘要纯文本,详情另挂渲染后的正文。整批渲染一次。
  448. *
  449. * 正文 = 摘要 + 正文(摘要放在前面,不加分隔)。摘要纯文本:有摘要用摘要,没有取正文第一段。
  450. * $render 只用于正文:channels 非空时代替术语所在 channel,mode 为 read / edit,
  451. * format 为 tree(挂 body)/ html(挂 html)。
  452. *
  453. * @param Collection<int, DhammaTerm> $terms
  454. * @param array{channels?: list<string>, mode?: string, format?: string} $render
  455. */
  456. private function decorate(Collection $terms, ?string $viewerUid, bool $withBody, array $render = []): void
  457. {
  458. if ($terms->isEmpty()) {
  459. return;
  460. }
  461. $abilities = $this->abilitiesMany($terms, $viewerUid);
  462. $items = [];
  463. foreach ($terms as $term) {
  464. $base = [
  465. 'channels' => $term->channal ? [$term->channal] : [],
  466. 'contentType' => $term->effectiveContentType(),
  467. ];
  468. $summary = trim((string) $term->summary);
  469. $items["{$term->guid}|summary"] = $base + ['source' => $summary !== '' ? $summary : (string) $term->note];
  470. if ($withBody) {
  471. $bodyChannels = ! empty($render['channels']) ? $render['channels'] : $base['channels'];
  472. $items["{$term->guid}|body"] = ['channels' => $bodyChannels] + $base + ['source' => trim($summary."\n\n".(string) $term->note)];
  473. }
  474. }
  475. $bodyFormat = ($render['format'] ?? 'tree') === 'html' ? Format::Html : Format::Tree;
  476. $rendered = $this->markup->renderManyAs(
  477. $items,
  478. new RenderOptions(mode: $render['mode'] ?? 'read'),
  479. $withBody ? [Format::Text, $bodyFormat] : [Format::Text],
  480. );
  481. foreach ($terms as $term) {
  482. $term->abilities = $abilities[$term->guid];
  483. $text = (string) $rendered[Format::Text->value]["{$term->guid}|summary"];
  484. $term->summary_text = trim((string) $term->summary) !== '' ? trim($text) : $this->firstParagraph($text);
  485. if ($withBody && $bodyFormat === Format::Html) {
  486. $term->html = (string) $rendered[Format::Html->value]["{$term->guid}|body"];
  487. } elseif ($withBody) {
  488. $term->body = $rendered[Format::Tree->value]["{$term->guid}|body"];
  489. }
  490. }
  491. }
  492. /**
  493. * 纯文本渲染({@see Format::Text})里段落之间只隔一个换行,第一个非空行就是第一段。
  494. */
  495. private function firstParagraph(string $text): string
  496. {
  497. foreach (preg_split('/\n/u', $text) ?: [] as $paragraph) {
  498. $paragraph = trim($paragraph);
  499. if ($paragraph !== '') {
  500. return $paragraph;
  501. }
  502. }
  503. return '';
  504. }
  505. /**
  506. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  507. * @param array<string, mixed> $data 已含 channel / owner / language
  508. */
  509. private function create(array $actor, array $data): DhammaTerm
  510. {
  511. $this->guardRedirect($data['word'], $data['tag'] ?? null, $data);
  512. return $this->show($this->insert($actor, $data), $actor['editor']);
  513. }
  514. /**
  515. * 写入一条新术语并抽分类、清缓存。不查权限、不查重、不渲染——由调用方负责(单条新建、导入共用)。
  516. * $index=false 时不立即重建搜索索引。
  517. *
  518. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  519. * @param array<string, mixed> $data 已含 channel / owner / language
  520. */
  521. public function insert(array $actor, array $data, bool $index = true): DhammaTerm
  522. {
  523. $now = time() * 1000;
  524. $term = new DhammaTerm;
  525. $term->forceFill([
  526. 'id' => app('snowflake')->id(),
  527. 'guid' => (string) Str::uuid(),
  528. 'word' => $data['word'],
  529. 'word_en' => Tools::getWordEn($data['word']),
  530. 'tag' => $this->normalizeTag($data['tag'] ?? null),
  531. 'meaning' => $data['meaning'],
  532. 'other_meaning' => $data['other_meaning'] ?? null,
  533. 'note' => $data['note'] ?? null,
  534. 'summary' => $data['summary'] ?? null,
  535. 'quality' => $data['quality'] ?? null,
  536. 'content_type' => $data['content_type'] ?? DhammaTerm::CONTENT_TYPE_V3,
  537. 'redirect' => $data['redirect'] ?? null,
  538. 'channal' => $data['channel'],
  539. 'language' => $data['language'],
  540. 'owner' => $data['owner'],
  541. 'editor_uid' => $actor['editor'],
  542. 'editor_id' => $this->users->intIdByUuid($actor['editor']) ?? 0,
  543. 'co_editor_uid' => $actor['co_editor'],
  544. 'version' => 1,
  545. 'create_time' => $now,
  546. 'modify_time' => $now,
  547. ]);
  548. DB::transaction(function () use ($term) {
  549. $term->save();
  550. $this->syncCategories($term->guid, $term->note);
  551. });
  552. $this->afterWrite($term, $index);
  553. return $term->fresh();
  554. }
  555. /**
  556. * 同一范围里 word + tag 唯一(tag 空串与 null 视为相同)。
  557. *
  558. * @param Builder<DhammaTerm> $scope
  559. * @param array<string, mixed> $data
  560. *
  561. * @throws BusinessException
  562. */
  563. private function guardUnique(Builder $scope, array $data): void
  564. {
  565. $existing = $this->findExisting($scope, $data['word'], $data['tag'] ?? null)?->guid;
  566. if ($existing !== null) {
  567. throw new BusinessException(__('messages.term_exists'), 409, 'term-exists', ['existing' => $existing]);
  568. }
  569. }
  570. /**
  571. * 范围内同 word + tag 的那一条(tag 空串与 null 视为相同)。
  572. *
  573. * @param Builder<DhammaTerm> $scope
  574. */
  575. public function findExisting(Builder $scope, string $word, ?string $tag): ?DhammaTerm
  576. {
  577. $query = $scope->where('word', $word);
  578. $this->whereTag($query, $tag);
  579. return $query->first();
  580. }
  581. /**
  582. * redirect 写成 word 或 word@tag,不能指向自己。目标是否存在不查(内容多由 LLM 生成,批量写入时目标可能还没建)。
  583. *
  584. * @param array<string, mixed> $data
  585. *
  586. * @throws ValidationException
  587. */
  588. public function guardRedirect(string $word, ?string $tag, array $data): void
  589. {
  590. $redirect = $data['redirect'] ?? null;
  591. if ($redirect === null || $redirect === '') {
  592. return;
  593. }
  594. [$targetWord, $targetTag] = array_pad(explode('@', $redirect, 2), 2, '');
  595. if ($targetWord === $word && $targetTag === (string) $this->normalizeTag($tag)) {
  596. throw ValidationException::withMessages(['redirect' => __('messages.term_redirect_self')]);
  597. }
  598. }
  599. /**
  600. * @param Builder<DhammaTerm> $query
  601. */
  602. private function whereTag(Builder $query, ?string $tag): void
  603. {
  604. $tag = $this->normalizeTag($tag);
  605. $tag === null
  606. ? $query->where(fn (Builder $q) => $q->whereNull('tag')->orWhere('tag', ''))
  607. : $query->where('tag', $tag);
  608. }
  609. public function normalizeTag(?string $tag): ?string
  610. {
  611. $tag = trim((string) $tag);
  612. return $tag === '' ? null : $tag;
  613. }
  614. /**
  615. * 从正文抽出 {{category|…}},整体替换这条术语的分类。同名的只留第一个。
  616. */
  617. private function syncCategories(string $guid, ?string $note): void
  618. {
  619. preg_match_all('/\{\{category\|([^}|]+)\}\}/u', (string) $note, $matches);
  620. $names = array_values(array_unique(array_filter(array_map(
  621. fn (string $name) => mb_substr(trim($name), 0, 128),
  622. $matches[1] ?? [],
  623. ))));
  624. TermCategory::where('term_guid', $guid)->delete();
  625. foreach ($names as $position => $name) {
  626. TermCategory::create(['term_guid' => $guid, 'category' => $name, 'position' => $position]);
  627. }
  628. }
  629. public function modified(DhammaTerm $term): BusinessException
  630. {
  631. return new BusinessException(
  632. __('messages.term_modified'),
  633. 412,
  634. 'term-modified',
  635. ['etag' => $term->etag()],
  636. 'Precondition Failed',
  637. );
  638. }
  639. /**
  640. * 写入后:清 v2 的术语缓存(v4 / v6 的旧渲染还在读),重建 OpenSearch 索引(全站搜索用;失败不阻断写入)。
  641. * $index=false 时只清缓存,索引由每周的 `opensearch:index-term` 补上(大批导入用)。
  642. */
  643. public function afterWrite(DhammaTerm $term, bool $index = true): void
  644. {
  645. $this->forgetCache($term);
  646. if (! $index) {
  647. return;
  648. }
  649. try {
  650. app(TermIndexService::class)->index($term->guid);
  651. } catch (\Throwable $e) {
  652. Log::warning('Failed to index term after write', ['guid' => $term->guid, 'error' => $e->getMessage()]);
  653. }
  654. }
  655. /**
  656. * v2 的缓存键是 `/term/{channel uid}/{word}`;studio 级术语要清 owner 名下每个 channel 的
  657. * (v2 自己那份清不掉:拿模型而不是 uid 拼键,见 DhammaTermController::deleteCache 的 FIXME)。
  658. */
  659. private function forgetCache(DhammaTerm $term): void
  660. {
  661. $channels = $term->channelUid() !== null
  662. ? [$term->channelUid()]
  663. : Channel::where('owner_uid', $term->owner)->pluck('uid')->all();
  664. foreach ($channels as $uid) {
  665. RedisCache::forget("/term/{$uid}/{$term->word}");
  666. }
  667. }
  668. }