GroupMemberService.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. <?php
  2. namespace App\Services\V3;
  3. use App\Models\GroupInfo;
  4. use App\Models\GroupMember;
  5. use App\Models\UserInfo;
  6. use App\Services\UserService;
  7. use Illuminate\Auth\Access\AuthorizationException;
  8. use Illuminate\Contracts\Pagination\LengthAwarePaginator;
  9. use Illuminate\Validation\ValidationException;
  10. /**
  11. * 团队成员的业务逻辑:我加入的团队、成员列表、加人、改角色、移人 / 退出。
  12. *
  13. * 取代 v2 `GroupMemberController` 的 view=user / view=group / store / destroy。
  14. * v2 那份原地保留不动(铁律 2),两边不共用代码。
  15. *
  16. * 规则:
  17. * - 看成员列表:任何成员
  18. * - 加人、移人、改角色:owner 与 manager({@see GroupAbilityService::MANAGE_MEMBERS})
  19. * - owner 那一行谁都不能改、不能移;本人可以退出(owner 除外)
  20. * - 改角色时 role 与 power 同写,v4 看到的身份与 v3 一致
  21. */
  22. class GroupMemberService
  23. {
  24. /** 加人不指定角色时的默认角色:只读 */
  25. public const DEFAULT_ROLE = GroupMember::ROLE_READER;
  26. public function __construct(private readonly GroupAbilityService $abilities) {}
  27. /**
  28. * 我加入的团队,按加入时间排序。
  29. *
  30. * `owned`:true 只要我创建的,false 只要我参加的别人的团队(取代 v2 的 view2 与
  31. * `group-my-number`——数量读分页的 total)。`search`:按团队名模糊匹配。
  32. *
  33. * @param array{owned?: bool, search?: string|null} $filters
  34. * @return LengthAwarePaginator<int, GroupMember>
  35. */
  36. public function listForUser(string $userUid, array $filters, int $perPage): LengthAwarePaginator
  37. {
  38. return GroupMember::with($this->myGroupRelations())
  39. ->where('user_id', $userUid)
  40. ->whereHas('group', function ($query) use ($userUid, $filters) {
  41. if (array_key_exists('owned', $filters)) {
  42. $query->where('owner', $filters['owned'] ? '=' : '<>', $userUid);
  43. }
  44. if (! empty($filters['search'])) {
  45. $query->where('name', 'ilike', '%'.$filters['search'].'%');
  46. }
  47. })
  48. ->orderBy('created_at')
  49. ->orderBy('id')
  50. ->paginate($perPage);
  51. }
  52. /**
  53. * 团队的成员列表,只有成员看得到。
  54. *
  55. * @return LengthAwarePaginator<int, GroupMember>
  56. *
  57. * @throws AuthorizationException 不是成员
  58. */
  59. public function listForGroup(GroupInfo $group, string $viewerUid, int $perPage): LengthAwarePaginator
  60. {
  61. if (! $this->abilities->membership($viewerUid, $group->uid)) {
  62. throw new AuthorizationException(__('messages.group_not_member'));
  63. }
  64. return $group->members()
  65. ->with(UserService::eagerLoadActor()[0])
  66. ->orderBy('power')
  67. ->orderBy('created_at')
  68. ->orderBy('id')
  69. ->paginate($perPage);
  70. }
  71. /**
  72. * 加一名成员。
  73. *
  74. * @param array{user_id: string, role?: string} $data
  75. *
  76. * @throws AuthorizationException 调用者不能管理成员
  77. * @throws ValidationException 用户不存在或已是成员
  78. */
  79. public function add(GroupInfo $group, string $actorUid, array $data): GroupMember
  80. {
  81. $this->authorizeManage($group, $actorUid);
  82. if (! UserInfo::where('userid', $data['user_id'])->exists()) {
  83. throw ValidationException::withMessages(['user_id' => __('messages.group_user_not_found')]);
  84. }
  85. if ($group->members()->where('user_id', $data['user_id'])->exists()) {
  86. throw ValidationException::withMessages(['user_id' => __('messages.group_member_exists')]);
  87. }
  88. $role = $data['role'] ?? self::DEFAULT_ROLE;
  89. $member = new GroupMember;
  90. $member->forceFill([
  91. 'id' => app('snowflake')->id(),
  92. 'user_id' => $data['user_id'],
  93. 'group_id' => $group->uid,
  94. 'group_name' => $group->name,
  95. 'role' => $role,
  96. 'power' => GroupMember::powerOf($role),
  97. ])->save();
  98. return $member->load(UserService::eagerLoadActor()[0]);
  99. }
  100. /**
  101. * 由 `$addedBy` 把用户拉进团队(邀请链接用);已经是成员就原样返回,角色不变。
  102. * 返回「我的团队」一行的形状(同 {@see listForUser()})。
  103. *
  104. * @throws AuthorizationException `$addedBy` 不能管理成员
  105. */
  106. public function join(GroupInfo $group, string $userUid, string $addedBy): GroupMember
  107. {
  108. $member = $this->abilities->membership($userUid, $group->uid)
  109. ?? $this->add($group, $addedBy, ['user_id' => $userUid, 'role' => self::DEFAULT_ROLE]);
  110. return $member->load($this->myGroupRelations());
  111. }
  112. /**
  113. * 改成员角色。
  114. *
  115. * @param array{role?: string} $data
  116. *
  117. * @throws AuthorizationException 调用者不能管理成员,或目标是 owner
  118. */
  119. public function update(GroupInfo $group, GroupMember $member, string $actorUid, array $data): GroupMember
  120. {
  121. $this->authorizeManage($group, $actorUid);
  122. $this->guardOwner($member);
  123. if (isset($data['role'])) {
  124. $member->forceFill([
  125. 'role' => $data['role'],
  126. 'power' => GroupMember::powerOf($data['role']),
  127. ])->save();
  128. }
  129. return $member->load(UserService::eagerLoadActor()[0]);
  130. }
  131. /**
  132. * 移除成员,或本人退出。owner 不能被移除、也不能退出。
  133. *
  134. * @throws AuthorizationException
  135. */
  136. public function remove(GroupInfo $group, GroupMember $member, string $actorUid): void
  137. {
  138. $this->guardOwner($member);
  139. if ($member->user_id !== $actorUid) {
  140. $this->authorizeManage($group, $actorUid);
  141. }
  142. $member->delete();
  143. }
  144. /**
  145. * 「我的团队」一行要带的团队信息(me/groups 的形状)。
  146. *
  147. * @return list<string>
  148. */
  149. private function myGroupRelations(): array
  150. {
  151. return [
  152. 'group:uid,name,description,owner,status,created_at',
  153. 'group.'.UserService::eagerLoadActor('creator')[0],
  154. ];
  155. }
  156. /**
  157. * @throws AuthorizationException
  158. */
  159. private function authorizeManage(GroupInfo $group, string $actorUid): void
  160. {
  161. $role = $this->abilities->roleIn($actorUid, $group->uid);
  162. if (! GroupAbilityService::roleAllows($role, GroupAbilityService::MANAGE_MEMBERS)) {
  163. throw new AuthorizationException(__('messages.group_forbidden'));
  164. }
  165. }
  166. /**
  167. * @throws AuthorizationException
  168. */
  169. private function guardOwner(GroupMember $member): void
  170. {
  171. if ($member->effectiveRole() === GroupMember::ROLE_OWNER) {
  172. throw new AuthorizationException(__('messages.group_owner_immutable'));
  173. }
  174. }
  175. }