DiscussionService.php 45 KB

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