AgentService.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. <?php
  2. namespace App\Services\Agent;
  3. use App\Models\Agent\Agent;
  4. use App\Models\Agent\AgentFlowCommissionProfile;
  5. use App\Models\Agent\AgentProfitCommissionProfile;
  6. use App\Models\Agent\AgentToken;
  7. use Illuminate\Support\Facades\DB;
  8. use Illuminate\Support\Facades\Hash;
  9. use Illuminate\Support\Str;
  10. class AgentService
  11. {
  12. public function __construct(
  13. private AgentFlowCommissionAssignmentService $flowAssignments,
  14. private AgentProfitCommissionAssignmentService $profitAssignments
  15. ) {
  16. }
  17. public function create(array $data, ?int $createdBy = null, ?Agent $scopeAgent = null): Agent
  18. {
  19. return DB::transaction(function () use ($data, $createdBy, $scopeAgent): Agent {
  20. $parentId = isset($data['parent_id']) ? (int) $data['parent_id'] : null;
  21. if ($scopeAgent) {
  22. if ((int) $scopeAgent->level !== Agent::LEVEL_ONE) {
  23. throw new \RuntimeException('二级代理不能继续新增下级代理');
  24. }
  25. if ($parentId && $parentId !== (int) $scopeAgent->id) {
  26. throw new \RuntimeException('一级代理只能新增自己的直属二级代理');
  27. }
  28. $parentId = (int) $scopeAgent->id;
  29. } elseif ($parentId) {
  30. throw new \RuntimeException('总后台只能新增一级代理');
  31. }
  32. $parent = $parentId ? Agent::query()->lockForUpdate()->findOrFail($parentId) : null;
  33. if ($scopeAgent && $parent && (int) $parent->status !== Agent::STATUS_ENABLED) {
  34. throw new \RuntimeException('不能在已禁用代理下新增账号');
  35. }
  36. $level = $parent ? ((int) $parent->level + 1) : Agent::LEVEL_ONE;
  37. if ($level > Agent::MAX_LEVEL) {
  38. throw new \RuntimeException('代理层级最多为二级');
  39. }
  40. $flowProfileId = (int)($data['flow_commission_profile_id']
  41. ?? $parent?->flow_commission_profile_id
  42. ?? AgentFlowCommissionProfile::officialDefaultId());
  43. if ($flowProfileId <= 0) throw new \RuntimeException('请先配置默认代理流水佣金方案');
  44. $flowProfile = AgentFlowCommissionProfile::query()->findOrFail($flowProfileId);
  45. $this->assertProfileAssignable($parent, $flowProfile, $scopeAgent);
  46. $profitProfileId = (int) ($data['profit_commission_profile_id']
  47. ?? $parent?->profit_commission_profile_id
  48. ?? AgentProfitCommissionProfile::officialDefaultId());
  49. if ($profitProfileId <= 0) throw new \RuntimeException('请先配置默认代理盈亏佣金比例');
  50. $profitProfile = AgentProfitCommissionProfile::query()->findOrFail($profitProfileId);
  51. $this->assertProfileAssignable($parent, $profitProfile, $scopeAgent);
  52. $agent = Agent::query()->create([
  53. 'parent_id' => $parent?->id,
  54. 'path' => '/',
  55. 'level' => $level,
  56. 'username' => trim((string) $data['username']),
  57. 'password' => Hash::make((string) $data['password']),
  58. 'withdraw_password' => empty($data['withdraw_password']) ? '' : Hash::make((string) $data['withdraw_password']),
  59. 'real_name' => trim((string) ($data['real_name'] ?? '')),
  60. 'invitation_code' => $this->invitationCode(),
  61. 'deposit_fee_rate' => (string) ($data['deposit_fee_rate'] ?? 0),
  62. 'withdraw_fee_rate' => (string) ($data['withdraw_fee_rate'] ?? 0),
  63. 'profit_commission_rate' => (string) ($data['profit_commission_rate'] ?? 0),
  64. 'flow_commission_profile_id' => $flowProfileId,
  65. 'profit_commission_profile_id' => $profitProfileId,
  66. 'status' => (int) ($data['status'] ?? Agent::STATUS_ENABLED),
  67. 'created_by' => $createdBy,
  68. ]);
  69. $agent->path = ($parent ? rtrim((string) $parent->path, '/') . '/' : '/') . $agent->id . '/';
  70. $agent->save();
  71. $this->flowAssignments->assign($agent, $flowProfile, now()->toDateString(), $createdBy);
  72. $this->profitAssignments->assign($agent, $profitProfile, now()->toDateString(), $createdBy);
  73. return $agent->fresh(['flowCommissionProfile', 'profitCommissionProfile']);
  74. });
  75. }
  76. public function update(Agent $agent, array $data, ?Agent $scopeAgent = null, ?int $createdBy = null): Agent
  77. {
  78. return DB::transaction(function () use ($agent, $data, $scopeAgent, $createdBy): Agent {
  79. $agent = Agent::query()->lockForUpdate()->findOrFail($agent->id);
  80. $newFlowProfile = null;
  81. if (array_key_exists('flow_commission_profile_id', $data)
  82. && $data['flow_commission_profile_id'] !== null
  83. && (int)$data['flow_commission_profile_id'] !== (int)$agent->flow_commission_profile_id) {
  84. $newFlowProfile = AgentFlowCommissionProfile::query()
  85. ->findOrFail((int)$data['flow_commission_profile_id']);
  86. $this->assertFlowProfileCoversChildren($agent, $newFlowProfile);
  87. }
  88. $newProfitProfile = null;
  89. if (array_key_exists('profit_commission_profile_id', $data)
  90. && $data['profit_commission_profile_id'] !== null
  91. && (int) $data['profit_commission_profile_id'] !== (int) $agent->profit_commission_profile_id) {
  92. $newProfitProfile = AgentProfitCommissionProfile::query()
  93. ->findOrFail((int) $data['profit_commission_profile_id']);
  94. $this->assertProfitProfileCoversChildren($agent, $newProfitProfile);
  95. }
  96. if ($scopeAgent) {
  97. $this->assertVisible($scopeAgent, (int) $agent->id);
  98. } elseif (array_key_exists('parent_id', $data)) {
  99. $this->move(
  100. $agent,
  101. $data['parent_id'] === null ? null : (int)$data['parent_id'],
  102. $newFlowProfile,
  103. $newProfitProfile
  104. );
  105. }
  106. $parent = $agent->parent_id ? Agent::query()->findOrFail($agent->parent_id) : null;
  107. if ($newFlowProfile) $this->assertProfileAssignable($parent, $newFlowProfile, $scopeAgent);
  108. if ($newProfitProfile) $this->assertProfileAssignable($parent, $newProfitProfile, $scopeAgent);
  109. if (array_key_exists('real_name', $data)) {
  110. $agent->real_name = trim((string) ($data['real_name'] ?? ''));
  111. }
  112. foreach (['username', 'status', 'deposit_fee_rate', 'withdraw_fee_rate', 'flow_commission_profile_id', 'profit_commission_profile_id'] as $field) {
  113. if (array_key_exists($field, $data) && $data[$field] !== null) {
  114. $agent->{$field} = $data[$field];
  115. }
  116. }
  117. if (!empty($data['password'])) {
  118. $agent->password = Hash::make((string) $data['password']);
  119. }
  120. if (!empty($data['withdraw_password'])) {
  121. $agent->withdraw_password = Hash::make((string) $data['withdraw_password']);
  122. }
  123. $agent->save();
  124. if (!empty($data['password']) || (int) $agent->status === Agent::STATUS_DISABLED) {
  125. AgentToken::query()->where('agent_id', $agent->id)->delete();
  126. }
  127. if ($newFlowProfile) {
  128. $this->flowAssignments->assign($agent, $newFlowProfile, now()->toDateString(), $createdBy);
  129. }
  130. if ($newProfitProfile) {
  131. $this->profitAssignments->assign($agent, $newProfitProfile, now()->toDateString(), $createdBy);
  132. }
  133. return $agent->fresh(['flowCommissionProfile', 'profitCommissionProfile']);
  134. });
  135. }
  136. public function assertVisible(Agent $root, int $targetId): void
  137. {
  138. if ((int) $root->id === $targetId) {
  139. return;
  140. }
  141. $visible = Agent::query()->whereKey($targetId)->where('path', 'like', rtrim((string) $root->path, '/') . '/%')->exists();
  142. if (!$visible) {
  143. throw new \RuntimeException('无权访问该代理');
  144. }
  145. }
  146. private function invitationCode(): string
  147. {
  148. do {
  149. $code = strtoupper(Str::random(10));
  150. } while (Agent::query()->where('invitation_code', $code)->exists());
  151. return $code;
  152. }
  153. private function assertProfileAssignable(
  154. ?Agent $parent,
  155. AgentFlowCommissionProfile|AgentProfitCommissionProfile $profile,
  156. ?Agent $scopeAgent = null
  157. ): void {
  158. $isFlow = $profile instanceof AgentFlowCommissionProfile;
  159. if ($scopeAgent) {
  160. if (!$parent) throw new \RuntimeException('一级代理只能给直属下级指定方案');
  161. if (!$profile->isOfficial() && !$profile->isOwnedBy((int) $parent->id)) {
  162. throw new \RuntimeException($isFlow ? '只能使用官方方案或自己创建的流水方案' : '只能使用官方方案或自己创建的盈亏方案');
  163. }
  164. } elseif (!$profile->isOfficial()) {
  165. throw new \RuntimeException($isFlow ? '总后台只能给代理指定官方流水方案' : '总后台只能给代理指定官方盈亏方案');
  166. }
  167. if ($parent) {
  168. $isFlow
  169. ? $this->assertFlowProfileWithinParent($parent, $profile)
  170. : $this->assertProfitProfileWithinParent($parent, $profile);
  171. }
  172. }
  173. private function assertFlowProfileWithinParent(Agent $parent, AgentFlowCommissionProfile $profile): void
  174. {
  175. $parent->loadMissing('flowCommissionProfile');
  176. foreach (AgentFlowCommissionProfile::RATE_FIELDS as $field) {
  177. if (!$parent->flowCommissionProfile) throw new \RuntimeException('上级代理未关联流水佣金方案');
  178. $parentRate = (string)$parent->flowCommissionProfile->{$field};
  179. if (bccomp((string)$profile->{$field}, $parentRate, 4) > 0) {
  180. throw new \RuntimeException('下级代理流水佣金方案不能高于上级方案');
  181. }
  182. }
  183. }
  184. private function assertProfitProfileWithinParent(Agent $parent, AgentProfitCommissionProfile $profile): void
  185. {
  186. $parent->loadMissing('profitCommissionProfile');
  187. foreach (AgentProfitCommissionProfile::RATE_FIELDS as $field) {
  188. if (!$parent->profitCommissionProfile) throw new \RuntimeException('上级代理未关联盈亏佣金方案');
  189. $parentRate = (string) $parent->profitCommissionProfile->{$field};
  190. if (bccomp((string) $profile->{$field}, $parentRate, 4) > 0) {
  191. throw new \RuntimeException('下级代理盈亏佣金方案不能高于上级方案');
  192. }
  193. }
  194. }
  195. private function assertFlowProfileCoversChildren(Agent $agent, AgentFlowCommissionProfile $profile): void
  196. {
  197. $children = Agent::query()->with('flowCommissionProfile')->where('parent_id', $agent->id)->get();
  198. foreach ($children as $child) {
  199. foreach (AgentFlowCommissionProfile::RATE_FIELDS as $field) {
  200. if (!$child->flowCommissionProfile) throw new \RuntimeException('下级代理未关联流水佣金方案');
  201. $childRate = (string)$child->flowCommissionProfile->{$field};
  202. if (bccomp((string)$profile->{$field}, $childRate, 4) < 0) {
  203. throw new \RuntimeException('代理流水佣金方案不能低于现有下级方案');
  204. }
  205. }
  206. }
  207. }
  208. private function assertProfitProfileCoversChildren(Agent $agent, AgentProfitCommissionProfile $profile): void
  209. {
  210. $children = Agent::query()->with('profitCommissionProfile')->where('parent_id', $agent->id)->get();
  211. foreach ($children as $child) {
  212. foreach (AgentProfitCommissionProfile::RATE_FIELDS as $field) {
  213. if (!$child->profitCommissionProfile) throw new \RuntimeException('下级代理未关联盈亏佣金方案');
  214. $childRate = (string) $child->profitCommissionProfile->{$field};
  215. if (bccomp((string) $profile->{$field}, $childRate, 4) < 0) {
  216. throw new \RuntimeException('代理盈亏佣金方案不能低于现有下级方案');
  217. }
  218. }
  219. }
  220. }
  221. private function move(
  222. Agent $agent,
  223. ?int $parentId,
  224. ?AgentFlowCommissionProfile $flowProfile = null,
  225. ?AgentProfitCommissionProfile $profitProfile = null
  226. ): void {
  227. if ($parentId === (int) $agent->id) {
  228. throw new \RuntimeException('上级代理不能是自己');
  229. }
  230. $currentParentId = $agent->parent_id === null ? null : (int) $agent->parent_id;
  231. if ($parentId === $currentParentId) {
  232. return;
  233. }
  234. $parent = $parentId ? Agent::query()->lockForUpdate()->findOrFail($parentId) : null;
  235. if ($parent && str_starts_with((string) $parent->path, (string) $agent->path)) {
  236. throw new \RuntimeException('不能把代理移动到自己的下级');
  237. }
  238. if ($parent && (int) $parent->level !== Agent::LEVEL_ONE) {
  239. throw new \RuntimeException('二级代理不能作为上级代理');
  240. }
  241. if ($parent) {
  242. $agent->loadMissing(['flowCommissionProfile', 'profitCommissionProfile']);
  243. $effectiveFlowProfile = $flowProfile ?: $agent->flowCommissionProfile;
  244. if (!$effectiveFlowProfile) throw new \RuntimeException('代理未关联流水佣金方案');
  245. $this->assertProfileAssignable($parent, $effectiveFlowProfile);
  246. $effectiveProfitProfile = $profitProfile ?: $agent->profitCommissionProfile;
  247. if (!$effectiveProfitProfile) throw new \RuntimeException('代理未关联盈亏佣金方案');
  248. $this->assertProfileAssignable($parent, $effectiveProfitProfile);
  249. } else {
  250. $agent->loadMissing(['flowCommissionProfile', 'profitCommissionProfile']);
  251. $effectiveFlowProfile = $flowProfile ?: $agent->flowCommissionProfile;
  252. if ($effectiveFlowProfile && !$effectiveFlowProfile->isOfficial()) {
  253. throw new \RuntimeException('一级代理只能使用官方流水方案');
  254. }
  255. $effectiveProfitProfile = $profitProfile ?: $agent->profitCommissionProfile;
  256. if ($effectiveProfitProfile && !$effectiveProfitProfile->isOfficial()) {
  257. throw new \RuntimeException('一级代理只能使用官方盈亏方案');
  258. }
  259. }
  260. $oldPath = (string) $agent->path;
  261. $oldLevel = (int) $agent->level;
  262. $newLevel = $parent ? ((int) $parent->level + 1) : 1;
  263. $newPath = ($parent ? rtrim((string) $parent->path, '/') . '/' : '/') . $agent->id . '/';
  264. $descendants = Agent::query()->where('path', 'like', rtrim($oldPath, '/') . '/%')->lockForUpdate()->get();
  265. $newMaxLevel = $descendants->max(fn(Agent $descendant) =>
  266. (int) $descendant->level + $newLevel - $oldLevel
  267. ) ?? $newLevel;
  268. if ($newLevel > Agent::MAX_LEVEL || $newMaxLevel > Agent::MAX_LEVEL) {
  269. throw new \RuntimeException('移动后会产生三级代理,操作已拒绝');
  270. }
  271. $agent->parent_id = $parent?->id;
  272. $agent->path = $newPath;
  273. $agent->level = $newLevel;
  274. foreach ($descendants as $descendant) {
  275. $descendant->path = $newPath . substr((string) $descendant->path, strlen($oldPath));
  276. $descendant->level = max(1, (int) $descendant->level + $newLevel - $oldLevel);
  277. $descendant->save();
  278. }
  279. }
  280. }