DiscussionService.php 35 KB

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