Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
0f63c6d
laravel_test_and_seeds_fix: Added a new function to the AuthControlle…
Riyad-Murad May 17, 2025
eda8e3c
laravel_test_and_seeds_fix: Remove some comments
Riyad-Murad May 17, 2025
c42c307
laravel_test_and_seeds_fix: Modified return Messages for controller f…
Riyad-Murad May 17, 2025
c63ceb4
laravel_test_and_seeds_fix: Added a new Request file for Contact
Riyad-Murad May 17, 2025
8bc5468
laravel_test_and_seeds_fix: Fixed fillable variable in ContactForm Model
Riyad-Murad May 17, 2025
e06784f
laravel_test_and_seeds_fix: Created ContactMessageService
Riyad-Murad May 17, 2025
dcfc200
laravel_test_and_seeds_fix: Fixed Service code
Riyad-Murad May 17, 2025
79a5f9a
laravel_test_and_seeds_fix: Fixed Service code
Riyad-Murad May 17, 2025
bd2befc
laravel_test_and_seeds_fix: Fixed Service code
Riyad-Murad May 17, 2025
8303dc8
laravel_test_and_seeds_fix: Added function "actingAsClient" to be use…
Riyad-Murad May 17, 2025
1d8bcf3
laravel_test_and_seeds_fix: Added function "actingAsProvider" to be u…
Riyad-Murad May 17, 2025
d9df0c8
laravel_test_and_seeds_fix: Added function "actingAsAdmin" to be used…
Riyad-Murad May 17, 2025
0390fdc
laravel_test_and_seeds_fix: Fixed Metric Factories to generate accura…
Riyad-Murad May 17, 2025
7f4f3f0
laravel_test_and_seeds_fix: Added a Logout test in the UserTest
Riyad-Murad May 17, 2025
8401ca1
laravel_test_and_seeds_fix: Added a test case in the Admin Test
Riyad-Murad May 17, 2025
f434e3c
laravel_test_and_seeds_fix: Added a test case in the Admin Test
Riyad-Murad May 17, 2025
ce63be5
laravel_test_and_seeds_fix: Added a test case in the Admin Test
Riyad-Murad May 17, 2025
296dddf
laravel_test_and_seeds_fix: Added a test case in the Admin Test
Riyad-Murad May 17, 2025
689bf06
laravel_test_and_seeds_fix: Added a test case in the Admin Test
Riyad-Murad May 17, 2025
a37b60d
laravel_test_and_seeds_fix: Added a test case in the Salve Test
Riyad-Murad May 17, 2025
07aa138
laravel_test_and_seeds_fix: Added a test case in the Slave Test
Riyad-Murad May 17, 2025
34f209d
laravel_test_and_seeds_fix: Added a test case in the Metric Test
Riyad-Murad May 17, 2025
33362f0
laravel_test_and_seeds_fix: Added a test case in the Metric Test
Riyad-Murad May 17, 2025
a375649
laravel_test_and_seeds_fix: Added a test case in the Line Test
Riyad-Murad May 17, 2025
645fcd3
laravel_test_and_seeds_fix: Added a test case in the Line Test
Riyad-Murad May 17, 2025
f0ae29b
laravel_test_and_seeds_fix: Added a test case in the Master Test
Riyad-Murad May 17, 2025
063b563
laravel_test_and_seeds_fix: Added a test case in the Master Test
Riyad-Murad May 17, 2025
f95215e
laravel_test_and_seeds_fix: Added a test case in the Client Test
Riyad-Murad May 17, 2025
b87a3fb
laravel_test_and_seeds_fix: Added a test case in the Client Test
Riyad-Murad May 17, 2025
b6ed406
laravel_test_and_seeds_fix: Added a test case in the Provider Test
Riyad-Murad May 17, 2025
6ffade7
laravel_test_and_seeds_fix: Added a test case in the Provider Test
Riyad-Murad May 17, 2025
798a78a
laravel_test_and_seeds_fix: Added a test case in the Provider Test
Riyad-Murad May 17, 2025
e582772
laravel_test_and_seeds_fix: Added a test case in the Provider Test
Riyad-Murad May 17, 2025
df5bd19
laravel_test_and_seeds_fix: Added a test case in the Provider Test
Riyad-Murad May 17, 2025
8f5f89a
laravel_test_and_seeds_fix: Added a test case in the Provider Test
Riyad-Murad May 17, 2025
52ae62c
laravel_test_and_seeds_fix: Added a test case in the Provider Test
Riyad-Murad May 17, 2025
5ef55b9
laravel_test_and_seeds_fix: Added a test case in the Provider Test
Riyad-Murad May 17, 2025
f24ba81
laravel_test_and_seeds_fix: Added a test case in the Provider Test
Riyad-Murad May 17, 2025
6bd254c
laravel_test_and_seeds_fix: Added a test case in the Provider Test
Riyad-Murad May 17, 2025
a4a092f
laravel_test_and_seeds_fix: Added a test case in the Provider Test
Riyad-Murad May 17, 2025
9606151
laravel_test_and_seeds_fix: Fixed "testSubmitMasterLinesSuccessfully"…
Riyad-Murad May 17, 2025
5275b8d
laravel_test_and_seeds_fix: Fixed "testSubmitSlaveMetricsSuccessfully…
Riyad-Murad May 17, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions amp-laravel/app/Http/Controllers/Common/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand All @@ -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);
}
}

Expand All @@ -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);
}
}

Expand Down
31 changes: 31 additions & 0 deletions amp-laravel/app/Http/Requests/ContactMessageRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ContactMessageRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}

/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|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',
];
}
}
2 changes: 1 addition & 1 deletion amp-laravel/app/Models/ContactForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class ContactForm extends Model
protected $fillable = [
'name',
'email',
'phone',
'phone_number',
'message',
];

Expand Down
18 changes: 18 additions & 0 deletions amp-laravel/app/Services/ContactMessageService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace App\Services;

use App\Models\ContactForm;

class ContactMessageService
{
public static function insertMessage(array $data): ContactForm
{
return ContactForm::create([
'name' => $data['name'],
'email' => $data['email'],
'phone_number' => $data['phone_number'],
'message' => $data['message'] ?? null,
]);
}
}
4 changes: 2 additions & 2 deletions amp-laravel/app/Services/Provider/GetOverviewDataService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 [
Expand Down
28 changes: 16 additions & 12 deletions amp-laravel/app/Services/Provider/GetPowerUsageByClientService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
26 changes: 26 additions & 0 deletions amp-laravel/app/Traits/ResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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");
}
}
18 changes: 15 additions & 3 deletions amp-laravel/database/factories/MetricFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand All @@ -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');
}
];
}
}
9 changes: 6 additions & 3 deletions amp-laravel/routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -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"]);
Expand All @@ -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");
});
Loading