2025-12-29 19:58:58 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Actions\User;
|
|
|
|
|
|
|
|
|
|
use App\Models\User;
|
|
|
|
|
use Exception;
|
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
|
use InvalidArgumentException;
|
|
|
|
|
|
|
|
|
|
class CreateUserAction
|
|
|
|
|
{
|
|
|
|
|
/**
|
|
|
|
|
* @throws Exception
|
|
|
|
|
*/
|
|
|
|
|
public function execute(array $data): User
|
|
|
|
|
{
|
|
|
|
|
try {
|
|
|
|
|
// Validate required fields first
|
2026-08-17 13:30:49 +02:00
|
|
|
if (! isset($data['name']) || empty($data['name'])) {
|
2025-12-29 19:58:58 +01:00
|
|
|
throw new InvalidArgumentException('Name is required');
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-17 13:30:49 +02:00
|
|
|
if (! isset($data['planner_id']) || empty($data['planner_id'])) {
|
2025-12-29 19:58:58 +01:00
|
|
|
throw new InvalidArgumentException('Planner ID is required');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
DB::beginTransaction();
|
|
|
|
|
|
|
|
|
|
Log::info('CreateUserAction: Starting user creation', [
|
|
|
|
|
'name' => $data['name'],
|
|
|
|
|
'planner_id' => $data['planner_id'],
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
// Create the user
|
|
|
|
|
$user = User::create([
|
|
|
|
|
'name' => $data['name'],
|
|
|
|
|
'planner_id' => $data['planner_id'],
|
|
|
|
|
]);
|
|
|
|
|
|
2026-08-17 13:30:49 +02:00
|
|
|
if (! $user) {
|
2025-12-29 19:58:58 +01:00
|
|
|
throw new Exception('User creation returned null');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Log::info('CreateUserAction: User creation result', [
|
|
|
|
|
'user_id' => $user->id,
|
|
|
|
|
'name' => $user->name,
|
|
|
|
|
'planner_id' => $user->planner_id,
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
// Verify the user was actually created
|
|
|
|
|
$createdUser = User::find($user->id);
|
2026-08-17 13:30:49 +02:00
|
|
|
if (! $createdUser) {
|
2025-12-29 19:58:58 +01:00
|
|
|
throw new Exception('User creation did not persist to database');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ($createdUser->name !== $data['name']) {
|
|
|
|
|
throw new Exception('User creation data mismatch');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
DB::commit();
|
|
|
|
|
|
|
|
|
|
Log::info('CreateUserAction: User successfully created', [
|
|
|
|
|
'user_id' => $user->id,
|
|
|
|
|
'name' => $user->name,
|
|
|
|
|
'planner_id' => $user->planner_id,
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
return $user;
|
|
|
|
|
|
|
|
|
|
} catch (Exception $e) {
|
|
|
|
|
DB::rollBack();
|
|
|
|
|
|
|
|
|
|
Log::error('CreateUserAction: User creation failed', [
|
|
|
|
|
'name' => $data['name'] ?? 'N/A',
|
|
|
|
|
'planner_id' => $data['planner_id'] ?? 'N/A',
|
|
|
|
|
'error' => $e->getMessage(),
|
|
|
|
|
'trace' => $e->getTraceAsString(),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
throw $e;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|