Viewing file: UserMappingController.php (9.96 KB) -rw-r--r-- Select action/file-type: (+) | (+) | (+) | Code (+) | Session (+) | (+) | SDB (+) | (+) | (+) | (+) | (+) | (+) |
<?php
namespace App\Http\Controllers;
use App\Models\User; use App\Models\HilltopAccount; use App\Models\AuditLog; use App\Models\SystemAlert; use App\Models\Campaign; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\DB; use Illuminate\Validation\Rules\Password;
class UserMappingController extends Controller { /** * Get all users with their account mappings and statistics */ public function index(Request $request) { $search = $request->query('search', '');
$users = User::where('type', 'customer') ->with(['hilltopAccount', 'campaigns']) ->when($search, function ($query, $search) { $query->where(function ($q) use ($search) { $q->where('name', 'like', "%{$search}%") ->orWhere('email', 'like', "%{$search}%") ->orWhereHas('hilltopAccount', function ($q) use ($search) { $q->where('alias', 'like', "%{$search}%"); }); }); }) ->get() ->map(function ($user) { $hilltopAccount = $user->hilltopAccount; $campaigns = $user->campaigns; // Calculate total spend from campaigns $totalSpend = $campaigns->sum('budget');
return [ 'id' => $user->id, 'userName' => $user->name, 'userEmail' => $user->email, 'accountAlias' => $hilltopAccount?->alias, 'accountId' => $hilltopAccount?->id, 'bindStatus' => $hilltopAccount ? 'bound' : 'unbound', 'bindTime' => $hilltopAccount?->updated_at?->format('Y-m-d H:i:s'), 'campaigns' => $campaigns->count(), 'totalSpend' => number_format($totalSpend, 2), ]; });
return response()->json($users); }
/** * Create a new user */ public function store(Request $request) { $validated = $request->validate([ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], 'password' => ['required', Password::defaults()], ]);
$user = User::create([ 'name' => $validated['name'], 'email' => $validated['email'], 'password' => Hash::make($validated['password']), 'type' => 'customer', ]);
// Assign customer role // $user->assignRole('customer');
AuditLog::log('User Created', 'user', $user->id, ['email' => $user->email, 'name' => $user->name]); SystemAlert::trigger('info', 'New User Registration', "New user {$user->name} ({$user->email}) registered.");
return response()->json([ 'message' => 'User created successfully', 'user' => [ 'id' => $user->id, 'userName' => $user->name, 'userEmail' => $user->email, 'accountAlias' => null, 'accountId' => null, 'bindStatus' => 'unbound', 'bindTime' => null, 'campaigns' => 0, 'totalSpend' => '0.00', ], ], 201); }
/** * Bind a HilltopAds account to a user */ public function bind(Request $request, $userId) { $validated = $request->validate([ 'account_id' => ['required', 'exists:hilltop_accounts,id'], ]);
$user = User::findOrFail($userId); $account = HilltopAccount::findOrFail($validated['account_id']);
// Check if account is available if ($account->status !== 'available') { return response()->json([ 'message' => 'This account is not available for binding', ], 400); }
// Check if user already has an account if ($user->hilltopAccount) { return response()->json([ 'message' => 'User already has an account bound. Please unbind first.', ], 400); }
DB::beginTransaction(); try { // Update account $account->update([ 'assigned_user_id' => $user->id, 'status' => 'assigned', ]);
// Create audit log AuditLog::log('Account Bound', 'user_mapping', $user->id, [ 'account_alias' => $account->alias, 'user_name' => $user->name, 'user_email' => $user->email, 'hilltop_account_id' => $account->id ]);
DB::commit();
return response()->json([ 'message' => 'Account bound successfully', 'account' => [ 'id' => $account->id, 'alias' => $account->alias, ], ]); } catch (\Exception $e) { DB::rollBack(); return response()->json([ 'message' => 'Failed to bind account', 'error' => $e->getMessage(), ], 500); } }
/** * Unbind a HilltopAds account from a user */ public function unbind($userId) { $user = User::findOrFail($userId); $account = $user->hilltopAccount;
if (!$account) { return response()->json([ 'message' => 'User does not have an account bound', ], 400); }
DB::beginTransaction(); try { $accountAlias = $account->alias;
// Update account $account->update([ 'assigned_user_id' => null, 'status' => 'available', ]);
// Create audit log AuditLog::log('Account Unbound', 'user_mapping', $user->id, [ 'account_alias' => $accountAlias, 'user_name' => $user->name, 'user_email' => $user->email, 'hilltop_account_id' => $account->id ]);
DB::commit();
return response()->json([ 'message' => 'Account unbound successfully', ]); } catch (\Exception $e) { DB::rollBack(); return response()->json([ 'message' => 'Failed to unbind account', 'error' => $e->getMessage(), ], 500); } }
/** * Rebind a user to a different HilltopAds account */ public function rebind(Request $request, $userId) { $validated = $request->validate([ 'account_id' => ['required', 'exists:hilltop_accounts,id'], ]);
$user = User::findOrFail($userId); $oldAccount = $user->hilltopAccount; $newAccount = HilltopAccount::findOrFail($validated['account_id']);
// Check if new account is available if ($newAccount->status !== 'available') { return response()->json([ 'message' => 'The new account is not available for binding', ], 400); }
DB::beginTransaction(); try { // Unbind old account if exists if ($oldAccount) { $oldAccount->update([ 'assigned_user_id' => null, 'status' => 'available', ]); }
// Bind new account $newAccount->update([ 'assigned_user_id' => $user->id, 'status' => 'assigned', ]);
// Create audit log AuditLog::log('Account Rebound', 'user_mapping', $user->id, [ 'old_account_alias' => $oldAccount?->alias, 'new_account_alias' => $newAccount->alias, 'user_name' => $user->name, 'user_email' => $user->email, 'hilltop_account_id' => $newAccount->id ]);
DB::commit();
return response()->json([ 'message' => 'Account rebound successfully', 'account' => [ 'id' => $newAccount->id, 'alias' => $newAccount->alias, ], ]); } catch (\Exception $e) { DB::rollBack(); return response()->json([ 'message' => 'Failed to rebind account', 'error' => $e->getMessage(), ], 500); } }
/** * Get audit history for a user's mappings */ public function auditHistory($userId) { $user = User::findOrFail($userId);
$audits = AuditLog::userMappingAudits() ->where('user_id', $userId) ->with(['hilltopAccount']) ->orderBy('created_at', 'desc') ->get() ->map(function ($audit) { return [ 'id' => $audit->id, 'action' => $audit->action, 'details' => $audit->details, 'accountAlias' => $audit->hilltopAccount?->alias, 'timestamp' => $audit->created_at->format('Y-m-d H:i:s'), 'timeAgo' => $audit->created_at->diffForHumans(), ]; });
return response()->json([ 'user' => [ 'id' => $user->id, 'name' => $user->name, 'email' => $user->email, ], 'audits' => $audits, ]); }
/** * Get user mapping statistics */ public function stats() { $totalUsers = User::where('type', 'customer')->count(); $boundUsers = User::where('type', 'customer') ->whereHas('hilltopAccount') ->count(); $unboundUsers = $totalUsers - $boundUsers;
return response()->json([ 'totalUsers' => $totalUsers, 'boundUsers' => $boundUsers, 'unboundUsers' => $unboundUsers, ]); } }
|