DiscussionService.php 34 KB

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