Skip to content

Commit 79dd5ab

Browse files
authored
Merge pull request #138 from Riyad-Murad/staging
Staging
2 parents d4334a0 + 8a6bf9d commit 79dd5ab

19 files changed

+782
-62
lines changed

amp-laravel/app/Http/Controllers/Common/AuthController.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@
33
namespace App\Http\Controllers\Common;
44

55
use Throwable;
6+
use App\Services\ContactMessageService;
67
use App\Services\UserLoginService;
78
use App\Http\Controllers\Controller;
89
use App\Http\Requests\AuthRequestLogin;
10+
use App\Http\Requests\ContactMessageRequest;
911
use Illuminate\Auth\AuthenticationException;
1012

1113
class AuthController extends Controller
@@ -30,6 +32,26 @@ public function login(AuthRequestLogin $request)
3032
}
3133
}
3234

35+
public function insertMessage(ContactMessageRequest $request)
36+
{
37+
try {
38+
$validatedData = $request->validated();
39+
$response = ContactMessageService::insertMessage($validatedData);
40+
41+
$messageData = [
42+
'id' => $response->id,
43+
'name' => $response->name,
44+
'email' => $response->email,
45+
'phone_number' => $response->phone_number,
46+
'message' => $response->message ?? null,
47+
];
48+
49+
return $this->loginMessageResponse(true, "Message Submitted Successfully", $messageData, 200);
50+
} catch (Throwable $e) {
51+
return $this->errorMessageResponse(false, "Something went wrong during Contact Message insertion", $e->getMessage(), 500);
52+
}
53+
}
54+
3355
public function logout()
3456
{
3557
$response = UserLoginService::logout();

amp-laravel/app/Http/Controllers/Provider/ProviderFunctionsController.php

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,9 @@ public function getUsers($id)
5757
try {
5858
$users = GetAllClientUsersService::getAll($id);
5959

60-
return $this->messageResponse(true, "Messages retrieved successfully", 200, $users);
60+
return $this->messageResponse(true, "Users retrieved successfully", 200, $users);
6161
} catch (\Exception $e) {
62-
return $this->errorMessageResponse(false, $e->getMessage(), "Failed to retrieve messages", 500);
62+
return $this->errorMessageResponse(false, $e->getMessage(), "Failed to retrieve users", 500);
6363
}
6464
}
6565

@@ -68,9 +68,9 @@ public function getMetrics($id)
6868
try {
6969
$metrics = GetAllClientMetricsService::getAll($id);
7070

71-
return $this->messageResponse(true, "Messages retrieved successfully", 200, $metrics);
71+
return $this->messageResponse(true, "Metrics retrieved successfully", 200, $metrics);
7272
} catch (\Exception $e) {
73-
return $this->errorMessageResponse(false, $e->getMessage(), "Failed to retrieve messages", 500);
73+
return $this->errorMessageResponse(false, $e->getMessage(), "Failed to retrieve metrics", 500);
7474
}
7575
}
7676

@@ -79,9 +79,9 @@ public function getLines($id)
7979
try {
8080
$lines = GetAllLinesService::getAll($id);
8181

82-
return $this->messageResponse(true, "Messages retrieved successfully", 200, $lines);
82+
return $this->messageResponse(true, "Lines retrieved successfully", 200, $lines);
8383
} catch (\Exception $e) {
84-
return $this->errorMessageResponse(false, $e->getMessage(), "Failed to retrieve messages", 500);
84+
return $this->errorMessageResponse(false, $e->getMessage(), "Failed to retrieve lines", 500);
8585
}
8686
}
8787

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?php
2+
3+
namespace App\Http\Requests;
4+
5+
use Illuminate\Foundation\Http\FormRequest;
6+
7+
class ContactMessageRequest extends FormRequest
8+
{
9+
/**
10+
* Determine if the user is authorized to make this request.
11+
*/
12+
public function authorize(): bool
13+
{
14+
return true;
15+
}
16+
17+
/**
18+
* Get the validation rules that apply to the request.
19+
*
20+
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
21+
*/
22+
public function rules(): array
23+
{
24+
return [
25+
'name' => 'required|string|max:255',
26+
'email' => 'required|email|max:255',
27+
'phone_number' => 'required|string|max:20',
28+
'message' => 'sometimes|required|string|max:1000',
29+
];
30+
}
31+
}

amp-laravel/app/Models/ContactForm.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class ContactForm extends Model
1212
protected $fillable = [
1313
'name',
1414
'email',
15-
'phone',
15+
'phone_number',
1616
'message',
1717
];
1818

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
namespace App\Services;
4+
5+
use App\Models\ContactForm;
6+
7+
class ContactMessageService
8+
{
9+
public static function insertMessage(array $data): ContactForm
10+
{
11+
return ContactForm::create([
12+
'name' => $data['name'],
13+
'email' => $data['email'],
14+
'phone_number' => $data['phone_number'],
15+
'message' => $data['message'] ?? null,
16+
]);
17+
}
18+
}

amp-laravel/app/Services/Provider/GetOverviewDataService.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@ public static function getOverviewData(int $providerId): array
1414
$clientSlaveIds = Metric::whereIn('master_id', $masterIds)->distinct()->pluck('slave_id');
1515
$totalClients = User::whereIn('slave_id', $clientSlaveIds)->where('user_type', 'Client')->count();
1616
$totalPowerThisMonth = Metric::whereIn('master_id', $masterIds)
17-
->whereYear('date_month', now()->year)
18-
->whereMonth('date_month', now()->month)
17+
->whereRaw('SUBSTRING(date_month, 1, 2) = ?', [now()->format('m')])
1918
->sum('power');
19+
2020
$averageVoltage = Metric::whereIn('master_id', $masterIds)->avg('voltage');
2121

