diff --git a/amp-laravel/app/Http/Controllers/Common/AuthController.php b/amp-laravel/app/Http/Controllers/Common/AuthController.php index 3189914e..53bd60db 100644 --- a/amp-laravel/app/Http/Controllers/Common/AuthController.php +++ b/amp-laravel/app/Http/Controllers/Common/AuthController.php @@ -3,9 +3,11 @@ namespace App\Http\Controllers\Common; use Throwable; +use App\Services\ContactMessageService; use App\Services\UserLoginService; use App\Http\Controllers\Controller; use App\Http\Requests\AuthRequestLogin; +use App\Http\Requests\ContactMessageRequest; use Illuminate\Auth\AuthenticationException; class AuthController extends Controller @@ -30,6 +32,26 @@ public function login(AuthRequestLogin $request) } } + public function insertMessage(ContactMessageRequest $request) + { + try { + $validatedData = $request->validated(); + $response = ContactMessageService::insertMessage($validatedData); + + $messageData = [ + 'id' => $response->id, + 'name' => $response->name, + 'email' => $response->email, + 'phone_number' => $response->phone_number, + 'message' => $response->message ?? null, + ]; + + return $this->loginMessageResponse(true, "Message Submitted Successfully", $messageData, 200); + } catch (Throwable $e) { + return $this->errorMessageResponse(false, "Something went wrong during Contact Message insertion", $e->getMessage(), 500); + } + } + public function logout() { $response = UserLoginService::logout(); diff --git a/amp-laravel/app/Http/Controllers/Provider/ProviderFunctionsController.php b/amp-laravel/app/Http/Controllers/Provider/ProviderFunctionsController.php index 2d7ddce5..34ac5c7b 100644 --- a/amp-laravel/app/Http/Controllers/Provider/ProviderFunctionsController.php +++ b/amp-laravel/app/Http/Controllers/Provider/ProviderFunctionsController.php @@ -57,9 +57,9 @@ public function getUsers($id) try { $users = GetAllClientUsersService::getAll($id); - return $this->messageResponse(true, "Messages retrieved successfully", 200, $users); + return $this->messageResponse(true, "Users retrieved successfully", 200, $users); } catch (\Exception $e) { - return $this->errorMessageResponse(false, $e->getMessage(), "Failed to retrieve messages", 500); + return $this->errorMessageResponse(false, $e->getMessage(), "Failed to retrieve users", 500); } } @@ -68,9 +68,9 @@ public function getMetrics($id) try { $metrics = GetAllClientMetricsService::getAll($id); - return $this->messageResponse(true, "Messages retrieved successfully", 200, $metrics); + return $this->messageResponse(true, "Metrics retrieved successfully", 200, $metrics); } catch (\Exception $e) { - return $this->errorMessageResponse(false, $e->getMessage(), "Failed to retrieve messages", 500); + return $this->errorMessageResponse(false, $e->getMessage(), "Failed to retrieve metrics", 500); } } @@ -79,9 +79,9 @@ public function getLines($id) try { $lines = GetAllLinesService::getAll($id); - return $this->messageResponse(true, "Messages retrieved successfully", 200, $lines); + return $this->messageResponse(true, "Lines retrieved successfully", 200, $lines); } catch (\Exception $e) { - return $this->errorMessageResponse(false, $e->getMessage(), "Failed to retrieve messages", 500); + return $this->errorMessageResponse(false, $e->getMessage(), "Failed to retrieve lines", 500); } } diff --git a/amp-laravel/app/Http/Requests/ContactMessageRequest.php b/amp-laravel/app/Http/Requests/ContactMessageRequest.php new file mode 100644 index 00000000..b8fe3386 --- /dev/null +++ b/amp-laravel/app/Http/Requests/ContactMessageRequest.php @@ -0,0 +1,31 @@ +|string> + */ + public function rules(): array + { + return [ + 'name' => 'required|string|max:255', + 'email' => 'required|email|max:255', + 'phone_number' => 'required|string|max:20', + 'message' => 'sometimes|required|string|max:1000', + ]; + } +} diff --git a/amp-laravel/app/Models/ContactForm.php b/amp-laravel/app/Models/ContactForm.php index c43d921f..be09d5d0 100644 --- a/amp-laravel/app/Models/ContactForm.php +++ b/amp-laravel/app/Models/ContactForm.php @@ -12,7 +12,7 @@ class ContactForm extends Model protected $fillable = [ 'name', 'email', - 'phone', + 'phone_number', 'message', ]; diff --git a/amp-laravel/app/Services/ContactMessageService.php b/amp-laravel/app/Services/ContactMessageService.php new file mode 100644 index 00000000..81b1adb4 --- /dev/null +++ b/amp-laravel/app/Services/ContactMessageService.php @@ -0,0 +1,18 @@ + $data['name'], + 'email' => $data['email'], + 'phone_number' => $data['phone_number'], + 'message' => $data['message'] ?? null, + ]); + } +} diff --git a/amp-laravel/app/Services/Provider/GetOverviewDataService.php b/amp-laravel/app/Services/Provider/GetOverviewDataService.php index 572c3ac5..c8d73613 100644 --- a/amp-laravel/app/Services/Provider/GetOverviewDataService.php +++ b/amp-laravel/app/Services/Provider/GetOverviewDataService.php @@ -14,9 +14,9 @@ public static function getOverviewData(int $providerId): array $clientSlaveIds = Metric::whereIn('master_id', $masterIds)->distinct()->pluck('slave_id'); $totalClients = User::whereIn('slave_id', $clientSlaveIds)->where('user_type', 'Client')->count(); $totalPowerThisMonth = Metric::whereIn('master_id', $masterIds) - ->whereYear('date_month', now()->year) - ->whereMonth('date_month', now()->month) + ->whereRaw('SUBSTRING(date_month, 1, 2) = ?', [now()->format('m')]) ->sum('power'); + $averageVoltage = Metric::whereIn('master_id', $masterIds)->avg('voltage'); return [ diff --git a/amp-laravel/app/Services/Provider/GetPowerUsageByClientService.php b/amp-laravel/app/Services/Provider/GetPowerUsageByClientService.php index 668aba56..b841a04b 100644 --- a/amp-laravel/app/Services/Provider/GetPowerUsageByClientService.php +++ b/amp-laravel/app/Services/Provider/GetPowerUsageByClientService.php @@ -10,23 +10,29 @@ class GetPowerUsageByClientService { public static function getPowerUsageByClient(int $providerId): array { - $masters = Master::where('user_id', $providerId)->with(['metrics' => function ($query) { - $query->whereYear('date_month', now()->year) - ->whereMonth('date_month', now()->month); - }])->get(); + $masters = Master::where('user_id', $providerId) + ->with(['metrics' => function ($query) { + $query->whereRaw('SUBSTRING(date_month, 1, 2) = ?', [now()->format('m')]); + }]) + ->get(); $clientPowerUsage = []; + // Collect unique slave_ids from the loaded metrics $clientSlaveIds = $masters->flatMap(function ($master) { - return $master->metrics->pluck('slave_id')->unique(); - })->toArray(); + return $master->metrics->pluck('slave_id'); + })->unique()->toArray(); - $clients = User::whereIn('slave_id', $clientSlaveIds)->where('user_type', 'Client')->get(['id', 'name', 'slave_id']); + // Get clients matching those slave_ids + $clients = User::whereIn('slave_id', $clientSlaveIds) + ->where('user_type', 'Client') + ->get(['id', 'name', 'slave_id']); foreach ($clients as $client) { - $totalPower = $masters->flatMap(function ($master) use ($client) { + // Sum power for each client's slave_id across all master's metrics (already filtered by month) + $totalPower = $masters->sum(function ($master) use ($client) { return $master->metrics->where('slave_id', $client->slave_id)->sum('power'); - })->sum(); + }); $clientPowerUsage[] = [ 'client_name' => $client->name, @@ -35,9 +41,7 @@ public static function getPowerUsageByClient(int $providerId): array } // Sort clients by total power usage in descending order - usort($clientPowerUsage, function ($a, $b) { - return $b['total_power'] <=> $a['total_power']; - }); + usort($clientPowerUsage, fn($a, $b) => $b['total_power'] <=> $a['total_power']); return $clientPowerUsage; } diff --git a/amp-laravel/app/Services/Provider/GetTotalPowerUsageService.php b/amp-laravel/app/Services/Provider/GetTotalPowerUsageService.php index f59a74c4..1f9f03da 100644 --- a/amp-laravel/app/Services/Provider/GetTotalPowerUsageService.php +++ b/amp-laravel/app/Services/Provider/GetTotalPowerUsageService.php @@ -10,9 +10,9 @@ class GetTotalPowerUsageService public static function getTotalPowerUsage(int $providerId): float { $masterIds = Master::where('user_id', $providerId)->pluck('id'); + return round(Metric::whereIn('master_id', $masterIds) - ->whereYear('date_month', now()->year) - ->whereMonth('date_month', now()->month) + ->whereRaw('SUBSTRING(date_month, 1, 2) = ?', [now()->format('m')]) ->sum('power'), 2); } } diff --git a/amp-laravel/app/Traits/ResponseTrait.php b/amp-laravel/app/Traits/ResponseTrait.php index 21a49d7f..c6421466 100644 --- a/amp-laravel/app/Traits/ResponseTrait.php +++ b/amp-laravel/app/Traits/ResponseTrait.php @@ -2,7 +2,9 @@ namespace App\Traits; +use App\Models\User; use Illuminate\Contracts\Validation\Validator; +use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth; use Illuminate\Http\Exceptions\HttpResponseException; trait ResponseTrait @@ -42,4 +44,28 @@ public function failedValidation(Validator $validator) 'message' => 'Invalid Credentials' ], 422)); } + + public function actingAsClient() + { + $client = User::factory()->create(['user_type' => 'Client']); + $token = JWTAuth::fromUser($client); + $request = $this->withHeader('Authorization', "Bearer $token"); + + return [$request, $client]; + } + + + public function actingAsProvider() + { + $provider = User::factory()->create(['user_type' => 'provider']); + $token = JWTAuth::fromUser($provider); + return $this->withHeader('Authorization', "Bearer $token"); + } + + public function actingAsAdmin() + { + $admin = User::factory()->create(['user_type' => 'admin']); + $token = JWTAuth::fromUser($admin); + return $this->withHeader('Authorization', "Bearer $token"); + } } diff --git a/amp-laravel/database/factories/MetricFactory.php b/amp-laravel/database/factories/MetricFactory.php index eac99c5a..9c792541 100644 --- a/amp-laravel/database/factories/MetricFactory.php +++ b/amp-laravel/database/factories/MetricFactory.php @@ -2,8 +2,8 @@ namespace Database\Factories; -use App\Models\Slave; -use App\Models\Master; +use DateTime; +use DateInterval; use Illuminate\Database\Eloquent\Factories\Factory; /** @@ -25,7 +25,19 @@ public function definition(): array 'current' => $this->faker->randomFloat(2, 0, 100), 'power' => $this->faker->randomFloat(2, 0, 500), 'energy' => $this->faker->randomFloat(2, 0, 10000), - 'date_month' => $this->faker->date('m-d'), + 'date_month' => function () { + $today = new DateTime(); + $startOfMonth = (new DateTime())->modify('first day of this month'); + $daysRange = (int)$today->format('d') - 1; // from day 1 to today + + if ($daysRange === 0) { + $randomDate = $startOfMonth; + } else { + $randomDate = (clone $startOfMonth)->add(new DateInterval('P' . rand(0, $daysRange) . 'D')); + } + + return $randomDate->format('m-d'); + } ]; } } diff --git a/amp-laravel/routes/api.php b/amp-laravel/routes/api.php index 44fec336..d85f87e5 100644 --- a/amp-laravel/routes/api.php +++ b/amp-laravel/routes/api.php @@ -31,8 +31,8 @@ Route::get("/getAllMetrics/{id}", [ProviderFunctionsController::class, "getMetrics"]); Route::get("/getAllLines/{id}", [ProviderFunctionsController::class, "getLines"]); - Route::get("/overview/{id}", [ProviderFunctionsController::class, "getOverviewData"]); // check for "totalPowerPerMonth" - Route::get("/totalPowerUsage/{id}", [ProviderFunctionsController::class, "getTotalPowerUsage"]); // check output + Route::get("/overview/{id}", [ProviderFunctionsController::class, "getOverviewData"]); + Route::get("/totalPowerUsage/{id}", [ProviderFunctionsController::class, "getTotalPowerUsage"]); Route::get("/averageVoltage/{id}", [ProviderFunctionsController::class, "getAverageVoltage"]); Route::get("/powerUsageByClient/{id}", [ProviderFunctionsController::class, "getPowerUsageByClient"]); Route::get("/voltageDistribution/{id}", [ProviderFunctionsController::class, "getVoltageDistribution"]); @@ -59,7 +59,10 @@ Route::post("/masterCheckIn", [ProviderCheckinController::class, "masterCheckin"]); Route::post("/lines", [LinesController::class, "masterLines"]); - + + // Public Route for Contact Message Submission + // Route::post("/insertMessage", [AuthController::class, "insertMessage"]); + //Unauthenticated Users Route::post("/login", [AuthController::class, "login"])->name("login"); }); diff --git a/amp-laravel/tests/Feature/AdminTest.php b/amp-laravel/tests/Feature/AdminTest.php new file mode 100644 index 00000000..f0120f98 --- /dev/null +++ b/amp-laravel/tests/Feature/AdminTest.php @@ -0,0 +1,119 @@ +actingAsAdmin()->getJson('/api/v1/admins/getAllProviders'); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'message' => 'Providers retrieved successfully', + ]) + ->assertJsonStructure([ + 'success', + 'message', + 'data' => [ + '*' => [ + 'id', + 'slave_id', + 'user_type', + 'name', + 'email', + 'phone_number', + 'created_at', + 'updated_at' + ] + ] + ]); + } + + public function testAdminCanGetAllContactMessages(): void + { + $response = $this->actingAsAdmin()->getJson('/api/v1/admins/getAllContactMessages'); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'message' => 'Messages retrieved successfully', + ]) + ->assertJsonStructure([ + 'success', + 'message', + 'data' => [ + '*' => [ + 'id', + 'name', + 'email', + 'message', + 'phone_number', + 'created_at', + 'updated_at' + ] + ] + ]); + } + + public function testAdminCanEditProvider(): void + { + $provider = User::factory()->create(['user_type' => 'provider']); + + $payload = [ + 'phone_number' => '71-852369' + ]; + + $response = $this->actingAsAdmin()->postJson("/api/v1/admins/editProvider/{$provider->id}", $payload); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'message' => 'Profile updated successfully', + 'data' => null + ]); + } + + public function testAdminCanEditProfile(): void + { + $payload = [ + 'name' => 'Nabiha' + ]; + + $response = $this->actingAsAdmin()->postJson('/api/v1/admins/editProfile', $payload); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'message' => 'Profile updated successfully', + 'data' => null + ]); + } + + + public function testAdminCanDeleteContactMessage(): void + { + $user = User::factory()->create(['user_type' => 'client']); + + $contactMessage = ContactForm::factory()->create([ + 'user_id' => $user->id, + ]); + + $response = $this->actingAsAdmin()->deleteJson("/api/v1/admins/deleteContactMessage/{$contactMessage->id}"); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'message' => 'Message deleted successfully', + 'data' => null + ]); + } +} diff --git a/amp-laravel/tests/Feature/ClientTest.php b/amp-laravel/tests/Feature/ClientTest.php new file mode 100644 index 00000000..1eba475c --- /dev/null +++ b/amp-laravel/tests/Feature/ClientTest.php @@ -0,0 +1,52 @@ +actingAsClient(); + + $response = $clientRequest->postJson('/api/v1/clients/editProfile', [ + 'name' => 'Gheeda', + ]); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'message' => 'Profile updated successfully', + 'data' => null, + ]); + } + + public function testClientCanGetDashboardData(): void + { + [$clientRequest, $client] = $this->actingAsClient(); + + $response = $clientRequest->getJson("/api/v1/clients/clientDashboardData/{$client->id}"); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'message' => 'Dashboard data fetched successfully', + ]) + ->assertJsonStructure([ + 'success', + 'message', + 'data' => [ + 'powerUsagePerDay', + 'cumulativePowerUsage', + 'totalPowerUsageThisMonth', + 'averageVoltageReach', + 'expectedPowerLimit', + ], + ]); + } +} diff --git a/amp-laravel/tests/Feature/LineTest.php b/amp-laravel/tests/Feature/LineTest.php index 75c4da8c..f3ef6844 100644 --- a/amp-laravel/tests/Feature/LineTest.php +++ b/amp-laravel/tests/Feature/LineTest.php @@ -2,19 +2,61 @@ namespace Tests\Feature; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; +use App\Models\Master; +use App\Traits\ResponseTrait; +use Illuminate\Foundation\Testing\WithFaker; class LineTest extends TestCase { - /** - * A basic feature test example. - */ - public function test_example(): void + use WithFaker, ResponseTrait; + + public function testSubmitMasterLinesSuccessfully(): void + { + $master = Master::factory()->create([]); + + $payload = [ + 'master_id' => $master->id, + 'voltage_l1' => "220.5", + 'voltage_l2' => "219.8", + 'voltage_l3' => "221.1", + 'power_l1' => "50.2", + 'power_l2' => "49.7", + 'power_l3' => "51.3" + ]; + + $response = $this->postJson('http://localhost:8000/api/v1/lines', $payload); + + $response->assertStatus(200) + ->assertJson([ + "success" => true, + "message" => "Master lines data saved" + ]) + ->assertJsonStructure([ + "success", + "message", + "data" => [ + "voltage_l1", + "voltage_l2", + "voltage_l3", + "power_l1", + "power_l2", + "power_l3", + "master_id", + "updated_at", + "created_at", + "id" + ] + ]); + } + + public function testSubmitMasterLinesValidationError(): void { - $response = $this->get('/'); + $response = $this->postJson('http://localhost:8000/api/v1/lines', []); - $response->assertStatus(200); + $response->assertStatus(422) + ->assertJson([ + "success" => false + ]); } } diff --git a/amp-laravel/tests/Feature/MasterTest.php b/amp-laravel/tests/Feature/MasterTest.php index 1595f3fd..636aa66c 100644 --- a/amp-laravel/tests/Feature/MasterTest.php +++ b/amp-laravel/tests/Feature/MasterTest.php @@ -2,19 +2,48 @@ namespace Tests\Feature; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; +use Illuminate\Foundation\Testing\WithFaker; +use Illuminate\Foundation\Testing\RefreshDatabase; class MasterTest extends TestCase { - /** - * A basic feature test example. - */ - public function test_example(): void + use WithFaker; + + public function testMasterCheckInSuccessfully(): void + { + $payload = [ + 'user_id' => 1, + 'name' => 'MASTR9' + ]; + + $response = $this->postJson('http://localhost:8000/api/v1/masterCheckIn', $payload); + + $response->assertStatus(200) + ->assertJson([ + "success" => true, + "message" => "Master checked in successfully" + ]) + ->assertJsonStructure([ + "success", + "message", + "data" => [ + "name", + "updated_at", + "created_at", + "id", + "user_id" + ] + ]); + } + + public function testMasterCheckInValidationError(): void { - $response = $this->get('/'); + $response = $this->postJson('http://localhost:8000/api/v1/masterCheckIn', []); - $response->assertStatus(200); + $response->assertStatus(422) + ->assertJson([ + "success" => false + ]); } } diff --git a/amp-laravel/tests/Feature/MetricTest.php b/amp-laravel/tests/Feature/MetricTest.php index bc0c89db..97fb1b36 100644 --- a/amp-laravel/tests/Feature/MetricTest.php +++ b/amp-laravel/tests/Feature/MetricTest.php @@ -2,19 +2,70 @@ namespace Tests\Feature; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; +use App\Models\Slave; +use App\Models\Master; +use App\Traits\ResponseTrait; +use Illuminate\Foundation\Testing\WithFaker; class MetricTest extends TestCase { - /** - * A basic feature test example. - */ - public function test_example(): void + use WithFaker, ResponseTrait; + + public function testSubmitSlaveMetricsSuccessfully(): void + { + [$request, $client] = $this->actingAsClient(); + + $master = Master::factory()->create([ + 'user_id' => $client->id, + ]); + + $slave = Slave::factory()->create([ + 'master_id' => $master->id, + ]); + + $payload = [ + 'power' => "10", + 'energy' => "30", + 'voltage' => "220", + 'current' => "20", + 'master_id' => $master->id, + 'date_month' => "05-16", + 'slave_id' => $slave->id + ]; + + $response = $request->postJson('http://localhost:8000/api/v1/metrics', $payload); + + $response->assertStatus(200) + ->assertJson([ + "success" => true, + "message" => "Slave metric stored" + ]) + ->assertJsonStructure([ + "success", + "message", + "data" => [ + "voltage", + "current", + "power", + "energy", + "slave_id", + "master_id", + "date_month", + "updated_at", + "created_at", + "id" + ] + ]); + } + + public function testSubmitSlaveMetricsValidationError(): void { - $response = $this->get('/'); + $response = $this->postJson('http://localhost:8000/api/v1/metrics', []); - $response->assertStatus(200); + $response->assertStatus(422) + ->assertJson([ + "success" => false + ]); } } diff --git a/amp-laravel/tests/Feature/ProviderTest.php b/amp-laravel/tests/Feature/ProviderTest.php new file mode 100644 index 00000000..ed595423 --- /dev/null +++ b/amp-laravel/tests/Feature/ProviderTest.php @@ -0,0 +1,268 @@ +actingAsProvider(); + + $response = $providerRequest->postJson('/api/v1/providers/editProfile', [ + 'name' => 'Riyad Riyad', + ]); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'message' => 'Profile updated successfully', + 'data' => null, + ]); + } + + public function testProviderCanEditAUser(): void + { + $providerRequest = $this->actingAsProvider(); + + $user = User::factory()->create(); + + $response = $providerRequest->postJson("/api/v1/providers/editUser/{$user->id}", [ + 'name' => 'Riyad Riyad', + ]); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'message' => 'Profile updated successfully', + 'data' => null, + ]); + } + + public function testProviderCanGetAllUsers(): void + { + $providerRequest = $this->actingAsProvider(); + + $provider = User::factory()->create(); + + $response = $providerRequest->getJson("/api/v1/providers/getAllUsers/{$provider->id}"); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'message' => 'Users retrieved successfully', + ]) + ->assertJsonStructure([ + 'success', + 'message', + 'data' => [ + '*' => [ + 'id', + 'slave_id', + 'user_type', + 'name', + 'email', + 'phone_number', + 'created_at', + 'updated_at', + ] + ] + ]); + } + + public function testProviderCanGetAllMetrics(): void + { + $providerRequest = $this->actingAsProvider(); + + $provider = User::factory()->create(); + + $response = $providerRequest->getJson("/api/v1/providers/getAllMetrics/{$provider->id}"); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'message' => 'Metrics retrieved successfully', + ]) + ->assertJsonStructure([ + 'success', + 'message', + 'data' => [ + '*' => [ + 'id', + 'slave_id', + 'power_usage', + 'voltage', + 'created_at', + 'updated_at', + ] + ] + ]); + } + + public function testProviderCanGetAllLines(): void + { + $providerRequest = $this->actingAsProvider(); + + $provider = User::factory()->create(); + + $response = $providerRequest->getJson("/api/v1/providers/getAllLines/{$provider->id}"); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'message' => 'Lines retrieved successfully', + ]) + ->assertJsonStructure([ + 'success', + 'message', + 'data' => [ + '*' => [ + 'id', + 'slave_id', + 'status', + 'created_at', + 'updated_at', + ] + ] + ]); + } + + public function testGetOverviewData() + { + $providerRequest = $this->actingAsProvider(); + + $provider = User::factory()->create(); + + $response = $providerRequest->getJson("/api/v1/providers/overview/{$provider->id}"); + + $response->assertStatus(200) + ->assertJsonStructure([ + 'success', + 'message', + 'data' => [ + 'totalClients', + 'totalPowerThisMonth', + 'averageVoltageAcrossClients', + 'latestMetricTimestamp', + ] + ]) + ->assertJson([ + 'success' => true, + 'message' => 'Overview data retrieved successfully', + ]); + } + + public function testGetTotalPowerUsage() + { + $providerRequest = $this->actingAsProvider(); + + $provider = User::factory()->create(); + + $response = $providerRequest->getJson("/api/v1/providers/totalPowerUsage/{$provider->id}"); + + $response->assertStatus(200) + ->assertJsonStructure(['success', 'message', 'data']) + ->assertJson([ + 'success' => true, + 'message' => 'Total power usage retrieved successfully', + ]); + } + + public function testGetAverageVoltage() + { + $providerRequest = $this->actingAsProvider(); + + $provider = User::factory()->create(); + + $response = $providerRequest->getJson("/api/v1/providers/averageVoltage/{$provider->id}"); + + $response->assertStatus(200) + ->assertJsonStructure(['success', 'message', 'data']) + ->assertJson([ + 'success' => true, + 'message' => 'Average voltage retrieved successfully', + ]); + } + + public function testGetPowerUsageByClient() + { + $providerRequest = $this->actingAsProvider(); + + $provider = User::factory()->create(); + + $response = $providerRequest->getJson("/api/v1/providers/powerUsageByClient/{$provider->id}"); + + $response->assertStatus(200) + ->assertJsonStructure([ + 'success', + 'message', + 'data' => [ + '*' => [ + 'client_name', + 'total_power', + ] + ] + ]) + ->assertJson([ + 'success' => true, + 'message' => 'Power usage by client retrieved successfully', + ]); + } + + public function testGetVoltageDistribution() + { + $providerRequest = $this->actingAsProvider(); + + $provider = User::factory()->create(); + + $response = $providerRequest->getJson("/api/v1/providers/voltageDistribution/{$provider->id}"); + + $response->assertStatus(200) + ->assertJsonStructure([ + 'success', + 'message', + 'data' => [ + '*' => [ + 'id', + 'voltage', + ] + ] + ]) + ->assertJson([ + 'success' => true, + 'message' => 'Voltage distribution retrieved successfully', + ]); + } + + public function testGetMetricsSummary() + { + $providerRequest = $this->actingAsProvider(); + + $provider = User::factory()->create(); + + $response = $providerRequest->getJson("/api/v1/providers/metricsSummary/{$provider->id}"); + + $response->assertStatus(200) + ->assertJsonStructure([ + 'success', + 'message', + 'data' => [ + 'minPower', + 'maxPower', + 'avgPower', + 'minVoltage', + 'maxVoltage', + 'avgVoltage', + ] + ]) + ->assertJson([ + 'success' => true, + 'message' => 'Metrics summary retrieved successfully', + ]); + } +} diff --git a/amp-laravel/tests/Feature/SlaveTest.php b/amp-laravel/tests/Feature/SlaveTest.php index f7267d25..113aaf2a 100644 --- a/amp-laravel/tests/Feature/SlaveTest.php +++ b/amp-laravel/tests/Feature/SlaveTest.php @@ -2,19 +2,47 @@ namespace Tests\Feature; -use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; +use Illuminate\Foundation\Testing\WithFaker; class SlaveTest extends TestCase { - /** - * A basic feature test example. - */ - public function test_example(): void + use WithFaker; + + public function testSlaveCheckInSuccessfully(): void + { + $payload = [ + 'master_id' => 1, + 'modbus_id' => 4 + ]; + + $response = $this->postJson('http://localhost:8000/api/v1/slaveCheckIn', $payload); + + $response->assertStatus(200) + ->assertJson([ + "success" => true, + "message" => "Slave Checkin Successful" + ]) + ->assertJsonStructure([ + "success", + "message", + "data" => [ + "id", + "master_id", + "modbus_id", + "created_at", + "updated_at" + ] + ]); + } + + public function testSlaveCheckInValidationError(): void { - $response = $this->get('/'); + $response = $this->postJson('http://localhost:8000/api/v1/slaveCheckIn', []); - $response->assertStatus(200); + $response->assertStatus(422) + ->assertJson([ + "success" => false + ]); } } diff --git a/amp-laravel/tests/Feature/UserTest.php b/amp-laravel/tests/Feature/UserTest.php index c2c01378..f58c1fa2 100644 --- a/amp-laravel/tests/Feature/UserTest.php +++ b/amp-laravel/tests/Feature/UserTest.php @@ -5,7 +5,7 @@ use Tests\TestCase; use App\Models\User; use Illuminate\Foundation\Testing\WithFaker; -// use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth; +use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth; // use Illuminate\Foundation\Testing\RefreshDatabase; class UserTest extends TestCase @@ -55,4 +55,19 @@ public function testInvalidLogin(): void ]); } + public function testLogoutUserSuccessfully(): void + { + $user = User::factory()->create(); + $token = JWTAuth::fromUser($user); + + $response = $this->withHeader('Authorization', "Bearer $token") + ->postJson('http://localhost:8000/api/v1/logout'); + + $response->assertStatus(200) + ->assertJson([ + "success" => true, + "message" => "Logged Out Successfully", + "data" => null + ]); + } }