AgentService.php 15 KB

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