DiscussionService.php 36 KB

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