AgentService.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. <?php
  2. namespace App\Services\Agent;
  3. use App\Models\Agent\Agent;
  4. use App\Models\Agent\AgentCommissionRule;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Hash;
  7. use Illuminate\Support\Str;
  8. class AgentService
  9. {
  10. public function create(array $data, ?int $createdBy = null, ?Agent $scopeAgent = null): Agent
  11. {
  12. return DB::transaction(function () use ($data, $createdBy, $scopeAgent): Agent {
  13. $parentId = isset($data['parent_id']) ? (int) $data['parent_id'] : null;
  14. if ($scopeAgent) {
  15. if ((int) $scopeAgent->level !== Agent::LEVEL_ONE) {
  16. throw new \RuntimeException('二级代理不能继续新增下级代理');
  17. }
  18. if ($parentId && $parentId !== (int) $scopeAgent->id) {
  19. throw new \RuntimeException('一级代理只能新增自己的直属二级代理');
  20. }
  21. $parentId = (int) $scopeAgent->id;
  22. } elseif ($parentId) {
  23. throw new \RuntimeException('总后台只能新增一级代理');
  24. }
  25. $parent = $parentId ? Agent::query()->lockForUpdate()->findOrFail($parentId) : null;
  26. if ($scopeAgent && $parent && (int) $parent->status !== Agent::STATUS_ENABLED) {
  27. throw new \RuntimeException('不能在已禁用代理下新增账号');
  28. }
  29. if ($parent) {
  30. $this->assertRatesWithinParent($parent, $data);
  31. }
  32. $level = $parent ? ((int) $parent->level + 1) : Agent::LEVEL_ONE;
  33. if ($level > Agent::MAX_LEVEL) {
  34. throw new \RuntimeException('代理层级最多为二级');
  35. }
  36. $agent = Agent::query()->create([
  37. 'parent_id' => $parent?->id,
  38. 'path' => '/',
  39. 'level' => $level,
  40. 'username' => trim((string) $data['username']),
  41. 'password' => Hash::make((string) $data['password']),
  42. 'withdraw_password' => empty($data['withdraw_password']) ? '' : Hash::make((string) $data['withdraw_password']),
  43. 'real_name' => trim((string) ($data['real_name'] ?? '')),
  44. 'invitation_code' => $this->invitationCode(),
  45. 'deposit_fee_rate' => (string) ($data['deposit_fee_rate'] ?? 0),
  46. 'withdraw_fee_rate' => (string) ($data['withdraw_fee_rate'] ?? 0),
  47. 'flow_commission_rate' => (string) ($data['flow_commission_rate'] ?? 0),
  48. 'profit_commission_rate' => (string) ($data['profit_commission_rate'] ?? 0),
  49. 'status' => (int) ($data['status'] ?? Agent::STATUS_ENABLED),
  50. 'created_by' => $createdBy,
  51. ]);
  52. $agent->path = ($parent ? rtrim((string) $parent->path, '/') . '/' : '/') . $agent->id . '/';
  53. $agent->save();
  54. AgentCommissionRule::query()->create([
  55. 'agent_id' => $agent->id,
  56. 'flow_rate' => $agent->flow_commission_rate,
  57. 'profit_rate' => $agent->profit_commission_rate,
  58. 'effective_from' => now()->toDateString(),
  59. 'status' => 1,
  60. 'created_by' => $createdBy,
  61. ]);
  62. return $agent->fresh();
  63. });
  64. }
  65. public function update(Agent $agent, array $data, ?Agent $scopeAgent = null): Agent
  66. {
  67. return DB::transaction(function () use ($agent, $data, $scopeAgent): Agent {
  68. $agent = Agent::query()->lockForUpdate()->findOrFail($agent->id);
  69. if ($scopeAgent) {
  70. $this->assertVisible($scopeAgent, (int) $agent->id);
  71. if ($agent->parent) {
  72. $this->assertRatesWithinParent($agent->parent, $data);
  73. }
  74. $this->assertRatesCoverChildren($agent, $data);
  75. } elseif (array_key_exists('parent_id', $data)) {
  76. $this->move($agent, $data['parent_id'] === null ? null : (int) $data['parent_id']);
  77. }
  78. if (array_key_exists('real_name', $data)) {
  79. $agent->real_name = trim((string) ($data['real_name'] ?? ''));
  80. }
  81. foreach (['username', 'status', 'deposit_fee_rate', 'withdraw_fee_rate', 'flow_commission_rate', 'profit_commission_rate'] as $field) {
  82. if (array_key_exists($field, $data) && $data[$field] !== null) {
  83. $agent->{$field} = $data[$field];
  84. }
  85. }
  86. if (!empty($data['password'])) {
  87. $agent->password = Hash::make((string) $data['password']);
  88. }
  89. if (!empty($data['withdraw_password'])) {
  90. $agent->withdraw_password = Hash::make((string) $data['withdraw_password']);
  91. }
  92. $agent->save();
  93. return $agent->fresh();
  94. });
  95. }
  96. public function assertVisible(Agent $root, int $targetId): void
  97. {
  98. if ((int) $root->id === $targetId) {
  99. return;
  100. }
  101. $visible = Agent::query()->whereKey($targetId)->where('path', 'like', rtrim((string) $root->path, '/') . '/%')->exists();
  102. if (!$visible) {
  103. throw new \RuntimeException('无权访问该代理');
  104. }
  105. }
  106. private function invitationCode(): string
  107. {
  108. do {
  109. $code = strtoupper(Str::random(10));
  110. } while (Agent::query()->where('invitation_code', $code)->exists());
  111. return $code;
  112. }
  113. private function assertRatesWithinParent(Agent $parent, array $data): void
  114. {
  115. foreach (['flow_commission_rate', 'profit_commission_rate'] as $field) {
  116. if (array_key_exists($field, $data) && bccomp((string) $data[$field], (string) $parent->{$field}, 4) > 0) {
  117. throw new \RuntimeException('下级代理佣金比例不能高于上级');
  118. }
  119. }
  120. }
  121. private function assertRatesCoverChildren(Agent $agent, array $data): void
  122. {
  123. foreach (['flow_commission_rate', 'profit_commission_rate'] as $field) {
  124. if (!array_key_exists($field, $data)) {
  125. continue;
  126. }
  127. $maxChildRate = Agent::query()->where('parent_id', $agent->id)->max($field) ?? 0;
  128. if (bccomp((string) $data[$field], (string) $maxChildRate, 4) < 0) {
  129. throw new \RuntimeException('代理佣金比例不能低于现有下级比例');
  130. }
  131. }
  132. }
  133. private function move(Agent $agent, ?int $parentId): void
  134. {
  135. if ($parentId === (int) $agent->id) {
  136. throw new \RuntimeException('上级代理不能是自己');
  137. }
  138. $currentParentId = $agent->parent_id === null ? null : (int) $agent->parent_id;
  139. if ($parentId === $currentParentId) {
  140. return;
  141. }
  142. $parent = $parentId ? Agent::query()->lockForUpdate()->findOrFail($parentId) : null;
  143. if ($parent && str_starts_with((string) $parent->path, (string) $agent->path)) {
  144. throw new \RuntimeException('不能把代理移动到自己的下级');
  145. }
  146. if ($parent && (int) $parent->level !== Agent::LEVEL_ONE) {
  147. throw new \RuntimeException('二级代理不能作为上级代理');
  148. }
  149. if ($parent) {
  150. $this->assertRatesWithinParent($parent, [
  151. 'flow_commission_rate' => $agent->flow_commission_rate,
  152. 'profit_commission_rate' => $agent->profit_commission_rate,
  153. ]);
  154. }
  155. $oldPath = (string) $agent->path;
  156. $oldLevel = (int) $agent->level;
  157. $newLevel = $parent ? ((int) $parent->level + 1) : 1;
  158. $newPath = ($parent ? rtrim((string) $parent->path, '/') . '/' : '/') . $agent->id . '/';
  159. $descendants = Agent::query()->where('path', 'like', rtrim($oldPath, '/') . '/%')->lockForUpdate()->get();
  160. $newMaxLevel = $descendants->max(fn(Agent $descendant) =>
  161. (int) $descendant->level + $newLevel - $oldLevel
  162. ) ?? $newLevel;
  163. if ($newLevel > Agent::MAX_LEVEL || $newMaxLevel > Agent::MAX_LEVEL) {
  164. throw new \RuntimeException('移动后会产生三级代理,操作已拒绝');
  165. }
  166. $agent->parent_id = $parent?->id;
  167. $agent->path = $newPath;
  168. $agent->level = $newLevel;
  169. foreach ($descendants as $descendant) {
  170. $descendant->path = $newPath . substr((string) $descendant->path, strlen($oldPath));
  171. $descendant->level = max(1, (int) $descendant->level + $newLevel - $oldLevel);
  172. $descendant->save();
  173. }
  174. }
  175. }