TermService.php 30 KB

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