initial commit

This commit is contained in:
2026-06-23 13:28:38 +07:00
commit 966ed115b2
590 changed files with 111412 additions and 0 deletions
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use PhpMqtt\Client\Facades\MQTT;
class PublishToTopic extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mqtt:publish';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Publish To MQTT topic';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
echo "Publishing to topic...\n";
$message = "Ini dari Backend!";
MQTT::publish('fromAPI', $message);
echo "$message\n";
return Command::SUCCESS;
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use PhpMqtt\Client\Contracts\MqttClient;
use PhpMqtt\Client\Facades\MQTT;
class SubscribeToTopic extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mqtt:subscribe';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Subscribe To MQTT topic';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
/** @var MqttClient $mqtt */
// $mqtt = MQTT::connection();
// $mqtt->publish('myInTopic', 'foo', 1);
// // $mqtt->subscribe('myInTopic', function (string $topic, string $message) {
// // echo sprintf('Received QoS level 1 message on topic [%s]: %s', $topic, $message);
// // }, 1);
// $mqtt->loop(true);
$mqtt = MQTT::connection();
$mqtt->subscribe('fromMobile', function(string $topic, string $message) {
echo sprintf('Received message on topic [%s]: %s\n',$topic, $message);
});
$mqtt->loop(true);
return Command::SUCCESS;
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*
* @param Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Spatie\Permission\Exceptions\UnauthorizedException;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<Throwable>, \Psr\Log\LogLevel::*>
*/
protected $levels = [
//
];
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<Throwable>>
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
$this->renderable(function (UnauthorizedException $e, $request) {
return baseResponse(
'failed',
'You do not have the required authorization!',
null,
$e->getMessage(),
401
);
});
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
use Illuminate\Http\JsonResponse;
function baseResponse($status , $message, $data, $error, $http_code): JsonResponse
{
return response()->json([
'message' => $message,
'status' => $status,
'data' => $data,
'error' => $error
], $http_code);
}
?>
+158
View File
@@ -0,0 +1,158 @@
<?php
namespace App\Http\Controllers;
use App\Interfaces\DoctorRepositoryInterface;
use App\Interfaces\PatientRepositoryInterface;
use App\Interfaces\UserRepositoryInterface;
use DB;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Throwable;
class AdminController extends Controller
{
private PatientRepositoryInterface $patientRepository;
private DoctorRepositoryInterface $doctorRepository;
public function __construct(
PatientRepositoryInterface $patientRepository,
DoctorRepositoryInterface $doctorRepository
)
{
$this->patientRepository = $patientRepository;
$this->doctorRepository = $doctorRepository;
}
/**
* Assign doctor with patients.
*
* @param Request $request
* @return JsonResponse
* @throws Throwable
*/
public function assign(Request $request): JsonResponse
{
try {
DB::beginTransaction();
$input = $request->all();
$doctor = $this->doctorRepository->getDoctorById($input['doctor_id']);
$patients = $this->patientRepository->getManyPatientById($input['patient_ids']);
$validate = array_values($doctor->patients->pluck('id')->toArray());
foreach ($patients as $patient){
if (in_array($patient->id, $validate)){
continue;
}else{
$patient->doctors()->attach($doctor);
}
}
DB::commit();
return baseResponse(
'success',
'success assign doctor with patients!',
null,
null,
200
);
}catch (Throwable $exception){
DB::rollBack();
return baseResponse(
'failed',
'failed assign doctor with patients!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Unassigned doctor with patients.
*
* @param Request $request
* @return JsonResponse
* @throws Throwable
*/
public function unassign(Request $request): JsonResponse
{
try {
DB::beginTransaction();
$input = $request->all();
$doctor = $this->doctorRepository->getDoctorById($input['doctor_id']);
$patients = $this->patientRepository->getManyPatientById($input['patient_ids']);
foreach ($patients as $patient){
$patient->doctors()->detach($doctor);
}
DB::commit();
return baseResponse(
'success',
'success unassigned doctor with patients!',
null,
null,
200
);
}catch (Throwable $exception){
DB::rollBack();
return baseResponse(
'failed',
'failed unassigned doctor with patients!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Unassigned doctor with patients.
*
* @param Request $request
* @return JsonResponse
* @throws Throwable
*/
public function unassignByDoctor(Request $request): JsonResponse
{
try {
DB::beginTransaction();
$input = $request->all();
$doctors = $this->doctorRepository->getDoctorById($input['doctor_ids']);
$patient = $this->patientRepository->getManyPatientById($input['patient_id']);
foreach ($doctors as $doctor){
$doctor->patients()->detach($patient);
}
DB::commit();
return baseResponse(
'success',
'success unassigned doctor with patients!',
null,
null,
200
);
}catch (Throwable $exception){
DB::rollBack();
return baseResponse(
'failed',
'failed unassigned doctor with patients!',
null,
$exception->getMessage(),
500
);
}
}
}
+83
View File
@@ -0,0 +1,83 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\LoginRequest;
use App\Interfaces\DiagnoseRepositoryInterface;
use App\Interfaces\PatientRepositoryInterface;
use Carbon\Carbon;
use Auth;
use Http;
use Storage;
class AuthController extends Controller
{
function login(LoginRequest $request) {
$credentials = $request->all();
$auth = Auth::guard('web');
if (!$auth->attempt($credentials)) {
return response()->json(['error'=>'Email or password incorrect'], 401);
}
$token = $auth->user()->createToken('authToken');
return baseResponse(
'success',
'success login!',
[
'user' => $auth->user(),
'access_token' => $token->accessToken,
'expired' => $token->token->expires_at->diffInSeconds(Carbon::now()),
],
null,
200
);
}
function profile() {
$user = Auth::user();
$role = Auth::user()->getRoleNames()[0];
return baseResponse(
'success',
'success get profile!',
[
'user' => collect($user->setAttribute('role',$role)),
'profile' => $role !== 'admin' ? collect($user->$role->setAttribute('relations', $user->$role->pivot))->except(['pivot']) : null,
],
null,
200
);
}
function logout() {
$user = Auth::user();
if (!$user){
return baseResponse(
'failed',
'You do not have the required authorization!',
null,
null,
401
);
}
$user->token()->revoke();
return baseResponse(
'success',
'success logout!',
$user,
null,
200
);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
@@ -0,0 +1,262 @@
<?php
namespace App\Http\Controllers;
use App\Interfaces\DiagnoseRepositoryInterface;
use App\Interfaces\DoctorRepositoryInterface;
use App\Interfaces\PatientRepositoryInterface;
use Auth;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Traits\EnumeratesValues;
class DashboardController extends Controller
{
private DoctorRepositoryInterface $doctorRepository;
private PatientRepositoryInterface $patientRepository;
private DiagnoseRepositoryInterface $diagnoseRepository;
public function __construct(
DoctorRepositoryInterface $doctorRepository,
PatientRepositoryInterface $patientRepository,
DiagnoseRepositoryInterface $diagnoseRepository
)
{
$this->doctorRepository = $doctorRepository;
$this->patientRepository = $patientRepository;
$this->diagnoseRepository = $diagnoseRepository;
}
public function admin_dashboard_statistic(): JsonResponse
{
// jadi nanti ada beberapa card yang isinya:
// 1. total dokter
// 2. total pasien
// 3. total normal
// 4. total mi
// 5. total gender
// 6. total patient today
$total_doctor = count($this->doctorRepository->getAllDoctors());
$total_patient = count($this->patientRepository->getAllPatients());
$total_patient_normal = collect($this->patientRepository->getAllPatients())->where('condition','normal')->count();
$total_patient_mi = collect($this->patientRepository->getAllPatients())->where('condition','mi')->count();
$total_patient_male = collect($this->patientRepository->getAllPatients())->where('gender','male')->count();
$total_patient_female = collect($this->patientRepository->getAllPatients())->where('gender','female')->count();
$total_patient_today = collect($this->patientRepository->getAllPatients())
->filter(function ($patient) {
return Carbon::parse($patient->updated_at)->isToday();
})
->count();
return baseResponse(
'success',
'success admin_get_total_statistic!',
[
'total_doctor' => $total_doctor,
'total_patient' => $total_patient,
'total_patient_normal' => $total_patient_normal,
'total_patient_mi' => $total_patient_mi,
'total_patient_male' => $total_patient_male,
'total_patient_female' => $total_patient_female,
'total_patient_today' => $total_patient_today
],
null,
200
);
}
private function get_patient_by_date($start, $end): EnumeratesValues|Collection
{
return collect($this->patientRepository->getAllPatients())
->whereBetween('updated_at', [$start, $end]);
}
public function admin_dashboard_graph(Request $request): JsonResponse
{
// 2. patient weekly (done)
// 3. patient monthly
// 4. custom date
// 5. tinggal bikin kondisi lagi
$filter = $request->query('filter');
$startOfWeek = Carbon::now()->startOfWeek();
$endOfWeek = Carbon::now()->endOfWeek();
$startOfMonth = Carbon::now()->startOfMonth();
$endOfMonth = Carbon::now()->endOfMonth();
$organizedData = [];
$patients = $this->patientRepository->getAllPatients();
if ($filter === 'weekly'){
for ($date = $startOfWeek; $date->lte($endOfWeek); $date->addDay()) {
// Your code here
$_date = Carbon::parse($date);
$organizedData[$_date->format('Y-m-d')] = collect($patients)->where('updated_at', '>=', $_date->startOfDay())->where('updated_at', '<=', $_date->endOfDay())->count();
}
}elseif ($filter === 'monthly'){
for ($date = $startOfMonth; $date->lte($endOfMonth); $date->addWeek()) {
// Your code here
$_date = Carbon::parse($date);
$organizedData['week ' . $_date->weekOfMonth] = collect($patients)->where('updated_at', '>=', $_date->startOfWeek())->where('updated_at', '<=', $_date->endOfWeek())->count();
}
}
elseif ($filter === 'custom'){
if (!$request->query('end_date') || !$request->query('start_date')){
return baseResponse(
'error',
'error admin_dashboard_graph!',
null,
null,
500
);
}
$customStart = Carbon::createFromFormat('Y-m-d', $request->query('start_date'));
$customEnd = Carbon::createFromFormat('Y-m-d', $request->query('end_date'));
for ($date = $customStart; $date->lte($customEnd); $date->addDay()) {
// Your code here
$_date = Carbon::parse($date);
$organizedData[$_date->format('Y-m-d')] = collect($patients)->where('updated_at', '>=', $_date->startOfDay())->where('updated_at', '<=', $_date->endOfDay())->count();
}
}
else{
for ($date = $startOfWeek; $date->lte($endOfWeek); $date->addDay()) {
// Your code here
$_date = Carbon::parse($date);
$organizedData[$_date->format('Y-m-d')] = collect($patients)->where('updated_at', '>=', $_date->startOfDay())->where('updated_at', '<=', $_date->endOfDay())->count();
}
}
return baseResponse(
'success',
'success admin_get_total_statistic!',
[
'patient' => $organizedData
],
null,
200
);
}
public function doctor_dashboard_statistic(): JsonResponse
{
// jadi nanti ada beberapa card yang isinya:
// 1. total pasien
// 2. total verified
// 3. total unverified
// 4. total mi
// 5. total normal
// 6. total gender
$user = Auth::user();
$patients = $user->doctor->patients;
$diagnoses = $this->diagnoseRepository->getCustomAllDiagnoses('doctor_id', $user->doctor->id);
$total_patient = collect($patients)->count();
$total_verified = collect($diagnoses)->where('is_verified',1)->count();
$total_unverified = collect($diagnoses)->where('is_verified',0)->count();
$total_patient_normal = collect($patients)->where('condition','normal')->count();
$total_patient_mi = collect($patients)->where('condition','mi')->count();
$total_patient_male = collect($patients)->where('gender','male')->count();
$total_patient_female = collect($patients)->where('gender','female')->count();
return baseResponse(
'success',
'success doctor_get_total_statistic!',
[
'total_patient' => $total_patient,
'total_verified' => $total_verified,
'total_unverified' => $total_unverified,
'total_patient_normal' => $total_patient_normal,
'total_patient_mi' => $total_patient_mi,
'total_patient_male' => $total_patient_male,
'total_patient_female' => $total_patient_female,
],
null,
200
);
}
public function doctor_dashboard_latest_diagnose(): JsonResponse
{
// get latest diagnose
$user = Auth::user();
$diagnoses = collect($this->diagnoseRepository->getCustomAllDiagnoses('doctor_id', $user->doctor->id))->sortByDesc('updated_at')->slice(0,5)->values()->toArray();
return baseResponse(
'success',
'success doctor_dashboard_latest_diagnose!',
[
'diagnoses' => $diagnoses
],
null,
200
);
}
public function patient_dashboard_statistic(): JsonResponse
{
// jadi nanti ada beberapa card yang isinya:
// 1. total verified
// 2. total unverified
// 3. total mi
// 4. total normal
$user = Auth::user();
$diagnoses = $user->patient->diagnoses;
$total_verified = collect($diagnoses)->where('is_verified',1)->count();
$total_unverified = collect($diagnoses)->where('is_verified',0)->count();
$total_patient_normal = collect($diagnoses)->where('diagnoses','normal')->count();
$total_patient_mi = collect($diagnoses)->where('diagnoses','mi')->count();
return baseResponse(
'success',
'success patient_get_total_statistic!',
[
'total_verified' => $total_verified,
'total_unverified' => $total_unverified,
'total_patient_normal' => $total_patient_normal,
'total_patient_mi' => $total_patient_mi,
],
null,
200
);
}
public function patient_dashboard_latest_diagnose(): JsonResponse
{
// get latest diagnose
$user = Auth::user();
$diagnoses = collect($user->patient->diagnoses)->sortByDesc('updated_at')->slice(0,5)->values()->toArray();
return baseResponse(
'success',
'success patient_dashboard_latest_diagnose!',
[
'diagnoses' => $diagnoses
],
null,
200
);
}
}
+419
View File
@@ -0,0 +1,419 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\DiagnoseRequest;
use App\Interfaces\DiagnoseRepositoryInterface;
use App\Interfaces\PatientRepositoryInterface;
use App\Interfaces\UserRepositoryInterface;
use Auth;
use DB;
use Http;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Storage;
use Throwable;
class DiagnoseController extends Controller
{
private DiagnoseRepositoryInterface $diagnoseRepository;
private PatientRepositoryInterface $patientRepository;
public function __construct(
DiagnoseRepositoryInterface $diagnoseRepository,
UserRepositoryInterface $userRepository,
PatientRepositoryInterface $patientRepository
)
{
$this->diagnoseRepository = $diagnoseRepository;
$this->patientRepository = $patientRepository;
$this->middleware('role:doctor', [
'only' => ['update'],
'except' => ['store']
]);
$this->middleware('role:patient', [
'only' => ['store'],
'except' => ['update']
]);
}
/**
* Display a listing of the resource.
*
* @return JsonResponse
*/
public function index(): JsonResponse
{
$user = Auth::user();
$data = $this->diagnoseRepository->getCustomAllDiagnoses($user->roles[0]['name'].'_id',$user->role_data['id']);
return baseResponse(
'success',
'success get all diagnose data',
$data,
null,
200
);
}
/**
* Store a newly created resource in storage.
*
* @param DiagnoseRequest $request
* @return JsonResponse
* @throws Throwable
*/
public function store(DiagnoseRequest $request): JsonResponse
{
try {
$input = $request->all();
$user = Auth::user();
$patient = $user->patient;
$doctor = $patient->doctors[0];
if (!$patient || !$doctor){
return baseResponse(
'failed',
'please make sure you already assign with doctor, or asking admin!',
null,
null,
500
);
}
$input['patient_id'] = $patient->id;
$input['doctor_id'] = $doctor->id;
$input['file'] = Storage::disk('s3')->put('apicta', $input['file']);
$diagnose = $this->diagnoseRepository->createDiagnose($input);
DB::commit();
return baseResponse(
'success',
'success create diagnose data!',
$diagnose,
null,
201
);
}catch (Throwable $exception){
DB::rollBack();
return baseResponse(
'failed',
'failed create diagnose data!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Display the specified resource.
*
* @param string $diagnose_id
* @return JsonResponse
*/
public function show(string $diagnose_id): JsonResponse
{
try {
$diagnose = $this->diagnoseRepository->getDiagnoseById($diagnose_id);
return baseResponse(
'success',
'success show diagnose data!',
$diagnose,
null,
200
);
}catch (Throwable $exception){
return baseResponse(
'failed',
'failed show diagnose data!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Update the specified resource in storage.
*
* @param DiagnoseRequest $request
* @param string $diagnose_id
* @return JsonResponse
* @throws Throwable
*/
public function update(DiagnoseRequest $request, string $diagnose_id): JsonResponse
{
try {
$data = $request->all();
DB::beginTransaction();
$diagnose_data = $this->diagnoseRepository->getDiagnoseById($diagnose_id);
$this->patientRepository->updatePatient($diagnose_data->patient_id, ['condition' => $data['diagnoses']]);
$this->diagnoseRepository->updateDiagnose($diagnose_id,$data);
DB::commit();
return baseResponse(
'success',
'success update diagnose data!',
null,
null,
200
);
}catch (Throwable $exception){
DB::rollBack();
return baseResponse(
'failed',
'failed update diagnose data!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Remove the specified resource from storage.
*
* @param string $diagnose_id
* @return JsonResponse
* @throws Throwable
*/
public function destroy(string $diagnose_id): JsonResponse
{
try {
DB::beginTransaction();
$this->diagnoseRepository->deleteDiagnose($diagnose_id);
DB::commit();
return baseResponse(
'success',
'success delete diagnose data!',
null,
null,
200
);
}catch (Throwable $exception){
DB::rollBack();
return baseResponse(
'failed',
'failed delete diagnose data!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Remove the specified resource from storage.
*
* @param Request $request
* @return JsonResponse
* @throws Throwable
*/
public function predict_patient(Request $request)
{
$file = $request->file('file');
$patient_id = $request->input('patient_id');
if (!$file){
return baseResponse(
'failed',
'please make sure you sending the file',
null,
null,
500
);
}
if (!$patient_id){
return baseResponse(
'failed',
'please make sure you sending the patient id',
null,
null,
500
);
}
try {
DB::beginTransaction();
$response = Http::attach('file',file_get_contents($file), $file->getClientOriginalName())
->post('https://myoscope.distancing.my.id/predict');
$patient = $this->patientRepository->getPatientById($patient_id);
$file_path = Storage::disk('s3')->put('apicta', $file);
$this->diagnoseRepository->createDiagnose([
'patient_id' =>$patient->id,
'doctor_id' =>$patient->doctors[0]->id,
'diagnoses' => $response['result'] ? 'mi' : 'normal',
'notes' => '-',
'is_verified' => false,
'file' => $file_path
]);
DB::commit();
return baseResponse(
'success',
'success predict',
$response->json(),
null,
200
);
}catch (Throwable $exception) {
DB::rollBack();
return baseResponse(
'failed',
'error when predict',
null,
$exception->getMessage(),
500
);
}
}
public function predict_doctor(Request $request)
{
$file = $request->file('file');
$patient_id = $request->input('patient_id');
if (!$file){
return baseResponse(
'failed',
'please make sure you sending the file',
null,
null,
500
);
}
if (!$patient_id){
return baseResponse(
'failed',
'please make sure you sending the patient id',
null,
null,
500
);
}
try {
DB::beginTransaction();
$response = Http::attach('file',file_get_contents($file), $file->getClientOriginalName())
->post('https://myoscope.distancing.my.id/predict');
$patient = $this->patientRepository->getPatientById($patient_id);
$file_path = Storage::disk('s3')->put('apicta', $file);
$this->diagnoseRepository->createDiagnose([
'patient_id' =>$patient->id,
'doctor_id' =>Auth::user()->doctor->id,
'diagnoses' => $response['result'] ? 'mi' : 'normal',
'notes' => '-',
'is_verified' => false,
'file' => $file_path
]);
DB::commit();
return baseResponse(
'success',
'success predict',
$response->json(),
null,
200
);
}catch (Throwable $exception) {
DB::rollBack();
return baseResponse(
'failed',
'error when predict',
null,
$exception->getMessage(),
500
);
}
}
public function repredict(Request $request){
$file_path = $request->input('file_path');
if (!$file_path){
return baseResponse(
'failed',
'please make sure you sending the file',
null,
null,
500
);
}
$file = Storage::disk('s3')->get($file_path);
$temp_file = tempnam(sys_get_temp_dir(), 's3');
file_put_contents($temp_file, $file);
if (!$file){
return baseResponse(
'failed',
'please make sure you sending the file',
null,
null,
500
);
}
try {
// $file_path = 'apicta/963q79jNwGT8Pqhs910e1eC57hZbWugnXnbYb2wr.wav';
// $file = Storage::disk('s3')->get($file_path);
//
// $local_path = 'files-alfara/alfara.wav';
// $res = Storage::disk('public')->put($local_path, $file);
// dd(file_get_contents(storage_path('app/public/files-alfara/alfara.wav')));
$response = Http::attach('file', file_get_contents($temp_file), basename($file_path))
->post('https://myoscope.distancing.my.id/predict');
//
// $response = Http::attach('file', file_get_contents($temp_file), 'ddddddd.wav');
// dd($response);
return baseResponse(
'success',
'success predict',
$response->json(),
null,
200
);
}catch (Throwable $exception){
return baseResponse(
'failed',
'error when predict',
null,
$exception->getMessage(),
500
);
}
}
}
+227
View File
@@ -0,0 +1,227 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\DoctorRequest;
use App\Interfaces\DoctorRepositoryInterface;
use App\Interfaces\UserRepositoryInterface;
use Auth;
use DB;
use Throwable;
use Illuminate\Http\JsonResponse;
use Hash;
class DoctorController extends Controller
{
private DoctorRepositoryInterface $doctorRepository;
private UserRepositoryInterface $userRepository;
public function __construct(
DoctorRepositoryInterface $doctorRepository,
UserRepositoryInterface $userRepository
)
{
$this->doctorRepository = $doctorRepository;
$this->userRepository = $userRepository;
}
/**
* Display a listing of the resource.
*
* @return JsonResponse
*/
public function index(): JsonResponse
{
$data = $this->doctorRepository->getAllDoctors();
return baseResponse(
'success',
'success get all doctor data',
$data,
null,
200
);
}
/**
* Store a newly created resource in storage.
*
* @param DoctorRequest $request
* @return JsonResponse
* @throws Throwable
*/
public function store(DoctorRequest $request): JsonResponse
{
try {
$input = $request->all();
DB::beginTransaction();
$user = $this->userRepository->createUser([
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
$user->assignRole('doctor');
$input['user_id'] = $user->id;
$doctor = $this->doctorRepository->createDoctor($input);
DB::commit();
return baseResponse(
'success',
'success create doctor data!',
$doctor,
null,
201
);
}catch (Throwable $exception){
DB::rollBack();
return baseResponse(
'failed',
'failed create doctor data!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Display the specified resource.
*
* @param string $doctor_id
* @return JsonResponse
*/
public function show(string $doctor_id): JsonResponse
{
try {
$doctor = $this->doctorRepository->getDoctorById($doctor_id);
return baseResponse(
'success',
'success show doctor data!',
$doctor,
null,
200
);
}catch (Throwable $exception){
return baseResponse(
'failed',
'failed show doctor data!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Update the specified resource in storage.
*
* @param DoctorRequest $request
* @param string $doctor_id
* @return JsonResponse
* @throws Throwable
*/
public function update(DoctorRequest $request, string $doctor_id): JsonResponse
{
try {
$data = $request->all();
DB::beginTransaction();
$this->doctorRepository->updateDoctor($doctor_id,$data);
DB::commit();
return baseResponse(
'success',
'success update doctor data!',
null,
null,
200
);
}catch (Throwable $exception){
DB::rollBack();
return baseResponse(
'failed',
'failed update doctor data!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Remove the specified resource from storage.
*
* @param string $doctor_id
* @return JsonResponse
* @throws Throwable
*/
public function destroy(string $doctor_id): JsonResponse
{
try {
DB::beginTransaction();
$this->doctorRepository->deleteDoctor($doctor_id);
DB::commit();
return baseResponse(
'success',
'success delete doctor data!',
null,
null,
200
);
}catch (Throwable $exception){
DB::rollBack();
return baseResponse(
'failed',
'failed delete doctor data!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Get patient list by doctor authentication.
*
* @return JsonResponse
* @throws Throwable
*/
public function getPatientByDoctor(): JsonResponse
{
try {
$user = Auth::user();
$doctor = $user->doctor;
if (!$doctor){
return baseResponse(
'failed',
'failed get list patient data!',
null,
null,
500
);
}
return baseResponse(
'success',
'success get list patient data!',
$doctor->patients,
null,
200
);
}catch (Throwable $exception){
return baseResponse(
'failed',
'failed get list patient data!',
null,
$exception->getMessage(),
500
);
}
}
}
@@ -0,0 +1,86 @@
<?php
namespace App\Http\Controllers;
use App\Models\Heartwave;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class HeartwaveController extends Controller
{
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param Heartwave $heartwave
* @return Response
*/
public function show(Heartwave $heartwave)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param Heartwave $heartwave
* @return Response
*/
public function edit(Heartwave $heartwave)
{
//
}
/**
* Update the specified resource in storage.
*
* @param Request $request
* @param Heartwave $heartwave
* @return Response
*/
public function update(Request $request, Heartwave $heartwave)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param Heartwave $heartwave
* @return Response
*/
public function destroy(Heartwave $heartwave)
{
//
}
}
+215
View File
@@ -0,0 +1,215 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\PatientRequest;
use App\Interfaces\PatientRepositoryInterface;
use App\Interfaces\UserRepositoryInterface;
use DB;
use Illuminate\Support\Facades\Auth;
use Throwable;
use Illuminate\Http\JsonResponse;
use Hash;
class PatientController extends Controller
{
private PatientRepositoryInterface $patientRepository;
private UserRepositoryInterface $userRepository;
public function __construct(
PatientRepositoryInterface $patientRepository,
UserRepositoryInterface $userRepository
)
{
$this->patientRepository = $patientRepository;
$this->userRepository = $userRepository;
}
/**
* Display a listing of the resource.
*
* @return JsonResponse
*/
public function index(): JsonResponse
{
$data = $this->patientRepository->getAllPatients();
return baseResponse(
'success',
'success get all patient data',
$data,
null,
200
);
}
/**
* Display a listing of the resource.
*
* @return JsonResponse
*/
public function indexExceptDoctor(string $doctor_id): JsonResponse
{
$data = $this->patientRepository->getAllPatientsExceptDoctor($doctor_id);
return baseResponse(
'success',
'success get all patient data',
$data,
null,
200
);
}
/**
* Store a newly created resource in storage.
*
* @param PatientRequest $request
* @return JsonResponse
* @throws Throwable
*/
public function store(PatientRequest $request): JsonResponse
{
try {
$input = $request->all();
DB::beginTransaction();
$user = $this->userRepository->createUser([
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
$user->assignRole('patient');
$input['user_id'] = $user->id;
$patient = $this->patientRepository->createPatient($input);
DB::commit();
return baseResponse(
'success',
'success create patient data!',
$patient,
null,
201
);
}catch (Throwable $exception){
DB::rollBack();
return baseResponse(
'failed',
'failed create patient data!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Display the specified resource.
*
* @param string $patient_id
* @return JsonResponse
*/
public function show(string $patient_id): JsonResponse
{
try {
$patient = $this->patientRepository->getPatientById($patient_id);
$result_patient = collect($patient);
if ($result_patient['diagnoses'] && Auth::user()->doctor){
$result_patient['diagnoses'] = collect($patient['diagnoses'])->where('doctor_id',Auth::user()->doctor->id)->values()->all();
}
return baseResponse(
'success',
'success show patient data!',
$result_patient,
null,
200
);
}catch (Throwable $exception){
return baseResponse(
'failed',
'failed show patient data!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Update the specified resource in storage.
*
* @param PatientRequest $request
* @param string $patient_id
* @return JsonResponse
* @throws Throwable
*/
public function update(PatientRequest $request, string $patient_id): JsonResponse
{
try {
$data = $request->all();
DB::beginTransaction();
$this->patientRepository->updatePatient($patient_id,$data);
DB::commit();
return baseResponse(
'success',
'success update patient data!',
null,
null,
200
);
}catch (Throwable $exception){
DB::rollBack();
return baseResponse(
'failed',
'failed update patient data!',
null,
$exception->getMessage(),
500
);
}
}
/**
* Remove the specified resource from storage.
*
* @param string $patient_id
* @return JsonResponse
* @throws Throwable
*/
public function destroy(string $patient_id): JsonResponse
{
try {
DB::beginTransaction();
$this->patientRepository->deletePatient($patient_id);
DB::commit();
return baseResponse(
'success',
'success delete patient data!',
null,
null,
200
);
}catch (Throwable $exception){
DB::rollBack();
return baseResponse(
'failed',
'failed delete patient data!',
null,
$exception->getMessage(),
500
);
}
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
namespace App\Http;
use App\Http\Middleware\Authenticate;
use App\Http\Middleware\EncryptCookies;
use App\Http\Middleware\PreventRequestsDuringMaintenance;
use App\Http\Middleware\RedirectIfAuthenticated;
use App\Http\Middleware\TrimStrings;
use App\Http\Middleware\TrustProxies;
use App\Http\Middleware\ValidateSignature;
use App\Http\Middleware\VerifyCsrfToken;
use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
use Illuminate\Auth\Middleware\Authorize;
use Illuminate\Auth\Middleware\EnsureEmailIsVerified;
use Illuminate\Auth\Middleware\RequirePassword;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull;
use Illuminate\Foundation\Http\Middleware\ValidatePostSize;
use Illuminate\Http\Middleware\HandleCors;
use Illuminate\Http\Middleware\SetCacheHeaders;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Routing\Middleware\ThrottleRequests;
use Illuminate\Session\Middleware\AuthenticateSession;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
use Spatie\Permission\Middlewares\PermissionMiddleware;
use Spatie\Permission\Middlewares\RoleMiddleware;
use Spatie\Permission\Middlewares\RoleOrPermissionMiddleware;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
TrustProxies::class,
HandleCors::class,
PreventRequestsDuringMaintenance::class,
ValidatePostSize::class,
TrimStrings::class,
ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
ShareErrorsFromSession::class,
VerifyCsrfToken::class,
SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array<string, class-string|string>
*/
protected $routeMiddleware = [
'auth' => Authenticate::class,
'auth.basic' => AuthenticateWithBasicAuth::class,
'auth.session' => AuthenticateSession::class,
'cache.headers' => SetCacheHeaders::class,
'can' => Authorize::class,
'guest' => RedirectIfAuthenticated::class,
'password.confirm' => RequirePassword::class,
'signed' => ValidateSignature::class,
'throttle' => ThrottleRequests::class,
'verified' => EnsureEmailIsVerified::class,
'role' => RoleMiddleware::class,
'permission' => PermissionMiddleware::class,
'role_or_permission' => RoleOrPermissionMiddleware::class,
];
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
// /**
// * Get the path the user should be redirected to when they are not authenticated.
// *
// * @param \Illuminate\Http\Request $request
// * @return string|null
// */
// protected function redirectTo($request)
// {
// if (! $request->expectsJson()) {
// return route('login');
// }
// }
protected function unauthenticated($request, array $guards)
{
return baseResponse(
'failed',
'You do not have the required authorization!',
null,
null,
401
);
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
@@ -0,0 +1,34 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure(Request): (Response|RedirectResponse) $next
* @param string|null ...$guards
* @return Response|RedirectResponse
*/
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts()
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
+82
View File
@@ -0,0 +1,82 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BaseFormRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return match($this->method()){
'POST' => $this->store(),
'PUT', 'PATCH' => $this->update(),
'DELETE' => $this->destroy(),
default => $this->index()
};
}
/**
* Get the validation rules that apply to the get request.
*
* @return array
*/
public function index()
{
return [
//
];
}
/**
* Get the validation rules that apply to the post request.
*
* @return array
*/
public function store()
{
return [
//
];
}
/**
* Get the validation rules that apply to the put/patch request.
*
* @return array
*/
public function update()
{
return [
//
];
}
/**
* Get the validation rules that apply to the delete request.
*
* @return array
*/
public function destroy()
{
return [
//
];
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Http\Requests;
use Illuminate\Validation\Rules\File;
use Illuminate\Validation\Rule;
class DiagnoseRequest extends BaseFormRequest
{
/**
* Get the validation rules that apply to the post request.
*
* @return array
*/
public function store()
{
return [
'diagnoses' => [
Rule::in(['normal','warning','danger']),
'required'
],
'file' => [
'required',
File::types(['mp3','wav'])
->max(2 * 1024),
]
];
}
/**
* Get the validation rules that apply to the put/patch request.
*
* @return array
*/
public function update()
{
return [
];
}
/**
* Get the validation rules that apply to the delete request.
*
* @return array
*/
public function destroy()
{
return [
];
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class DoctorRequest extends BaseFormRequest
{
/**
* Get the validation rules that apply to the post request.
*
* @return array
*/
public function store()
{
return [
'fullname' => 'required',
'address' => 'required',
'phone' => 'required',
'emergency_phone' => 'required',
'gender' => 'required',
'age' => 'required',
// user
'email' => 'required|email',
'password' => 'required',
];
}
/**
* Get the validation rules that apply to the put/patch request.
*
* @return array
*/
public function update()
{
return [
'role' => [
Rule::in(['admin','patient','doctor'])
],
];
}
/**
* Get the validation rules that apply to the delete request.
*
* @return array
*/
public function destroy()
{
return [
];
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, mixed>
*/
public function rules()
{
return [
'email' => 'email|required|string',
'password' => 'required|string'
];
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class PatientRequest extends BaseFormRequest
{
/**
* Get the validation rules that apply to the post request.
*
* @return array
*/
public function store()
{
return [
'fullname' => 'required',
'address' => 'required',
'phone' => 'required',
'emergency_phone' => 'required',
'gender' => 'required',
'age' => 'required',
'device_id' => 'required',
'condition' => 'required',
// user
'email' => 'required|email',
'password' => 'required',
];
}
/**
* Get the validation rules that apply to the put/patch request.
*
* @return array
*/
public function update()
{
return [
'role' => [
Rule::in(['admin','patient','doctor'])
],
];
}
/**
* Get the validation rules that apply to the delete request.
*
* @return array
*/
public function destroy()
{
return [
];
}
}
@@ -0,0 +1,13 @@
<?php
namespace App\Interfaces;
interface DiagnoseRepositoryInterface
{
public function getAllDiagnoses();
public function getCustomAllDiagnoses($customParameter, $id);
public function getDiagnoseById($diagnoseId);
public function deleteDiagnose($diagnoseId);
public function createDiagnose(array $diagnoseData);
public function updateDiagnose($diagnoseId, array $diagnoseData);
}
@@ -0,0 +1,12 @@
<?php
namespace App\Interfaces;
interface DoctorRepositoryInterface
{
public function getAllDoctors();
public function getDoctorById($doctorId);
public function deleteDoctor($doctorId);
public function createDoctor(array $doctorData);
public function updateDoctor($doctorId, array $doctorData);
}
@@ -0,0 +1,15 @@
<?php
namespace App\Interfaces;
interface PatientRepositoryInterface
{
public function getAllPatients();
public function getPatientById($patientId);
public function getManyPatientById($patientIds);
public function deletePatient($patientId);
public function createPatient(array $patientData);
public function updatePatient($patientId, array $patientData);
public function getAllPatientsExceptDoctor($doctorId);
}
@@ -0,0 +1,12 @@
<?php
namespace App\Interfaces;
interface UserRepositoryInterface
{
public function getAllUsers();
public function getUserById($userId);
public function deleteUser($userId);
public function createUser(array $userData);
public function updateUser($userId, array $userData);
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Models;
use App\Traits\UUID;
use Eloquent;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Class Diagnose
* @package App\Models
* @mixin Eloquent
*/
class Diagnose extends Model
{
use HasFactory, UUID;
protected $table = 'diagnoses';
protected $fillable = ['patient_id', 'doctor_id', 'diagnoses','notes','is_verified','file'];
public function doctor() {
return $this->belongsTo(Doctor::class, 'doctor_id', 'id');
}
public function patient() {
return $this->belongsTo(Patient::class);
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Models;
use App\Traits\UUID;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Eloquent;
/**
* Class Doctor
* @package App\Models
* @mixin Eloquent
*/
class Doctor extends Model
{
use HasFactory, UUID;
protected $table = 'doctors';
protected $fillable = ['user_id', 'fullname', 'address', 'phone', 'emergency_phone', 'gender', 'age'];
protected $casts = [
'id' => 'string'
];
protected $hidden = [
'pivot'
];
public function user(){
return $this->hasOne(User::class,'id','user_id');
}
public function patients(){
return $this->belongsToMany(Patient::class,'doctor_patients',
'doctor_id','patient_id')->
withTimestamps();
}
public function pivot(){
return $this->belongsToMany(Patient::class,'doctor_patients',
'doctor_id','patient_id')->
withTimestamps();
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class DoctorPatient extends Model
{
use HasFactory;
protected $table = 'doctor_patients';
protected $fillable = [
'doctor_id',
'patient_id'
];
protected $casts = [
'doctor_id' => 'string',
'patient_id' => 'string'
];
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Heartwave extends Model
{
use HasFactory;
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace App\Models;
use App\Traits\UUID;
use Eloquent;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Class Patient
* @package App\Models
* @mixin Eloquent
*/
class Patient extends Model
{
use HasFactory, UUID;
protected $table = 'patients';
protected $fillable = [
'user_id',
'fullname',
'address',
'phone',
'emergency_phone',
'gender',
'age',
'device_id',
'condition'
];
protected $casts = [
'id' => 'string'
];
protected $hidden = [
'pivot'
];
public function doctors(){
return $this->belongsToMany(Doctor::class,'doctor_patients',
'patient_id','doctor_id')->
withTimestamps();
}
public function user(){
return $this->hasOne(User::class,'id','user_id');
}
public function diagnoses(){
return $this->hasMany(Diagnose::class,'patient_id','id');
}
public function pivot(){
return $this->belongsToMany(Doctor::class,'doctor_patients',
'patient_id','doctor_id')->
withTimestamps();
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace App\Models;
use Auth;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use App\Traits\UUID;
use Spatie\Permission\Traits\HasRoles;
use Eloquent;
/**
* Class User
* @package App\Models
* @mixin Eloquent
*/
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, UUID, HasRoles;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
'roles'
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $guard_name = 'api';
public function doctor()
{
return $this->hasOne(Doctor::class);
}
public function role_data()
{
if (Auth::user()->hasRole('doctor')) {
return $this->hasOne(Doctor::class);
} elseif (Auth::user()->hasRole('patient')) {
return $this->hasOne(Patient::class);
}
}
// public function admin() {
// }
public function patient()
{
return $this->hasOne(Patient::class);
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Providers;
use Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->app->register(IdeHelperServiceProvider::class);
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use Carbon\Carbon;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::tokensExpireIn(Carbon::now()->addDays(1));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(7));
Passport::personalAccessTokensExpireIn(Carbon::now()->addDays(1));
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*
* @return void
*/
public function boot()
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*
* @return bool
*/
public function shouldDiscoverEvents()
{
return false;
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Providers;
use App\Interfaces\DiagnoseRepositoryInterface;
use App\Interfaces\DoctorRepositoryInterface;
use App\Interfaces\PatientRepositoryInterface;
use App\Interfaces\UserRepositoryInterface;
use App\Repositories\DiagnoseRepository;
use App\Repositories\DoctorRepository;
use App\Repositories\PatientRepository;
use App\Repositories\UserRepository;
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
$this->app->bind(PatientRepositoryInterface::class, PatientRepository::class);
$this->app->bind(UserRepositoryInterface::class, UserRepository::class);
$this->app->bind(DoctorRepositoryInterface::class, DoctorRepository::class);
$this->app->bind(DiagnoseRepositoryInterface::class, DiagnoseRepository::class);
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*
* @return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*
* @return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Repositories;
use App\Interfaces\DiagnoseRepositoryInterface;
use App\Models\Diagnose;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
class DiagnoseRepository implements DiagnoseRepositoryInterface
{
public function getAllDiagnoses(): \Illuminate\Support\Collection
{
return Diagnose::orderBy('updated_at', 'desc')->get();
}
public function getCustomAllDiagnoses($customParameter, $id): Collection
{
return Diagnose::with('doctor','patient')->where($customParameter,$id)->orderBy('updated_at', 'desc')->get();
}
public function getDiagnoseById($diagnoseId): Model|Diagnose|array|Collection
{
return Diagnose::with('doctor','patient')->findOrFail($diagnoseId);
}
public function deleteDiagnose($diagnoseId): int
{
return Diagnose::destroy($diagnoseId);
}
public function createDiagnose(array $diagnoseData): Model|Diagnose
{
return Diagnose::create($diagnoseData);
}
public function updateDiagnose($diagnoseId, array $diagnoseData)
{
return Diagnose::whereId($diagnoseId)->update($diagnoseData);
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Repositories;
use App\Interfaces\DoctorRepositoryInterface;
use App\Models\Doctor;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
class DoctorRepository implements DoctorRepositoryInterface
{
public function getAllDoctors(): Collection
{
return Doctor::all();
}
public function getDoctorById($doctorId)
{
return Doctor::with('user','patients')->findOrFail($doctorId);
}
public function deleteDoctor($doctorId): int
{
return Doctor::destroy($doctorId);
}
public function createDoctor(array $doctorData): Model|Doctor
{
return Doctor::create($doctorData);
}
public function updateDoctor($doctorId, array $doctorData): bool
{
return Doctor::find($doctorId)->update($doctorData);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Repositories;
use App\Interfaces\PatientRepositoryInterface;
use App\Models\Doctor;
use App\Models\DoctorPatient;
use App\Models\Patient;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
class PatientRepository implements PatientRepositoryInterface
{
public function getAllPatients(): \Illuminate\Support\Collection
{
return Patient::orderBy('updated_at', 'asc')->get();
}
public function getAllPatientsExceptDoctor($doctorId): Collection
{
$patients = Patient::all();
$patient_doctor = Doctor::find($doctorId)->patients;
return $patients->diff($patient_doctor);
}
public function getPatientById($patientId): Model|Collection|Builder|array|null
{
return Patient::with(['user', 'doctors', 'diagnoses' => function ($query) {
$query->orderBy('updated_at', 'desc');
}])->findOrFail($patientId);
}
public function deletePatient($patientId): int
{
return Patient::destroy($patientId);
}
public function createPatient(array $patientData): Model|Patient
{
return Patient::create($patientData);
}
public function updatePatient($patientId, array $patientData): bool
{
return Patient::find($patientId)->update($patientData);
}
public function getManyPatientById($patientIds): Collection
{
return Patient::with('user')->findMany($patientIds);
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Repositories;
use App\Interfaces\UserRepositoryInterface;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
class UserRepository implements UserRepositoryInterface
{
public function getAllUsers()
{
return User::all();
}
public function getUserById($userId): Model|User|array|Collection
{
return User::findOrFail($userId);
}
public function deleteUser($userId): int
{
return User::destroy($userId);
}
public function createUser(array $userData): Model|User
{
return User::create($userData);
}
public function updateUser($userId, array $userData)
{
return User::whereId($userId)->update($userData);
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait UUID
{
protected static function boot ()
{
// Boot other traits on the Model
parent::boot();
/**
* Listen for the creating event on the user model.
* Sets the 'id' to a UUID using Str::uuid() on the instance being created
*/
static::creating(function ($model) {
if ($model->getKey() === null) {
$model->setAttribute($model->getKeyName(), Str::uuid()->toString());
}
});
}
// Tells the database not to auto-increment this field
public function getIncrementing ()
{
return false;
}
// Helps the application specify the field type in the database
public function getKeyType ()
{
return 'string';
}
}