2222
return [

amp-laravel/app/Services/Provider/GetPowerUsageByClientService.php

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,29 @@ class GetPowerUsageByClientService
1010
{
1111
public static function getPowerUsageByClient(int $providerId): array
1212
{
13-
$masters = Master::where('user_id', $providerId)->with(['metrics' => function ($query) {
14-
$query->whereYear('date_month', now()->year)
15-
->whereMonth('date_month', now()->month);
16-
}])->get();
13+
$masters = Master::where('user_id', $providerId)
14+
->with(['metrics' => function ($query) {
15+
$query->whereRaw('SUBSTRING(date_month, 1, 2) = ?', [now()->format('m')]);
16+
}])
17+
->get();
1718

1819
$clientPowerUsage = [];
1920

21+
// Collect unique slave_ids from the loaded metrics
2022
$clientSlaveIds = $masters->flatMap(function ($master) {
21-
return $master->metrics->pluck('slave_id')->unique();
22-
})->toArray();
23+
return $master->metrics->pluck('slave_id');
24+
})->unique()->toArray();
2325

24-
$clients = User::whereIn('slave_id', $clientSlaveIds)->where('user_type', 'Client')->get(['id', 'name', 'slave_id']);
26+
// Get clients matching those slave_ids
27+
$clients = User::whereIn('slave_id', $clientSlaveIds)
28+
->where('user_type', 'Client')
29+
->get(['id', 'name', 'slave_id']);
2530

2631
foreach ($clients as $client) {
27-
$totalPower = $masters->flatMap(function ($master) use ($client) {
32+
// Sum power for each client's slave_id across all master's metrics (already filtered by month)
33+
$totalPower = $masters->sum(function ($master) use ($client) {
2834
return $master->metrics->where('slave_id', $client->slave_id)->sum('power');
29-
})->sum();
35+
});
3036

3137
$clientPowerUsage[] = [
3238
'client_name' => $client->name,
@@ -35,9 +41,7 @@ public static function getPowerUsageByClient(int $providerId): array
3541
}
3642

3743
// Sort clients by total power usage in descending order
38-
usort($clientPowerUsage, function ($a, $b) {
39-
return $b['total_power'] <=> $a['total_power'];
40-
});
44+
usort($clientPowerUsage, fn($a, $b) => $b['total_power'] <=> $a['total_power']);
4145

4246
return $clientPowerUsage;
4347
}

amp-laravel/app/Services/Provider/GetTotalPowerUsageService.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ class GetTotalPowerUsageService
1010
public static function getTotalPowerUsage(int $providerId): float
1111
{
1212
$masterIds = Master::where('user_id', $providerId)->pluck('id');
13+
1314
return round(Metric::whereIn('master_id', $masterIds)
14-
->whereYear('date_month', now()->year)
15-
->whereMonth('date_month', now()->month)
15+
->whereRaw('SUBSTRING(date_month, 1, 2) = ?', [now()->format('m')])
1616
->sum('power'), 2);
1717
}
1818
}

amp-laravel/app/Traits/ResponseTrait.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
namespace App\Traits;
44

5+
use App\Models\User;
56
use Illuminate\Contracts\Validation\Validator;
7+
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;
68
use Illuminate\Http\Exceptions\HttpResponseException;
79

810
trait ResponseTrait
@@ -42,4 +44,28 @@ public function failedValidation(Validator $validator)
4244
'message' => 'Invalid Credentials'
4345
], 422));
4446
}
47+
48+
public function actingAsClient()
49+
{
50+
$client = User::factory()->create(['user_type' => 'Client']);
51+
$token = JWTAuth::fromUser($client);
52+
$request = $this->withHeader('Authorization', "Bearer $token");
53+
54+
return [$request, $client];
55+
}
56+
57+
58+
public function actingAsProvider()
59+
{
60+
$provider = User::factory()->create(['user_type' => 'provider']);
61+
$token = JWTAuth::fromUser($provider);
62+
return $this->withHeader('Authorization', "Bearer $token");
63+
}
64+
65+
public function actingAsAdmin()
66+
{
67+
$admin = User::factory()->create(['user_type' => 'admin']);
68+
$token = JWTAuth::fromUser($admin);
69+
return $this->withHeader('Authorization', "Bearer $token");
70+
}
4571
}

amp-laravel/database/factories/MetricFactory.php

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
namespace Database\Factories;
44

5-
use App\Models\Slave;
6-
use App\Models\Master;
5+
use DateTime;
6+
use DateInterval;
77
use Illuminate\Database\Eloquent\Factories\Factory;
88

99
/**
@@ -25,7 +25,19 @@ public function definition(): array
2525
'current' => $this->faker->randomFloat(2, 0, 100),
2626
'power' => $this->faker->randomFloat(2, 0, 500),
2727
'energy' => $this->faker->randomFloat(2, 0, 10000),
28-
'date_month' => $this->faker->date('m-d'),
28+
'date_month' => function () {
29+
$today = new DateTime();
30+
$startOfMonth = (new DateTime())->modify('first day of this month');
31+
$daysRange = (int)$today->format('d') - 1; // from day 1 to today
32+
33+
if ($daysRange === 0) {
34+
$randomDate = $startOfMonth;
35+
} else {
36+
$randomDate = (clone $startOfMonth)->add(new DateInterval('P' . rand(0, $daysRange) . 'D'));
37+
}
38+
39+
return $randomDate->format('m-d');
40+
}
2941
];
3042
}
3143
}

0 commit comments

Comments
 (0)