GroupService.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Exceptions\BusinessException;
  4. use App\Models\AiModel;
  5. use App\Models\Article;
  6. use App\Models\Attachment;
  7. use App\Models\Channel;
  8. use App\Models\Collection;
  9. use App\Models\Commentary;
  10. use App\Models\Course;
  11. use App\Models\CustomBook;
  12. use App\Models\CustomBookSentence;
  13. use App\Models\DhammaTerm;
  14. use App\Models\DictInfo;
  15. use App\Models\GroupInfo;
  16. use App\Models\GroupMember;
  17. use App\Models\Project;
  18. use App\Models\SentBlock;
  19. use App\Models\Share;
  20. use App\Models\Tag;
  21. use App\Models\TagMap;
  22. use App\Models\Task;
  23. use App\Services\UserService;
  24. use Illuminate\Auth\Access\AuthorizationException;
  25. use Illuminate\Contracts\Pagination\LengthAwarePaginator;
  26. use Illuminate\Database\Eloquent\Builder;
  27. use Illuminate\Support\Facades\DB;
  28. use Illuminate\Support\Str;
  29. use Illuminate\Validation\ValidationException;
  30. /**
  31. * 团队本身:搜公开团队、看详情、建、改、删。
  32. *
  33. * 取代 v2 `GroupController`(index 的 view=all、show、store、update、destroy)。
  34. * 「我的团队」列表在 {@see GroupMemberService::listForUser()}(载荷是成员记录)。
  35. * v2 那份原地保留不动(铁律 2),两边不共用代码。
  36. */
  37. class GroupService
  38. {
  39. /**
  40. * 可能以团队为 owner 的表:删团队前逐表检查,名下还有东西就拒绝。
  41. * 只列 owner 列存 uuid 的;articles / collections 的 owner_id 是整数用户 id,不算。
  42. *
  43. * @var array<string, array{0: class-string, 1: string}>
  44. */
  45. private const OWNED = [
  46. 'channel' => [Channel::class, 'owner_uid'],
  47. 'article' => [Article::class, 'owner'],
  48. 'collection' => [Collection::class, 'owner'],
  49. 'term' => [DhammaTerm::class, 'owner'],
  50. 'course' => [Course::class, 'studio_id'],
  51. 'project' => [Project::class, 'owner_id'],
  52. 'task' => [Task::class, 'owner_id'],
  53. 'tag' => [Tag::class, 'owner_id'],
  54. 'tag_map' => [TagMap::class, 'owner_uid'],
  55. 'attachment' => [Attachment::class, 'owner_uid'],
  56. 'ai_model' => [AiModel::class, 'owner_id'],
  57. 'custom_book' => [CustomBook::class, 'owner'],
  58. 'custom_book_sentence' => [CustomBookSentence::class, 'owner'],
  59. 'dict' => [DictInfo::class, 'owner_id'],
  60. 'commentary' => [Commentary::class, 'owner_id'],
  61. 'sent_block' => [SentBlock::class, 'owner_uid'],
  62. ];
  63. public function __construct(
  64. private readonly GroupAbilityService $abilities,
  65. private readonly AgentGrantService $agents,
  66. ) {}
  67. /**
  68. * 按名字搜公开团队(共享资源时挑团队用)。私有团队不出现。
  69. *
  70. * @return LengthAwarePaginator<int, GroupInfo>
  71. */
  72. public function searchPublic(?string $search, int $perPage): LengthAwarePaginator
  73. {
  74. return $this->withCreator()
  75. ->where('status', '>=', GroupInfo::STATUS_PUBLIC)
  76. ->when($search, fn (Builder $query, string $value) => $query->where('name', 'ilike', '%'.$value.'%'))
  77. ->orderBy('name')
  78. ->orderBy('uid')
  79. ->paginate($perPage);
  80. }
  81. /**
  82. * 团队详情:公开团队谁都能看,私有团队只有成员能看。附上查看者的角色。
  83. *
  84. * @throws AuthorizationException 私有团队且不是成员
  85. */
  86. public function show(GroupInfo $group, ?string $viewerUid): GroupInfo
  87. {
  88. $role = $viewerUid ? $this->abilities->roleIn($viewerUid, $group->uid) : null;
  89. if ($role === null && $group->status < GroupInfo::STATUS_PUBLIC) {
  90. throw new AuthorizationException(__('messages.group_not_member'));
  91. }
  92. return $this->withViewerRole($group->load(UserService::eagerLoadActor('creator')[0]), $role);
  93. }
  94. /**
  95. * 建团队,建的人成为 owner。同一个人名下不能重名。
  96. *
  97. * @param array{name: string, description?: string|null, status?: int} $data
  98. *
  99. * @throws ValidationException 重名
  100. */
  101. public function create(string $userUid, array $data): GroupInfo
  102. {
  103. // 团队是权限本身,不支持 AI 模型代建(模型从来不是任何团队的成员,改、删本来就过不了)
  104. $this->agents->assertHuman($userUid);
  105. $this->guardUniqueName($userUid, $data['name']);
  106. $group = DB::transaction(function () use ($userUid, $data) {
  107. $now = time() * 1000;
  108. $group = new GroupInfo;
  109. $group->forceFill([
  110. 'id' => app('snowflake')->id(),
  111. 'uid' => (string) Str::uuid(),
  112. 'name' => $data['name'],
  113. 'description' => $data['description'] ?? null,
  114. 'status' => $data['status'] ?? GroupInfo::STATUS_PUBLIC,
  115. 'owner' => $userUid,
  116. 'create_time' => $now,
  117. 'modify_time' => $now,
  118. ])->save();
  119. (new GroupMember)->forceFill([
  120. 'id' => app('snowflake')->id(),
  121. 'user_id' => $userUid,
  122. 'group_id' => $group->uid,
  123. 'group_name' => $group->name,
  124. 'role' => GroupMember::ROLE_OWNER,
  125. 'power' => GroupMember::powerOf(GroupMember::ROLE_OWNER),
  126. ])->save();
  127. return $group;
  128. });
  129. return $this->withViewerRole($group->load(UserService::eagerLoadActor('creator')[0]), GroupMember::ROLE_OWNER);
  130. }
  131. /**
  132. * 改团队信息(owner / manager)。只改传了的字段;改名时同步成员记录上冗余的团队名。
  133. *
  134. * @param array{name?: string, description?: string|null, status?: int} $data
  135. *
  136. * @throws AuthorizationException
  137. * @throws ValidationException 重名
  138. */
  139. public function update(GroupInfo $group, string $actorUid, array $data): GroupInfo
  140. {
  141. $role = $this->authorize($group, $actorUid, GroupAbilityService::MANAGE_GROUP);
  142. if (isset($data['name']) && $data['name'] !== $group->name) {
  143. $this->guardUniqueName($group->owner, $data['name'], $group->uid);
  144. }
  145. DB::transaction(function () use ($group, $data) {
  146. $group->forceFill($data + ['modify_time' => time() * 1000])->save();
  147. if (isset($data['name'])) {
  148. $group->members()->update(['group_name' => $data['name']]);
  149. }
  150. });
  151. return $this->withViewerRole($group->load(UserService::eagerLoadActor('creator')[0]), $role);
  152. }
  153. /**
  154. * 删团队(只有 owner)。名下还有资源就拒绝;否则连同成员记录与共享给它的 share 一起硬删。
  155. *
  156. * @throws AuthorizationException
  157. * @throws BusinessException 名下还有资源(409)
  158. */
  159. public function delete(GroupInfo $group, string $actorUid): void
  160. {
  161. $this->authorize($group, $actorUid, GroupAbilityService::DELETE_GROUP);
  162. $owned = $this->ownedResources($group->uid);
  163. if ($owned !== []) {
  164. throw new BusinessException(
  165. __('messages.group_has_resources'),
  166. 409,
  167. 'group-has-resources',
  168. ['resources' => $owned],
  169. );
  170. }
  171. DB::transaction(function () use ($group) {
  172. $group->shares()->delete();
  173. $group->members()->delete();
  174. $group->delete();
  175. });
  176. }
  177. /**
  178. * 团队名下各类资源的条数,只列有的。
  179. *
  180. * @return array<string, int>
  181. */
  182. public function ownedResources(string $groupUid): array
  183. {
  184. $counts = [];
  185. foreach (self::OWNED as $type => [$model, $column]) {
  186. $count = $model::query()->where($column, $groupUid)->count();
  187. if ($count > 0) {
  188. $counts[$type] = $count;
  189. }
  190. }
  191. return $counts;
  192. }
  193. /**
  194. * @return Builder<GroupInfo>
  195. */
  196. private function withCreator(): Builder
  197. {
  198. return GroupInfo::query()->with(UserService::eagerLoadActor('creator')[0]);
  199. }
  200. /**
  201. * 查看者的角色挂在模型上给 Resource 读,Resource 不查库。
  202. */
  203. private function withViewerRole(GroupInfo $group, ?string $role): GroupInfo
  204. {
  205. $group->setAttribute('viewer_role', $role);
  206. return $group;
  207. }
  208. /**
  209. * @throws AuthorizationException
  210. */
  211. private function authorize(GroupInfo $group, string $actorUid, string $ability): string
  212. {
  213. $role = $this->abilities->roleIn($actorUid, $group->uid);
  214. if (! GroupAbilityService::roleAllows($role, $ability)) {
  215. throw new AuthorizationException(__('messages.group_forbidden'));
  216. }
  217. return $role;
  218. }
  219. /**
  220. * @throws ValidationException
  221. */
  222. private function guardUniqueName(string $ownerUid, string $name, ?string $exceptUid = null): void
  223. {
  224. $exists = GroupInfo::where('owner', $ownerUid)
  225. ->where('name', $name)
  226. ->when($exceptUid, fn (Builder $query, string $uid) => $query->where('uid', '<>', $uid))
  227. ->exists();
  228. if ($exists) {
  229. throw ValidationException::withMessages(['name' => __('messages.group_name_exists')]);
  230. }
  231. }
  232. }