| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- <?php
- namespace App\Http\Controllers\agent;
- use App\Http\Controllers\AgentApiController;
- use App\Models\Agent\Agent;
- use App\Models\User;
- use App\Services\Agent\AgentDomainService;
- use App\Services\MemberSuperiorService;
- use App\Services\Sharing\ShareRelations;
- use Carbon\Carbon;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- class ReferralController extends AgentApiController
- {
- public function resolve(Request $request, AgentDomainService $domains)
- {
- return $this->execute(function () use ($request, $domains) {
- $data = $request->validate([
- 'agent_code' => ['nullable', 'string', 'max:32', 'required_without:domain'],
- 'domain' => ['nullable', 'string', 'max:255', 'required_without:agent_code'],
- ]);
- $agent = $domains->resolve($data['agent_code'] ?? null, $data['domain'] ?? null);
- if (!$agent?->isJoint()) throw new \RuntimeException('代理推广信息不存在或已禁用');
- return [
- 'agent_id' => (int) $agent->id,
- 'agent_code' => $agent->invitation_code,
- 'agent_name' => $agent->username,
- ];
- });
- }
- public function bind(Request $request, AgentDomainService $domains)
- {
- return $this->execute(function () use ($request, $domains) {
- $data = $request->validate([
- 'agent_code' => ['nullable', 'string', 'max:32', 'required_without:domain'],
- 'domain' => ['nullable', 'string', 'max:255', 'required_without:agent_code'],
- ]);
- $agent = $domains->resolve($data['agent_code'] ?? null, $data['domain'] ?? null);
- if (!$agent) {
- throw new \RuntimeException('代理推广信息不存在或已禁用');
- }
- // 入股代理的历史邀请码和域名可以传入,但不会改变会员归属。
- if (!$agent->isJoint()) {
- return ['user_id' => (int) $request->user->id, 'agent_id' => null];
- }
- return DB::transaction(function () use ($request, $agent) {
- ShareRelations::lock();
- $user = User::query()->lockForUpdate()->findOrFail($request->user->id);
- $agent = Agent::query()->whereKey($agent->id)->where('status', Agent::STATUS_ENABLED)->lockForUpdate()->first();
- if (!$agent) throw new \RuntimeException('代理推广信息不存在或已禁用');
- if (!$agent->isJoint() || MemberSuperiorService::hasMemberSuperior($user)) {
- return ['user_id' => (int) $user->id, 'agent_id' => null];
- }
- if (MemberSuperiorService::hasJointAgent($user)) {
- if ((int) $user->agent_id !== (int) $agent->id) {
- throw new \RuntimeException('会员已绑定其他代理,不能重复修改');
- }
- return ['user_id' => (int) $user->id, 'agent_id' => (int) $agent->id];
- }
- $createdAt = $user->getRawOriginal('created_at');
- if (!$createdAt || Carbon::parse($createdAt)->lt(now()->subMinutes(config('agent.referral_bind_minutes', 30)))) {
- throw new \RuntimeException('推广归属只能在新会员注册后及时绑定');
- }
- $user->agent_id = $agent->id;
- $user->agent_user_code = null;
- $user->save();
- return ['user_id' => (int) $user->id, 'agent_id' => (int) $agent->id];
- });
- });
- }
- }
|