DiscussionService.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Exceptions\BusinessException;
  4. use App\Http\Api\ChannelApi;
  5. use App\Http\Api\MdRender;
  6. use App\Http\Api\Mq;
  7. use App\Http\Api\ShareApi;
  8. use App\Http\Resources\DiscussionResource as MqDiscussionPayload;
  9. use App\Models\Article;
  10. use App\Models\ArticleCollection;
  11. use App\Models\Collection as ArticleCollectionOwner;
  12. use App\Models\DhammaTerm;
  13. use App\Models\Discussion;
  14. use App\Models\Sentence;
  15. use App\Models\Task;
  16. use App\Models\Wbw;
  17. use App\Models\WbwBlock;
  18. use App\Services\UserService;
  19. use Illuminate\Contracts\Pagination\LengthAwarePaginator;
  20. use Illuminate\Database\Eloquent\Builder;
  21. use Illuminate\Support\Collection;
  22. use Illuminate\Support\Facades\DB;
  23. use Illuminate\Validation\ValidationException;
  24. /**
  25. * 评论线程(`/v3/discussions`)的业务逻辑:查询、可见性、权限、写入。
  26. *
  27. * 底层是 `discussions` 表,v2 的 `DiscussionController` 另有一套实现,两边不共用——
  28. * 见 CLAUDE.md 铁律 2。
  29. *
  30. * 线程模型固定两层:话题(parent 为空)+ 一层回复。回复的类型、挂靠对象一律跟随话题,
  31. * 不单独存取;状态、标题、severity 只对话题有意义。
  32. *
  33. * 批注(note / commentary,{@see Discussion::INJECTED_TYPES})也走这里,但它不是评论:
  34. * 锚定在句子的某个位置、注入该句所在 channel 的阅读页(所有读者可见),所以
  35. * - 只能挂在句子上,只有该句的管理者(channel 编辑者)能新建;改、删同评论(作者或管理者);
  36. * - 其他用户可以回复;没有开关状态,不能与评论线程互转;新建批注不发通知;
  37. * - 列表与统计不带 type 时只算评论线程,要批注须显式 type=note / commentary。
  38. *
  39. * glossary(外挂术语)是评论线程(有回复和开关),但像批注一样只能挂在句子上、只有该句的管理者能发起,
  40. * 对所有人公开可见。锚点除批注外,issue 与 glossary 也收({@see Discussion::ANCHORED_TYPES})。
  41. *
  42. * 写入方(`$actor`)由 {@see AgentGrantService::actor()} 给出:人类直接写,或 AI 模型凭人类
  43. * 授权代写。代写时 editor 是授权人、co_editor 是模型,权限一律按 editor 判,
  44. * 而且只能写授权覆盖的 channel / book 里的东西。
  45. *
  46. * 可见性沿用 v2 `view=question` 的口径,但这里对列表、单条、回复一视同仁(v2 只在
  47. * 列表上做了这个判断):
  48. * - 未登录看不到不公开的话题(discussion);
  49. * - basic 角色在自己无权管理的对象上,只能看到自己发起的不公开话题。
  50. * issue 2026-10-21 起公开:它会注入阅读页(高亮 + 点击看内容),阅读页是公开且共享缓存的。
  51. *
  52. * TODO: 以下两项需要加列,2026-10-15 用户决定暂缓:
  53. * - qa 的「已回答」现在用 status=close 表示;社区通行做法是把某条回复标为答案
  54. * (GitHub Discussions 的 isAnswer),需要加一列(如 answer_id)。
  55. * - 关闭话题不留痕,不知道是谁、什么时候关的。可以学 Google Drive 用带 action 的
  56. * 回复记录,也可以加 closed_by / closed_at 两列。
  57. */
  58. class DiscussionService
  59. {
  60. /** 登录即可发起的话题类型 */
  61. private const COLLABORATION_TYPES = ['discussion', 'issue'];
  62. /** 不公开的话题类型:未登录用户看不到,basic 角色在无权管理的对象上只能看自己的 */
  63. private const PRIVATE_TYPES = ['discussion'];
  64. /** 批注的锚点字段:定位到句子里的哪一段 */
  65. private const ANCHOR_FIELDS = ['pos_start', 'pos_end', 'quote_exact', 'quote_prefix', 'quote_suffix'];
  66. /**
  67. * 一次调用内的权限缓存。每个公开方法进来先清空:Service 随控制器实例存活,
  68. * 控制器实例又会被路由缓存(测试里、常驻进程里都会跨请求复用),不清空就会把
  69. * 上一个请求的权限带进下一个请求。
  70. *
  71. * @var array<string, array<int, string>> 用户 uid → 可编辑的 channel uid 列表
  72. */
  73. private array $editableChannels = [];
  74. /** @var array<string, bool> "用户 uid|对象类型|对象 id" → 是否能管理该对象 */
  75. private array $managers = [];
  76. public function __construct(
  77. private readonly UserService $users,
  78. private readonly AgentGrantService $grants,
  79. private readonly TipitakaReadingService $reading,
  80. ) {}
  81. /**
  82. * 某个对象上的话题列表。删除了但还有回复的话题以墓碑形式出现。
  83. *
  84. * @param array{target_type: string, target_id: string, type?: string, status?: string, severity?: string, sort?: string} $filters
  85. * @return LengthAwarePaginator<int, Discussion>
  86. */
  87. public function listTopics(array $filters, ?string $viewerUid, int $perPage): LengthAwarePaginator
  88. {
  89. $this->resetCache();
  90. $query = $this->topicQuery()
  91. ->where('res_type', $filters['target_type'])
  92. ->where('res_id', $filters['target_id'])
  93. ->tap(fn ($q) => $this->applyTypeFilter($q, $filters['type'] ?? null))
  94. ->when($filters['status'] ?? null, fn ($q, $value) => $q->where('status', $value))
  95. ->when($filters['severity'] ?? null, fn ($q, $value) => $q->whereIn('severity', explode(',', $value)))
  96. ->withCount('replies as reply_count');
  97. $this->applyVisibility($query, $viewerUid, $filters['target_type'], $filters['target_id']);
  98. $sort = $filters['sort'] ?? '-created_at';
  99. $query->orderBy(ltrim($sort, '-'), str_starts_with($sort, '-') ? 'desc' : 'asc');
  100. $page = $query->paginate($perPage);
  101. $this->decorate($page->getCollection(), $viewerUid);
  102. return $page;
  103. }
  104. /**
  105. * 某个 channel 的一段经文(整个 channel / 一本书 / 一章 / 一段段落区间)里,挂在句子上的话题。
  106. *
  107. * 与 {@see self::listTopics()} 同一套口径(类型过滤、墓碑、可见性),区别只在范围:那边是
  108. * 一个对象,这边是一批句子,所以每条多带所在句子的坐标(`sentence_*` 属性),按经文顺序
  109. * (书、段、句起始词)排列,同一句里按时间。
  110. *
  111. * `discussions.res_id` 是 uuid、`sentences.uid` 是 varchar,pgsql 不会隐式转换,所以关联时
  112. * 把 res_id 转成文本;不转 sentences 那边,免得遇到不是 uuid 格式的旧句子 uid 整条查询报错。
  113. *
  114. * @param array{book?: int, chapter?: int, para?: int, to?: int, type?: string, status?: string, severity?: string} $filters
  115. * @return LengthAwarePaginator<int, Discussion>
  116. */
  117. public function listInChannel(string $channel, array $filters, ?string $viewerUid, int $perPage): LengthAwarePaginator
  118. {
  119. $this->resetCache();
  120. $query = Discussion::withTrashed()
  121. ->select('discussions.*')
  122. ->addSelect([
  123. 's.book_id as sentence_book',
  124. 's.paragraph as sentence_paragraph',
  125. 's.word_start as sentence_word_start',
  126. 's.word_end as sentence_word_end',
  127. ])
  128. // 用 join 不用 belongsTo + whereHas:要按句子的 channel / 范围过滤、按经文顺序排序,
  129. // 关联做不到排序;而且 whereHas 拼出的 `sentences.uid = discussions.res_id` 没处插
  130. // ::text,pgsql 直接报 varchar = uuid。坐标顺带从这里取,不必再预加载一次
  131. ->join('sentences as s', fn ($join) => $join->on(DB::raw('discussions.res_id::text'), '=', 's.uid'))
  132. ->where('discussions.res_type', 'sentence')
  133. ->where('s.channel_uid', $channel)
  134. ->whereNull('s.deleted_at')
  135. ->whereNull('discussions.parent')
  136. // 删了的话题只有还挂着回复时才留下(墓碑),同 topicQuery()
  137. ->where(fn ($q) => $q->whereNull('discussions.deleted_at')
  138. ->orWhereExists(fn ($sub) => $sub->select(DB::raw(1))
  139. ->from('discussions as r')
  140. ->whereColumn('r.parent', 'discussions.id')
  141. ->whereNull('r.deleted_at')))
  142. ->when($filters['status'] ?? null, fn ($q, $value) => $q->where('discussions.status', $value))
  143. ->when($filters['severity'] ?? null, fn ($q, $value) => $q->whereIn('discussions.severity', explode(',', $value)))
  144. ->with(self::relations())
  145. ->withCount('replies as reply_count');
  146. $types = isset($filters['type']) ? explode(',', $filters['type']) : Discussion::THREAD_TYPES;
  147. $query->whereIn('discussions.type', $types);
  148. if (isset($filters['book'])) {
  149. $book = (int) $filters['book'];
  150. $query->where('s.book_id', $book);
  151. if (isset($filters['chapter'])) {
  152. $query->whereBetween('s.paragraph', $this->reading->chapterRange($book, (int) $filters['chapter']));
  153. } elseif (isset($filters['para'])) {
  154. $from = (int) $filters['para'];
  155. $to = (int) ($filters['to'] ?? $from);
  156. if ($to < $from) {
  157. throw ValidationException::withMessages(['to' => __('site.invalid_parameter')]);
  158. }
  159. $query->whereBetween('s.paragraph', [$from, $to]);
  160. }
  161. }
  162. // 可见性同 applyVisibility():一个 channel 里的句子管理者是同一批人,按 channel 判一次
  163. if ($viewerUid === null) {
  164. $query->whereNotIn('discussions.type', self::PRIVATE_TYPES);
  165. } elseif ($this->isBasic($viewerUid) && ! in_array($channel, $this->editableChannels($viewerUid), true)) {
  166. $query->where(fn ($q) => $q->whereNotIn('discussions.type', self::PRIVATE_TYPES)
  167. ->orWhere('discussions.editor_uid', $viewerUid));
  168. }
  169. $page = $query
  170. ->orderBy('s.book_id')
  171. ->orderBy('s.paragraph')
  172. ->orderBy('s.word_start')
  173. ->orderBy('discussions.created_at')
  174. ->paginate($perPage);
  175. $this->decorate($page->getCollection(), $viewerUid);
  176. return $page;
  177. }
  178. /**
  179. * 某个对象上的话题概况:各状态的话题数(只数没删的、当前用户看得见的),
  180. * 以及当前用户能在这里发起哪些类型的话题。
  181. *
  182. * @param array{target_type: string, target_id: string, type?: string} $filters
  183. * @return array{status_counts: array{active: int, close: int}, creatable_types: list<string>}
  184. */
  185. public function summary(array $filters, ?string $viewerUid): array
  186. {
  187. $this->resetCache();
  188. $query = Discussion::query()
  189. ->whereNull('parent')
  190. ->whereIn('type', Discussion::COMMENT_TYPES)
  191. ->where('res_type', $filters['target_type'])
  192. ->where('res_id', $filters['target_id'])
  193. ->tap(fn ($q) => $this->applyTypeFilter($q, $filters['type'] ?? null));
  194. $this->applyVisibility($query, $viewerUid, $filters['target_type'], $filters['target_id']);
  195. $counts = $query->toBase()
  196. ->select('status', DB::raw('count(*) as total'))
  197. ->groupBy('status')
  198. ->pluck('total', 'status');
  199. return [
  200. 'status_counts' => [
  201. 'active' => (int) ($counts['active'] ?? 0),
  202. 'close' => (int) ($counts['close'] ?? 0),
  203. ],
  204. 'creatable_types' => $this->creatableTypes($viewerUid, $filters['target_type'], $filters['target_id']),
  205. ];
  206. }
  207. /**
  208. * 一批对象(句子 / 逐词)的讨论角标:未关闭的评论线程数,以及其中查看者发起的数目。
  209. *
  210. * 一条 group by 查完;可见性口径同列表({@see self::applyVisibility()}),basic 角色能管理
  211. * 哪些对象批量算出,不逐个查。按请求顺序返回,没有讨论的给 0。
  212. *
  213. * TODO: 课程迁 v3 之后,补上 v2 课程模式的「学生的讨论」:逐词按坐标(book / paragraph / wid)
  214. * 匹配学员 channel 上同一个词的讨论(v2 `DiscussionCountController@store` 的 course_id 分支,
  215. * 前端 `WbwPaliDiscussionIcon` 的 wbw 参数)。现在只数这个对象本身上的。
  216. *
  217. * @param list<array{type: string, id: string}> $targets
  218. * @return list<array{target_type: string, target_id: string, total: int, mine: int}>
  219. */
  220. public function batchCount(array $targets, ?string $viewerUid): array
  221. {
  222. $this->resetCache();
  223. $idsByType = collect($targets)->groupBy('type')->map(fn ($items) => $items->pluck('id')->unique()->values()->all());
  224. $query = Discussion::query()
  225. ->whereNull('parent')
  226. ->where('status', 'active')
  227. ->whereIn('type', Discussion::THREAD_TYPES)
  228. ->where(function ($q) use ($idsByType) {
  229. foreach ($idsByType as $type => $ids) {
  230. $q->orWhere(fn ($q) => $q->where('res_type', $type)->whereIn('res_id', $ids));
  231. }
  232. });
  233. if ($viewerUid === null) {
  234. $query->whereNotIn('type', self::PRIVATE_TYPES);
  235. } elseif ($this->isBasic($viewerUid)) {
  236. $managed = $this->managedTargets($viewerUid, $idsByType->all());
  237. $query->where(fn ($q) => $q->whereNotIn('type', self::PRIVATE_TYPES)
  238. ->orWhere('editor_uid', $viewerUid)
  239. ->orWhereIn('res_id', $managed));
  240. }
  241. $rows = $query->toBase()
  242. ->select('res_type', 'res_id', DB::raw('count(*) as total'))
  243. ->selectRaw('sum(case when editor_uid = ? then 1 else 0 end) as mine', [$viewerUid])
  244. ->groupBy('res_type', 'res_id')
  245. ->get()
  246. ->keyBy(fn ($row) => $row->res_type.'/'.$row->res_id);
  247. return array_map(function (array $target) use ($rows) {
  248. $row = $rows[$target['type'].'/'.$target['id']] ?? null;
  249. return [
  250. 'target_type' => $target['type'],
  251. 'target_id' => $target['id'],
  252. 'total' => (int) ($row->total ?? 0),
  253. 'mine' => (int) ($row->mine ?? 0),
  254. ];
  255. }, array_values($targets));
  256. }
  257. /**
  258. * 单条(话题或回复)。删除了的回复、删除了且没有回复的话题都当作不存在。
  259. */
  260. public function show(Discussion $discussion, ?string $viewerUid): Discussion
  261. {
  262. $this->resetCache();
  263. $this->assertComment($discussion);
  264. if ($discussion->trashed() && ($discussion->parent !== null || ! $discussion->replies()->exists())) {
  265. abort(404);
  266. }
  267. $topic = $discussion->parent === null ? $discussion : Discussion::withTrashed()->findOrFail($discussion->parent);
  268. $this->assertVisible($topic, $viewerUid);
  269. $discussion->load(self::relations());
  270. if ($discussion->parent === null) {
  271. $discussion->loadCount('replies as reply_count');
  272. } else {
  273. $discussion->type = $topic->type;
  274. }
  275. $this->decorate(collect([$discussion]), $viewerUid);
  276. return $discussion;
  277. }
  278. /**
  279. * 话题下的回复,按时间正序。墓碑话题的回复照样可读。
  280. *
  281. * @return LengthAwarePaginator<int, Discussion>
  282. */
  283. public function listReplies(Discussion $topic, ?string $viewerUid, int $perPage): LengthAwarePaginator
  284. {
  285. $this->resetCache();
  286. $this->assertComment($topic);
  287. if ($topic->parent !== null) {
  288. abort(404);
  289. }
  290. $this->assertVisible($topic, $viewerUid);
  291. $page = Discussion::query()
  292. ->where('parent', $topic->id)
  293. ->with(self::relations())
  294. ->orderBy('created_at')
  295. ->paginate($perPage);
  296. // 回复的类型一律跟随话题:历史数据里有 qa 话题下 type=discussion 的回复
  297. $page->getCollection()->each(fn (Discussion $reply) => $reply->type = $topic->type);
  298. $this->decorate($page->getCollection(), $viewerUid);
  299. return $page;
  300. }
  301. /**
  302. * 发起话题,或新建一条批注(批注不发通知)。
  303. *
  304. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  305. * @param array{target_type: string, target_id: string, type?: string, title?: string|null, content?: string|null, severity?: string|null, pos_start?: int|null, pos_end?: int|null, quote_exact?: string|null, quote_prefix?: string|null, quote_suffix?: string|null, tpl_id?: string|null, notify?: bool} $data
  306. */
  307. public function createTopic(array $actor, array $data): Discussion
  308. {
  309. $this->resetCache();
  310. $userUid = $actor['editor'];
  311. if (! $this->targetExists($data['target_type'], $data['target_id'])) {
  312. throw ValidationException::withMessages(['target_id' => __('messages.discussion_target_not_found')]);
  313. }
  314. $this->assertGrantCovers($actor, $data['target_type'], $data['target_id']);
  315. $type = $data['type'] ?? 'discussion';
  316. if (! in_array($type, $this->creatableTypes($userUid, $data['target_type'], $data['target_id']), true)) {
  317. abort(403, __('messages.discussion_forbidden'));
  318. }
  319. $topic = new Discussion;
  320. $topic->res_type = $data['target_type'];
  321. $topic->res_id = $data['target_id'];
  322. $topic->type = $type;
  323. $topic->title = $data['title'] ?? null;
  324. $topic->content = $data['content'] ?? null;
  325. $topic->content_type = 'markdown';
  326. $topic->severity = $data['severity'] ?? null;
  327. $topic->tpl_id = $data['tpl_id'] ?? null;
  328. $topic->fill(array_intersect_key($data, array_flip(self::ANCHOR_FIELDS)));
  329. $topic->editor_uid = $userUid;
  330. $topic->co_editor_uid = $actor['co_editor'];
  331. $topic->save();
  332. if (! $this->isAnnotation($topic) && ($data['notify'] ?? true)) {
  333. $this->notify($topic);
  334. }
  335. return $this->fresh($topic, $userUid);
  336. }
  337. /**
  338. * 回复话题。话题必须没关闭;不能回复一条回复。
  339. *
  340. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  341. * @param array{content: string, notify?: bool} $data
  342. */
  343. public function createReply(Discussion $topic, array $actor, array $data): Discussion
  344. {
  345. $this->resetCache();
  346. $userUid = $actor['editor'];
  347. $this->assertComment($topic);
  348. if ($topic->parent !== null) {
  349. throw ValidationException::withMessages(['discussion' => __('messages.discussion_reply_to_reply')]);
  350. }
  351. $this->assertVisible($topic, $userUid);
  352. $this->assertGrantCovers($actor, $topic->res_type, $topic->res_id);
  353. if ($topic->status === 'close') {
  354. throw new BusinessException(__('messages.discussion_closed'), 409, 'discussion-closed');
  355. }
  356. if (! $this->canReply($userUid, $topic)) {
  357. abort(403, __('messages.discussion_forbidden'));
  358. }
  359. $reply = DB::transaction(function () use ($topic, $userUid, $actor, $data) {
  360. $reply = new Discussion;
  361. $reply->res_type = $topic->res_type;
  362. $reply->res_id = $topic->res_id;
  363. $reply->type = $topic->type;
  364. $reply->parent = $topic->id;
  365. $reply->content = $data['content'];
  366. $reply->content_type = 'markdown';
  367. $reply->editor_uid = $userUid;
  368. $reply->co_editor_uid = $actor['co_editor'];
  369. $reply->save();
  370. // children_count 列只有 v2 的 sent-discussion-tree 在读,v3 现算;这里只是让它别漂移
  371. $topic->increment('children_count');
  372. return $reply;
  373. });
  374. if ($data['notify'] ?? true) {
  375. $this->notify($reply);
  376. }
  377. return $this->fresh($reply, $userUid);
  378. }
  379. /**
  380. * 局部更新。title / status / type / severity 只对话题有效。
  381. *
  382. * 改 type 时回复跟着改;新类型不收原来的 severity 时,severity 清空。锚点不清:
  383. * 留着不显示也不影响校验,改回可带锚点的类型时位置自动恢复。
  384. * 改成 glossary 须挂在句子上、且当前用户是该句的管理者(同新建)。
  385. * 批注:锚点可改,没有 status,type 只能在 note / commentary 之间改,
  386. * 正文不能清空,commentary 的正文必须是义注句子模板(按改后的 type 与正文判)。
  387. *
  388. * 改了内容(标题、正文、锚点)时 co_editor 改成这次写入的协作者:人亲自改则清空,
  389. * AI 代改则换成该模型。只改 status / type / severity 不动 co_editor。
  390. *
  391. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  392. * @param array{title?: string, content?: string|null, status?: string, type?: string, severity?: string|null, pos_start?: int|null, pos_end?: int|null, quote_exact?: string|null, quote_prefix?: string|null, quote_suffix?: string|null} $data
  393. */
  394. public function update(Discussion $discussion, array $actor, array $data): Discussion
  395. {
  396. $this->resetCache();
  397. $userUid = $actor['editor'];
  398. $this->assertComment($discussion);
  399. $this->assertGrantCovers($actor, $discussion->res_type, $discussion->res_id);
  400. $abilities = $this->abilities($discussion, $userUid);
  401. if (! $abilities['update']) {
  402. abort(403, __('messages.discussion_forbidden'));
  403. }
  404. $isTopic = $discussion->parent === null;
  405. $topicOnly = array_intersect_key($data, array_flip(['title', 'status', 'type', 'severity']));
  406. if (! $isTopic && $topicOnly !== []) {
  407. throw ValidationException::withMessages(
  408. array_fill_keys(array_keys($topicOnly), __('messages.discussion_topic_only'))
  409. );
  410. }
  411. $this->assertAnnotationUpdate($discussion, $data);
  412. if (array_key_exists('status', $data) && ! $abilities['close']) {
  413. abort(403, __('messages.discussion_forbidden'));
  414. }
  415. $type = $data['type'] ?? $discussion->type;
  416. if ($type === Discussion::TYPE_GLOSSARY && $discussion->type !== Discussion::TYPE_GLOSSARY) {
  417. $this->assertCanBecomeGlossary($discussion, $userUid);
  418. }
  419. if (array_key_exists('severity', $data)) {
  420. if ($data['severity'] !== null && ! in_array($data['severity'], Discussion::SEVERITIES[$type] ?? [], true)) {
  421. throw ValidationException::withMessages(['severity' => __('messages.discussion_severity_not_allowed')]);
  422. }
  423. } elseif ($discussion->severity !== null && ! in_array($discussion->severity, Discussion::SEVERITIES[$type] ?? [], true)) {
  424. $data['severity'] = null;
  425. }
  426. DB::transaction(function () use ($discussion, $data, $actor) {
  427. $typeChanged = array_key_exists('type', $data) && $data['type'] !== $discussion->type;
  428. $authored = array_intersect_key($data, array_flip(['title', 'content', ...self::ANCHOR_FIELDS]));
  429. $discussion->fill($authored);
  430. // 改了内容,co_editor 就跟着这次写的人走:人亲自改 → 清空,AI 代改 → 换成这个模型。
  431. // 只改状态 / 类型 / severity 是管理动作,不动内容的署名。
  432. if ($authored !== []) {
  433. $discussion->co_editor_uid = $actor['co_editor'];
  434. }
  435. foreach (['status', 'type', 'severity'] as $field) {
  436. if (array_key_exists($field, $data)) {
  437. $discussion->{$field} = $data[$field];
  438. }
  439. }
  440. $discussion->save();
  441. if ($typeChanged) {
  442. Discussion::where('parent', $discussion->id)->update(['type' => $discussion->type]);
  443. }
  444. });
  445. return $this->fresh($discussion, $userUid);
  446. }
  447. /**
  448. * 软删除。作者本人或挂靠对象的管理者能删(v2 只允许作者)。
  449. *
  450. * 删话题不动回复:有回复的话题以墓碑形式继续出现在列表里;删回复会让话题的
  451. * children_count 减一。返回删除后的资源(AIP-164:软删的资源没有消失)。
  452. *
  453. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  454. */
  455. public function delete(Discussion $discussion, array $actor): Discussion
  456. {
  457. $this->resetCache();
  458. $userUid = $actor['editor'];
  459. $this->assertComment($discussion);
  460. $this->assertGrantCovers($actor, $discussion->res_type, $discussion->res_id);
  461. if (! $this->abilities($discussion, $userUid)['delete']) {
  462. abort(403, __('messages.discussion_forbidden'));
  463. }
  464. DB::transaction(function () use ($discussion) {
  465. $discussion->delete();
  466. if ($discussion->parent !== null) {
  467. Discussion::where('id', $discussion->parent)
  468. ->where('children_count', '>', 0)
  469. ->decrement('children_count');
  470. }
  471. });
  472. return $this->fresh($discussion, $userUid);
  473. }
  474. /**
  475. * 编辑者与协作者的预加载声明。
  476. *
  477. * @return array<int, string>
  478. */
  479. private static function relations(): array
  480. {
  481. return [...UserService::eagerLoadActor(), UserService::eagerLoadAssistant('coEditor')];
  482. }
  483. /**
  484. * AI 代写时,授权必须覆盖这次写入落到的 channel / book;只有句子能定位到 channel,
  485. * 挂在别的对象上的一律不覆盖。人类直接写不受限。
  486. *
  487. * @param array{editor: string, co_editor: string|null, scope: array{channel: string, book: int}|null} $actor
  488. */
  489. private function assertGrantCovers(array $actor, string $targetType, string $targetId): void
  490. {
  491. if ($actor['scope'] === null) {
  492. return;
  493. }
  494. $sentence = $targetType === 'sentence'
  495. ? Sentence::where('uid', $targetId)->first(['channel_uid', 'book_id'])
  496. : null;
  497. if (! $this->grants->covers($actor['scope'], $sentence?->channel_uid, $sentence ? (int) $sentence->book_id : null)) {
  498. abort(403, __('messages.agent_grant_scope'));
  499. }
  500. }
  501. /**
  502. * 这批对象里查看者能管理的(所在 channel 可编辑),一次查出,供 basic 角色的可见性用。
  503. *
  504. * @param array<string, list<string>> $idsByType
  505. * @return list<string>
  506. */
  507. private function managedTargets(string $userUid, array $idsByType): array
  508. {
  509. $editable = $this->editableChannels($userUid);
  510. $managed = [];
  511. if (! empty($idsByType['sentence'])) {
  512. array_push($managed, ...Sentence::whereIn('uid', $idsByType['sentence'])
  513. ->whereIn('channel_uid', $editable)->pluck('uid')->all());
  514. }
  515. if (! empty($idsByType['wbw'])) {
  516. $blocks = WbwBlock::whereIn('channel_uid', $editable)->select('uid');
  517. array_push($managed, ...Wbw::whereIn('uid', $idsByType['wbw'])
  518. ->whereIn('block_uid', $blocks)->pluck('uid')->all());
  519. }
  520. return array_map('strval', $managed);
  521. }
  522. private function isAnnotation(Discussion $discussion): bool
  523. {
  524. return in_array($discussion->type, Discussion::INJECTED_TYPES, true);
  525. }
  526. /**
  527. * 列表 / 统计的类型过滤:传了就按传的,没传只算评论线程(批注要显式点名)。
  528. *
  529. * @param Builder<Discussion> $query
  530. */
  531. private function applyTypeFilter(Builder $query, ?string $type): void
  532. {
  533. $type === null
  534. ? $query->whereIn('type', Discussion::THREAD_TYPES)
  535. : $query->where('type', $type);
  536. }
  537. /**
  538. * 批注与评论线程在 PATCH 上的差异,见 {@see self::update()}。
  539. *
  540. * @param array<string, mixed> $data
  541. */
  542. private function assertAnnotationUpdate(Discussion $discussion, array $data): void
  543. {
  544. $isAnnotation = $this->isAnnotation($discussion);
  545. $errors = [];
  546. if (array_key_exists('type', $data)
  547. && in_array($data['type'], Discussion::INJECTED_TYPES, true) !== $isAnnotation) {
  548. $errors['type'] = __('messages.discussion_type_group');
  549. }
  550. if (! in_array($data['type'] ?? $discussion->type, Discussion::ANCHORED_TYPES, true)) {
  551. foreach (array_intersect(self::ANCHOR_FIELDS, array_keys($data)) as $field) {
  552. $errors[$field] = __('messages.discussion_anchor_thread');
  553. }
  554. }
  555. if ($isAnnotation) {
  556. if (array_key_exists('status', $data)) {
  557. $errors['status'] = __('messages.discussion_annotation_no_status');
  558. }
  559. $type = $data['type'] ?? $discussion->type;
  560. $content = trim((string) (array_key_exists('content', $data) ? $data['content'] : $discussion->content));
  561. if ($content === '') {
  562. $errors['content'] = __('validation.required', ['attribute' => 'content']);
  563. } elseif ($type === Discussion::TYPE_COMMENTARY && ! preg_match(Discussion::COMMENTARY_PATTERN, $content)) {
  564. $errors['content'] = __('messages.discussion_commentary_format');
  565. }
  566. }
  567. if ($errors !== []) {
  568. throw ValidationException::withMessages($errors);
  569. }
  570. }
  571. /**
  572. * 话题改成 glossary:与新建同口径,只能挂在句子上、只有该句的管理者能改。
  573. */
  574. private function assertCanBecomeGlossary(Discussion $discussion, string $userUid): void
  575. {
  576. if ($discussion->res_type !== 'sentence') {
  577. throw ValidationException::withMessages(['type' => __('messages.discussion_glossary_target')]);
  578. }
  579. if (! $this->canManageTarget($userUid, $discussion->res_type, $discussion->res_id)) {
  580. abort(403, __('messages.discussion_forbidden'));
  581. }
  582. }
  583. private function resetCache(): void
  584. {
  585. $this->editableChannels = [];
  586. $this->managers = [];
  587. }
  588. /**
  589. * 话题的基础查询:只要评论类型、只要顶级;删了的话题只有还挂着回复时才留下(墓碑)。
  590. *
  591. * @return Builder<Discussion>
  592. */
  593. private function topicQuery(): Builder
  594. {
  595. return Discussion::withTrashed()
  596. ->whereNull('parent')
  597. ->whereIn('type', Discussion::COMMENT_TYPES)
  598. ->where(fn ($q) => $q->whereNull('deleted_at')->orWhereHas('replies'))
  599. ->with(self::relations());
  600. }
  601. /**
  602. * 列表上的可见性过滤。口径见类注释。
  603. *
  604. * @param Builder<Discussion> $query
  605. */
  606. private function applyVisibility(Builder $query, ?string $viewerUid, string $targetType, string $targetId): void
  607. {
  608. if ($viewerUid === null) {
  609. $query->whereNotIn('type', self::PRIVATE_TYPES);
  610. return;
  611. }
  612. if ($this->isBasic($viewerUid) && ! $this->canManageTarget($viewerUid, $targetType, $targetId)) {
  613. $query->where(fn ($q) => $q->whereNotIn('type', self::PRIVATE_TYPES)
  614. ->orWhere('editor_uid', $viewerUid));
  615. }
  616. }
  617. /**
  618. * 单条话题的可见性。看不见就当作不存在(404),不暴露它的存在。
  619. */
  620. private function assertVisible(Discussion $topic, ?string $viewerUid): void
  621. {
  622. if (! in_array($topic->type, self::PRIVATE_TYPES, true)) {
  623. return;
  624. }
  625. if ($viewerUid === null) {
  626. abort(404);
  627. }
  628. if ($topic->editor_uid !== $viewerUid
  629. && $this->isBasic($viewerUid)
  630. && ! $this->canManageTarget($viewerUid, $topic->res_type, $topic->res_id)) {
  631. abort(404);
  632. }
  633. }
  634. /**
  635. * 评论线程与批注以外的记录(如任务状态日志)不归 v3 discussions 管。
  636. */
  637. private function assertComment(Discussion $discussion): void
  638. {
  639. if (! in_array($discussion->type, Discussion::COMMENT_TYPES, true)) {
  640. abort(404);
  641. }
  642. }
  643. /**
  644. * 当前用户能在这个对象上发起哪些类型的话题。
  645. *
  646. * 协作类(discussion / issue)登录即可;qa / help 沿用 v2 `can_create` 的口径:
  647. * 只能发在文章上,而且只有文章的编辑者能发;批注(note / commentary)与 glossary 只能加在
  648. * 句子上,而且只有该句的管理者能加(v2 登录即可,v3 收紧)。
  649. *
  650. * @return list<string>
  651. */
  652. private function creatableTypes(?string $userUid, string $targetType, string $targetId): array
  653. {
  654. if ($userUid === null) {
  655. return [];
  656. }
  657. $types = self::COLLABORATION_TYPES;
  658. if ($targetType === 'article' && $this->canManageTarget($userUid, $targetType, $targetId)) {
  659. array_push($types, 'qa', 'help');
  660. }
  661. // 批注注入阅读页、所有读者可见,只有该句的管理者能加
  662. if ($targetType === 'sentence' && $this->canManageTarget($userUid, $targetType, $targetId)) {
  663. array_push($types, Discussion::TYPE_GLOSSARY, Discussion::TYPE_NOTE, Discussion::TYPE_COMMENTARY);
  664. }
  665. return $types;
  666. }
  667. /**
  668. * 当前用户对一条记录能做的动作。前端按它决定显示哪些菜单,后端按它放行。
  669. *
  670. * @return array{update: bool, delete: bool, close: bool, reply: bool}
  671. */
  672. private function abilities(Discussion $discussion, ?string $viewerUid): array
  673. {
  674. $none = ['update' => false, 'delete' => false, 'close' => false, 'reply' => false];
  675. if ($viewerUid === null || $discussion->trashed()) {
  676. return $none;
  677. }
  678. $isAuthor = $discussion->editor_uid === $viewerUid;
  679. $canManage = $isAuthor || $this->canManageTarget($viewerUid, $discussion->res_type, $discussion->res_id);
  680. $isTopic = $discussion->parent === null;
  681. if ($this->isAnnotation($discussion)) {
  682. // 批注没有开关;回复与评论线程一样,登录即可
  683. return [
  684. 'update' => $canManage,
  685. 'delete' => $canManage,
  686. 'close' => false,
  687. 'reply' => $isTopic && $this->canReply($viewerUid, $discussion),
  688. ];
  689. }
  690. return [
  691. 'update' => $canManage,
  692. // 作者,或挂靠对象的管理者(审核别人的评论)。v2 只允许作者删,v3 放开:
  693. // 删除是软删,删错了可以恢复
  694. 'delete' => $canManage,
  695. 'close' => $isTopic && $canManage,
  696. 'reply' => $isTopic && $discussion->status === 'active' && $this->canReply($viewerUid, $discussion),
  697. ];
  698. }
  699. /**
  700. * 能否回复:登录即可;文章上的 qa 只有文章编辑者能答(沿用 v2 `can_reply` 的口径)。
  701. */
  702. private function canReply(?string $userUid, Discussion $topic): bool
  703. {
  704. if ($userUid === null) {
  705. return false;
  706. }
  707. if ($topic->type === 'qa' && $topic->res_type === 'article') {
  708. return $this->canManageTarget($userUid, 'article', $topic->res_id);
  709. }
  710. return true;
  711. }
  712. /**
  713. * 能否管理挂靠的对象:句子与逐词看所在 channel 的编辑权,文章看文章的编辑权,
  714. * 其它对象(术语、任务)没有「管理者」这一说,只有作者本人。
  715. */
  716. private function canManageTarget(string $userUid, string $targetType, string $targetId): bool
  717. {
  718. $key = "{$userUid}|{$targetType}|{$targetId}";
  719. if (array_key_exists($key, $this->managers)) {
  720. return $this->managers[$key];
  721. }
  722. $result = match ($targetType) {
  723. 'sentence', 'wbw' => ($channel = $this->channelOf($targetType, $targetId)) !== null
  724. && in_array($channel, $this->editableChannels($userUid), true),
  725. 'article' => $this->canEditArticle($userUid, $targetId),
  726. default => false,
  727. };
  728. return $this->managers[$key] = $result;
  729. }
  730. /**
  731. * 句子 / 逐词所在的 channel。
  732. */
  733. private function channelOf(string $targetType, string $targetId): ?string
  734. {
  735. if ($targetType === 'sentence') {
  736. return Sentence::where('uid', $targetId)->value('channel_uid');
  737. }
  738. $blockUid = Wbw::where('uid', $targetId)->value('block_uid');
  739. return $blockUid ? WbwBlock::where('uid', $blockUid)->value('channel_uid') : null;
  740. }
  741. /**
  742. * @return array<int, string>
  743. */
  744. private function editableChannels(string $userUid): array
  745. {
  746. return $this->editableChannels[$userUid] ??= ChannelApi::getCanEditByUser($userUid);
  747. }
  748. /**
  749. * 文章编辑权:所有者、文章协作者(power ≥ 20),或文章所在的同主人文集的协作者。
  750. * 与 v2 `ArticleController::userCanEdit()` 同口径,v3 不去依赖 v2 的控制器。
  751. */
  752. private function canEditArticle(string $userUid, string $articleUid): bool
  753. {
  754. $article = Article::where('uid', $articleUid)->first(['uid', 'owner']);
  755. if (! $article) {
  756. return false;
  757. }
  758. if ($article->owner === $userUid || ShareApi::getResPower($userUid, $article->uid) >= 20) {
  759. return true;
  760. }
  761. $collections = ArticleCollectionOwner::whereIn(
  762. 'uid',
  763. ArticleCollection::where('article_id', $article->uid)->select('collect_id')
  764. )->where('owner', $article->owner)->pluck('uid');
  765. return $collections->contains(fn ($uid) => ShareApi::getResPower($userUid, $uid) >= 20);
  766. }
  767. private function isBasic(string $userUid): bool
  768. {
  769. return in_array('basic', (array) ($this->users->byUuid($userUid)['roles'] ?? []), true);
  770. }
  771. private function targetExists(string $targetType, string $targetId): bool
  772. {
  773. return match ($targetType) {
  774. 'sentence' => Sentence::where('uid', $targetId)->exists(),
  775. 'wbw' => Wbw::where('uid', $targetId)->exists(),
  776. 'article' => Article::where('uid', $targetId)->exists(),
  777. 'term' => DhammaTerm::where('guid', $targetId)->exists(),
  778. 'task' => Task::where('id', $targetId)->exists(),
  779. default => false,
  780. };
  781. }
  782. /**
  783. * 写操作之后重新读出完整资源(含墓碑),挂好关系与权限。
  784. *
  785. * 保留 wasRecentlyCreated:Laravel 的 ResourceResponse 据此把新建的响应设为 201,
  786. * 控制器不用手写状态码。
  787. */
  788. private function fresh(Discussion $discussion, string $userUid): Discussion
  789. {
  790. $fresh = Discussion::withTrashed()->with(self::relations())->findOrFail($discussion->id);
  791. $fresh->wasRecentlyCreated = $discussion->wasRecentlyCreated;
  792. if ($fresh->parent === null) {
  793. $fresh->loadCount('replies as reply_count');
  794. }
  795. $this->decorate(collect([$fresh]), $userUid);
  796. return $fresh;
  797. }
  798. /**
  799. * 给一批记录挂上权限与正文渲染结果。
  800. *
  801. * 只有挂在句子上的才渲染:正文里的模板要用句子所在的 channel 去解析。
  802. * channel 一次批量查出,不逐行查。
  803. *
  804. * @param Collection<int, Discussion> $items
  805. */
  806. private function decorate(Collection $items, ?string $viewerUid): void
  807. {
  808. $sentenceIds = $items->where('res_type', 'sentence')->pluck('res_id')->unique()->values();
  809. $channels = $sentenceIds->isEmpty()
  810. ? collect()
  811. : Sentence::whereIn('uid', $sentenceIds)->pluck('channel_uid', 'uid');
  812. foreach ($items as $item) {
  813. $item->abilities = $this->abilities($item, $viewerUid);
  814. $channel = $item->res_type === 'sentence' ? ($channels[$item->res_id] ?? null) : null;
  815. if ($channel && ! $item->trashed() && $item->content) {
  816. $item->rendered = [
  817. 'html' => MdRender::render($item->content, [$channel], null, 'read'),
  818. 'summary' => MdRender::render($item->content, [$channel], null, 'read', 'translation', 'markdown', 'text'),
  819. ];
  820. }
  821. }
  822. }
  823. /**
  824. * 推给 mq:discussion 工作进程(站内信 + webhook)。
  825. *
  826. * 载荷沿用 v2 `DiscussionResource` 的形状:那是工作进程读的消息契约
  827. * (读 editor.nickName、parent、res_type…),不是 v2 的 HTTP 契约。
  828. */
  829. private function notify(Discussion $discussion): void
  830. {
  831. Mq::publish('discussion', new MqDiscussionPayload($discussion));
  832. }
  833. }