From 0dc960a1edbde2ba424d391b3a3fb87353c39fd3 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Fri, 8 Jul 2022 14:37:42 +0700 Subject: [PATCH 01/19] move sql to db dir --- {sql => database/sql}/001-absensi.sql | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {sql => database/sql}/001-absensi.sql (100%) diff --git a/sql/001-absensi.sql b/database/sql/001-absensi.sql similarity index 100% rename from sql/001-absensi.sql rename to database/sql/001-absensi.sql From 02daf0b2e9f0fe258ec4e2f021a1c0f2a5236d16 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Fri, 8 Jul 2022 14:38:03 +0700 Subject: [PATCH 02/19] remove whitespaces&comments --- config/api.php | 6 ++---- config/auth.php | 4 ++-- routes/web.php | 39 +++++++++++++-------------------------- 3 files changed, 17 insertions(+), 32 deletions(-) diff --git a/config/api.php b/config/api.php index 6edc41c..dfe274b 100644 --- a/config/api.php +++ b/config/api.php @@ -1,7 +1,5 @@ - env('API_GOLANG', 'http://127.0.0.1:8090'), - 'paxel' => env('API_PAXEL', 'https://paxel.oslogdev.com/db/search'), 'nominatim' => env('API_NOMINATIM', 'https://nominatim.oslogdev.com') ]; -?> \ No newline at end of file +?> diff --git a/config/auth.php b/config/auth.php index 43c69ca..7828955 100644 --- a/config/auth.php +++ b/config/auth.php @@ -1,4 +1,4 @@ - [ @@ -19,4 +19,4 @@ return [ ] ]; -?> \ No newline at end of file +?> diff --git a/routes/web.php b/routes/web.php index 6bf0b77..4b2ca96 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,33 +1,20 @@ get('/', function () use ($router) { return $router->app->version(); }); $router->group(['prefix'=>'api'], function () use ($router) { $router->post('/login', 'AuthController@login'); - + $router->post('/role/search', 'RoleController@search'); $router->post('/role/add', 'RoleController@add'); $router->get('/role/edit/{id}', 'RoleController@edit'); $router->put('/role/update/{id}', 'RoleController@update'); $router->delete('/role/delete/{id}', 'RoleController@delete'); $router->get('/role/list', 'RoleController@list'); - - + + $router->post('/menu/add', 'MenuController@add'); $router->get('/menu/edit/{id}', 'MenuController@edit'); $router->put('/menu/update/{id}', 'MenuController@update'); @@ -49,14 +36,14 @@ $router->group(['prefix'=>'api'], function () use ($router) { $router->get('/document-project/get/{id}', 'ProjectDokumenController@dokumenByProyekId'); $router->delete('/document-project/delete/{id}', 'ProjectDokumenController@delete'); $router->post('/document-project/search', 'ProjectDokumenController@searchDocProject'); - + $router->post('/document-activity/upload', 'ActivityDokumenController@uploadProjectDokumen'); $router->get('/document-activity/get/{id}', 'ActivityDokumenController@dokumenByActivityId'); $router->delete('/document-activity/delete/{id}', 'ActivityDokumenController@delete'); $router->post('/document-activity/search', 'ActivityDokumenController@searchDocProject'); $router->get('/document-activity/download/{id}', 'ActivityDokumenController@downloadDokumen'); - + $router->post('/project/search', 'ProjectController@search'); $router->post('/project/add', 'ProjectController@add'); $router->put('/project/update/{id}', 'ProjectController@update'); @@ -122,9 +109,9 @@ $router->group(['prefix'=>'api'], function () use ($router) { $router->get('/request-material/list', 'RequestMaterialController@list'); $router->put('/request-material/update-warehouse-site/{id}', 'RequestMaterialController@updateWarehouseSite'); - + $router->post('/material-to-project/assign', 'MaterialProjectController@assignMaterial'); - + $router->post('/material-resource/add', 'MaterialResourceController@add'); $router->post('/material-resource/search', 'MaterialResourceController@search'); $router->get('/material-resource/update/{id}', 'MaterialResourceController@edit'); @@ -166,7 +153,7 @@ $router->group(['prefix'=>'api'], function () use ($router) { $router->delete('/user-to-version-gantt/delete/{id}', 'UserToVersionGanttController@delete'); $router->get('/user-to-version-gantt/list', 'UserToVersionGanttController@list'); $router->get('/user-to-version-gantt/get-by-gantt/{gantt_id}', 'UserToVersionGanttController@getByUserGantt'); - + $router->post('/user-to-activity/add', 'UserToActivityController@add'); $router->post('/user-to-activity/add-multiple', 'UserToActivityController@addMultiple'); $router->get('/user-to-activity/edit/{id}', 'UserToActivityController@edit'); @@ -189,7 +176,7 @@ $router->group(['prefix'=>'api'], function () use ($router) { $router->get('/activity/set-baseline/{gantt_id}', 'ActivityController@setBaseline'); $router->post('/activity/get-curva-s', 'ActivityController@getCalculateCurvaS'); $router->get('/activity/synchronize-report/{gantt_id}', 'ActivityController@synchronizeReport'); - + $router->post('/link', 'LinkController@add'); $router->put('/link/{id}', 'LinkController@update'); $router->delete('/link/{id}', 'LinkController@delete'); @@ -296,7 +283,7 @@ $router->group(['prefix'=>'api'], function () use ($router) { $router->post('/dashboard/search-user-presence', 'DashboardController@searchUserPresencePoints'); $router->post('/dashboard/status-proyek', 'DashboardController@statusProyek'); $router->post('/dashboard/curva-s', 'DashboardController@curvaS'); - + $router->post('/report-activity/add', 'ReportActivityController@add'); $router->get('/report-activity/edit/{id}', 'ReportActivityController@edit'); $router->put('/report-activity/update/{id}', 'ReportActivityController@update'); @@ -313,7 +300,7 @@ $router->group(['prefix'=>'api'], function () use ($router) { $router->get('/report-activity-material/datatables', 'ReportActivityMaterialController@datatables'); $router->post('/report-activity-material/update-status', 'ReportActivityMaterialController@updateStatusStartFinish'); $router->get('/report-activity-material/test', 'ReportActivityMaterialController@countForProgressTest'); - + $router->post('/waypoint/add', 'WaypointController@add'); $router->get('/waypoint/edit/{id}', 'WaypointController@edit'); @@ -420,5 +407,5 @@ $router->group(['prefix'=>'api'], function () use ($router) { $router->delete('/project-to-checklist-k3/delete/{id}', 'ProjectToChecklistK3Controller@delete'); $router->get('/project-to-checklist-k3/list', 'ProjectToChecklistK3Controller@list'); }); - -}); \ No newline at end of file + +}); From d8c71b3802a3b2c698dfde5298ccba65e04cf2ff Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Fri, 8 Jul 2022 17:15:30 +0700 Subject: [PATCH 03/19] add assets --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 8c80041..66ed42a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ /vendor /.idea +/assets /storage Homestead.json Homestead.yaml From 0cc81339f5081be8cd1119a68c2da8829030cef9 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Fri, 8 Jul 2022 17:18:03 +0700 Subject: [PATCH 04/19] move role routes & project doc download to auth group --- routes/web.php | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/routes/web.php b/routes/web.php index 4b2ca96..abd459e 100644 --- a/routes/web.php +++ b/routes/web.php @@ -7,14 +7,6 @@ $router->get('/', function () use ($router) { $router->group(['prefix'=>'api'], function () use ($router) { $router->post('/login', 'AuthController@login'); - $router->post('/role/search', 'RoleController@search'); - $router->post('/role/add', 'RoleController@add'); - $router->get('/role/edit/{id}', 'RoleController@edit'); - $router->put('/role/update/{id}', 'RoleController@update'); - $router->delete('/role/delete/{id}', 'RoleController@delete'); - $router->get('/role/list', 'RoleController@list'); - - $router->post('/menu/add', 'MenuController@add'); $router->get('/menu/edit/{id}', 'MenuController@edit'); $router->put('/menu/update/{id}', 'MenuController@update'); @@ -28,15 +20,21 @@ $router->group(['prefix'=>'api'], function () use ($router) { $router->delete('/role-menu/delete-byrole/{id}', 'RoleMenuController@deleteByRole'); $router->post('/role-menu/search', 'RoleMenuController@search'); $router->get('/role-menu/get-role/{id}', 'RoleMenuController@listMenu'); - $router->get('/document-project/download/{id}', 'ProjectDokumenController@downloadDokumen'); $router->group(['middleware' => 'auth'], function () use ($router) { + $router->post('/role/search', 'RoleController@search'); + $router->post('/role/add', 'RoleController@add'); + $router->get('/role/edit/{id}', 'RoleController@edit'); + $router->put('/role/update/{id}', 'RoleController@update'); + $router->delete('/role/delete/{id}', 'RoleController@delete'); + $router->get('/role/list', 'RoleController@list'); + $router->post('/document-project/upload', 'ProjectDokumenController@uploadProjectDokumen'); $router->get('/document-project/get/{id}', 'ProjectDokumenController@dokumenByProyekId'); $router->delete('/document-project/delete/{id}', 'ProjectDokumenController@delete'); $router->post('/document-project/search', 'ProjectDokumenController@searchDocProject'); - + $router->get('/document-project/download/{id}', 'ProjectDokumenController@downloadDokumen'); $router->post('/document-activity/upload', 'ActivityDokumenController@uploadProjectDokumen'); $router->get('/document-activity/get/{id}', 'ActivityDokumenController@dokumenByActivityId'); From 00b8602cab69ccd4c55d07a22103f2517ca4d933 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Sat, 9 Jul 2022 11:09:11 +0700 Subject: [PATCH 05/19] clean controllers --- .../Controllers/ActivityDokumenController.php | 174 ++++--- app/Http/Controllers/AuthController.php | 27 +- app/Http/Controllers/DashboardController.php | 455 ++++++++---------- app/Http/Controllers/DivisiController.php | 155 +++--- app/Http/Controllers/ProjectController.php | 415 ++++++++-------- .../Controllers/ProjectDokumenController.php | 179 +++---- app/Http/Controllers/RoleController.php | 191 ++++---- 7 files changed, 766 insertions(+), 830 deletions(-) diff --git a/app/Http/Controllers/ActivityDokumenController.php b/app/Http/Controllers/ActivityDokumenController.php index d0add21..f3a1143 100644 --- a/app/Http/Controllers/ActivityDokumenController.php +++ b/app/Http/Controllers/ActivityDokumenController.php @@ -7,93 +7,89 @@ use App\Models\ActivityDokumen; class ActivityDokumenController extends Controller { - public function dokumenByActivityId($id){ - if($id && $id!="" && (int)$id > 0){ - $dataDokumen = ActivityDokumen::where("activity_id", $id)->get(); - - return response()->json(['status'=>'success','data'=>$dataDokumen,'code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'activity id is required!','code'=>400], 400); - } - } - - public function delete($id) - { - if($id && $id!="" && (int)$id > 0){ - $dokumen = ActivityDokumen::find($id); - if($dokumen){ - if(file_exists($this->pathActivityDocument.$dokumen->file)){ - unlink($this->pathActivityDocument.$dokumen->file); - } - $dokumen->delete(); - return response()->json(['status'=>'success','message'=>'Dokumen deleted successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'Dokumen not found!','code'=>400], 400); - } - }else{ - return response()->json(['status'=>'failed','message'=>'Id is required!','code'=>400], 400); - } - } - - public function uploadProjectDokumen(Request $request) - { - if($request->hasFile('dokumen')){ - $activity_id = $request->activity_id; - $dokumen = $request->file('dokumen'); - $extension = $dokumen->extension(); - $name = $dokumen->getClientOriginalName(); - - $result = $dokumen->move($this->pathActivityDocument, $name); - if($result){ - $data = [ - 'activity_id' => (int)$activity_id, - 'file' => $name, - 'description' => $request->description - ]; - - $result = ActivityDokumen::create($data); - - if($result){ - return response()->json(['status'=>'success','message'=>'file upload is successfully!','code'=>200], 200); - }else{ - unlink($this->pathActivityDocument.$name); - return response()->json(['status'=>'failed','message'=>'file upload is failed!','code'=>400], 400); - } - - }else{ - return response()->json(['status'=>'failed','message'=>'file upload is failed!','code'=>400], 400); - } - }else{ - return response()->json(['status'=>'failed','message'=>'file is required!','code'=>400], 400); - } - } - - public function searchDocProject(Request $request){ - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_document_activity'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function downloadDokumen($id) - { - if($id && $id!="" && (int)$id > 0){ - $dokumen = ActivityDokumen::find($id); - if($dokumen){ - if(file_exists($this->pathActivityDocument.$dokumen->file)){ - $pathToFile = $this->pathActivityDocument.$dokumen->file; - return response()->download($pathToFile); - }else{ - return response()->json(['status'=>'failed','message'=>'Dokumen not found!','code'=>400], 400); - } - }else{ - return response()->json(['status'=>'failed','message'=>'Dokumen not found!','code'=>400], 400); - } - }else{ - return response()->json(['status'=>'failed','message'=>'Id is required!','code'=>400], 400); - } - } + + public function dokumenByActivityId($id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'activity id is required!','code'=>400], 400); + + $dataDokumen = ActivityDokumen::where("activity_id", $id)->get(); + return response()->json(['status'=>'success','data'=>$dataDokumen,'code'=>200], 200); + } + + public function delete($id) + { + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'Id is required!','code'=>400], 400); + + $document = ActivityDokumen::find($id); + + if(!$document) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + + if(file_exists($this->pathActivityDocument.$document->file)) + unlink($this->pathActivityDocument.$document->file); + + $document->delete(); + return response()->json(['status'=>'success','message'=>'Dokumen deleted successfully!','code'=>200], 200); + } + + public function uploadProjectDokumen(Request $request) + { + if(!$request->hasFile('dokumen')) + return response()->json(['status'=>'failed','message'=>'file is required!','code'=>400], 400); + + $activity_id = $request->activity_id; + $document = $request->file('dokumen'); + $name = $document->getClientOriginalName(); + + $result = $document->move($this->pathActivityDocument, $name); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'Upload failed!','code'=> 500], 500); + + $data = [ + 'activity_id' => (int)$activity_id, + 'file' => $name, + 'description' => $request->description + ]; + + $result = ActivityDokumen::create($data); + + if(!$result){ + unlink($this->pathActivityDocument.$name); + return response()->json(['status'=>'failed','message'=>'Upload failed!','code'=> 500], 500); + } + + return response()->json(['status'=>'success','message'=>'Upload success!','code'=>200], 200); + } + + public function searchDocProject(Request $request){ + $payload = $request->all(); + + $dataBuilder = $this->setUpPayload($payload, 'm_document_activity'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function downloadDokumen($id) + { + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'Id is required!','code'=>400], 400); + + $document = ActivityDokumen::find($id); + + if(!$document) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>400], 400); + + if(file_exists($this->pathActivityDocument.$document->file)){ + $pathToFile = $this->pathActivityDocument.$document->file; + return response()->download($pathToFile); + } + + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>400], 400); + } } diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 6324987..f50d5c2 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -7,21 +7,14 @@ use Illuminate\Http\Request; use App\Models\User; use App\Models\Role; -use App\Models\Project; -use App\Models\UserProject; class AuthController extends Controller { - /** - * Create a new AuthController instance. - * - * @return void - */ public function __construct() { $this->middleware('auth:api', ['except' => ['login']]); } - + public function login(Request $request) { $username = $request->username; @@ -32,13 +25,7 @@ class AuthController extends Controller return response()->json(['status'=>'error','message'=>'You must fill all the fields'], 400); } - $credentials = array( - "username"=> $username, - "password"=> md5($password) - ); - - $user = User::where('username', $username)->where('password', md5($password)) - ->first(); + $user = User::where('username', $username)->where('password', md5($password))->first(); if($is_mobile){ $fcm_token = $request->fcm_token; @@ -55,7 +42,7 @@ class AuthController extends Controller $hr = User::find($user->id); if($hr){ - $result = $hr->update($dataUpdateFcm); + $hr->update($dataUpdateFcm); } } @@ -65,7 +52,7 @@ class AuthController extends Controller $user->role = $dataRole; } - + if (! $token =Auth::login($user)) { return response()->json(['error' => 'Unauthorized'], 401); } @@ -76,12 +63,12 @@ class AuthController extends Controller protected function respondWithToken($token, $user) { return response()->json([ - 'code' => 200, + 'code' => 200, 'data' => array( 'data_user' => $user, - 'access_token' => $token, + 'access_token' => $token, 'token_type' => 'bearer', - 'expires_in' => auth()->factory()->getTTL() * 60 + 'expires_in' => auth()->factory()->getTTL() * 360 ), ]); } diff --git a/app/Http/Controllers/DashboardController.php b/app/Http/Controllers/DashboardController.php index 9a6b278..2623b1c 100644 --- a/app/Http/Controllers/DashboardController.php +++ b/app/Http/Controllers/DashboardController.php @@ -6,247 +6,220 @@ use Illuminate\Http\Request; use App\Models\Project; use App\Models\Activity; use App\Models\ReportActivity; -use App\Models\UserToActivity; -use DB; +use App\Models\Role; class DashboardController extends Controller { - public function costPlanningActual(Request $request) - { - $dataPayload = $request->all(); - $dataMaxVersionGantt = []; - foreach ($dataPayload['project_id'] as $val) { - $dataMaxVersionGantt[] = $this->getMaxVersionGantt($val); - } - - $dataFinal=[]; - foreach ($dataMaxVersionGantt as $val) { - $data = Activity::select('m_activity.id', 'm_activity.proyek_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.rencana_biaya', 'm_activity.biaya_actual', 'mp.nama as proyek_name')->join("m_proyek as mp", "m_activity.proyek_id", "=", "mp.id")->where('proyek_id', $val['proyek_id'])->where('version_gantt_id', $val['last_version_gantt'])->whereNull('parent_id')->orderBy('id', 'asc')->get(); - $dataFinal[] = array("proyek_id" => $val['proyek_id'], "proyek_name" => isset($data) && count($data) > 0 ? $data[0]['proyek_name'] : "-", "version_gantt_id" => $val['last_version_gantt'], "data" => $data); - } - - if($dataPayload){ - return response()->json(['status'=>'success','code'=>200,'data'=>$dataFinal, 'totalRecord'=>1], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list role, please try again later!','code'=>400], 400); - } - } - - public function getMaxVersionGantt($id){ - $data = Activity::select(Activity::raw('MAX(version_gantt_id) as last_version_gantt'))->where("proyek_id", $id)->first(); - return array("last_version_gantt"=>$data->last_version_gantt, "proyek_id" => $id, "proyek_name" => $data->proyek_name); - } - - public function percentagePlanningActual(Request $request) - { - $dataPayload = $request->all(); - $dataMaxVersionGantt = []; - foreach ($dataPayload['project_id'] as $val) { - $dataMaxVersionGantt[] = $this->getMaxVersionGantt($val); - } - $dataFinal=[]; - foreach ($dataMaxVersionGantt as $val) { - $data = Activity::select('m_activity.id', 'm_activity.proyek_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.persentase_progress', 'm_activity.persentase_bobot', 'm_activity.bobot_planning', 'mp.nama as proyek_name')->join("m_proyek as mp", "m_activity.proyek_id", "=", "mp.id")->where('proyek_id', $val['proyek_id'])->where('version_gantt_id', $val['last_version_gantt'])->whereNull('parent_id')->orderBy('id', 'asc')->get(); - $dataFinal[] = array("proyek_id" => $val['proyek_id'], "proyek_name" => isset($data) && count($data) > 0 ? $data[0]['proyek_name'] : "-", "version_gantt_id" => $val['last_version_gantt'], "data" => $data); - - } - - if($dataPayload){ - return response()->json(['status'=>'success','code'=>200,'data'=>$dataFinal, 'totalRecord'=>1], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list role, please try again later!','code'=>400], 400); - } - } - - public function list() - { - $data = Role::all(); - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list role, please try again later!','code'=>400], 400); - } - } - - - - - - - public function getActivityByProjectId($projectId) { - $output = []; - $data = Activity::select('id')->where('proyek_id', $projectId)->get(); - if (count($data) > 0) { - foreach ($data as $actData) { - $output[] = $actData->id; - } - } - return $output; - } - - /* for statusProyek, I want something output like this - const statusProyek = [ - { - "id": "1", - "proyek_name": "Pembuatan Aplikasi Survey Covid Varian Baru", // ambil dari m_proyek - "total_task": 80, // ambil dari m_activity -> SUM(jumlah_pekerjaan) where proyek_id berdasarkan proyek_id terpilih - "task_on_progress": 60, // ambil dari report_activity -> SUM(job_count_report) where activity_id berdasarkan activity_id terpilih - "day_left": 7, // ambil dari m_proyek, cari sisa hari (end_date - hari ini) - "percentage": 75 // (task_on_progress / total_task * 100) - }, - { - "id": "2", - "proyek_name": "Pembangunan Jembatan Layang", - "total_task": 70, // SELECT SUM(jumlah_pekerjaan) FROM public.m_activity WHERE proyek_id IN (11); - "task_on_progress": 70, // SELECT SUM(job_count_report) FROM public.report_activity WHERE activity_id IN (349, 355); - "day_left": 0, - "percentage": 100 - }, - ... - ] - */ - public function statusProyek(Request $request) { - $dataPayload = $request->all(); - $reqProject = []; - $dataFinal = []; - - if (!isset($dataPayload['project_id'])) { - return response()->json(['status'=>'failed','message'=>'Undefined project_id','code'=>400], 400); - } - - foreach ($dataPayload['project_id'] as $val) { - $prj["project_id"] = $val; - $prj["activity_id"] = $this->getActivityByProjectId($val); - - $reqProject[] = $prj; - } - - if (count($reqProject) > 0) { - $row = []; - - for ($i=0; $i < count($reqProject); $i++) { - $dataMaxVersionGantt = Activity::select(Activity::raw('MAX(version_gantt_id) as last_version_gantt'))->where("proyek_id", $reqProject[$i]['project_id'])->first(); - $last_version_gantt = $dataMaxVersionGantt->last_version_gantt; - $queryProject = Project::select('id', 'nama', 'mulai_proyek', 'akhir_proyek')->where('id',$reqProject[$i]['project_id'])->first(); - $sum_jumlah_pekerjaan = Activity::where('proyek_id', $reqProject[$i]['project_id'])->where('version_gantt_id', $last_version_gantt)->sum("jumlah_pekerjaan"); - $count_activity = Activity::where('proyek_id', $reqProject[$i]['project_id'])->where('version_gantt_id', $last_version_gantt)->count("id"); - $count_activity_done = Activity::where('proyek_id', $reqProject[$i]['project_id'])->where('persentase_progress', '100')->where('version_gantt_id', $last_version_gantt)->count("id"); - $progress_percentage = Activity::where('proyek_id', $reqProject[$i]['project_id'])->whereNull('parent_id')->where('version_gantt_id', $last_version_gantt)->sum("persentase_progress"); - $count_progress_percentage = Activity::where('proyek_id', $reqProject[$i]['project_id'])->whereNull('parent_id')->where('version_gantt_id', $last_version_gantt)->count("persentase_progress"); - - $progress_actual = Activity::select('id', 'bobot_planning', 'persentase_progress')->where('proyek_id', $reqProject[$i]['project_id'])->whereNull('parent_id')->where('version_gantt_id', $last_version_gantt)->get(); - $current_progress = 0; - foreach($progress_actual as $objRow) { - $current_progress += ($objRow->bobot_planning * $objRow->persentase_progress) / 100; - } - - if (count($reqProject[$i]['activity_id']) > 0) { - for ($j=0; $j < count($reqProject[$i]['activity_id']); $j++) { - $sum_job_count_report = ReportActivity::whereIn('activity_id', $reqProject[$i]['activity_id'])->sum("job_count_report"); - } - } - - if (!isset($queryProject->id)) { - return response()->json(['status'=>'failed','message'=>'Project with id='.$reqProject[$i]['project_id'].' is not found!','code'=>400], 400); - } - - $now = time(); - $akhir_proyek = strtotime($queryProject->akhir_proyek); - $datediff = $akhir_proyek - $now; - - $mulai_proyek = strtotime($queryProject->mulai_proyek); - $total_kontrak = $akhir_proyek - $mulai_proyek; - - $row["id"] = $queryProject->id; - $row["proyek_name"] = $queryProject->nama; - $row["mulai_proyek"] = $queryProject->mulai_proyek; - $row["akhir_proyek"] = $queryProject->akhir_proyek; - $row["total_kontrak"] = round($total_kontrak / (60 * 60 * 24)); - $row["total_task"] = $sum_jumlah_pekerjaan; - $row["task_on_progress"] = $sum_job_count_report; - $row["count_activity"] = $count_activity; - $row["count_activity_done"] = $count_activity_done; - $row["day_left"] = round($datediff / (60 * 60 * 24)); - $row["percentage"] = round($current_progress,3); - $row["count_progress_percentage"] = $count_progress_percentage; - - $dataFinal[] = $row; - } - } - - if($dataFinal){ - return response()->json(['status'=>'success','code'=>200,'data'=>$dataFinal, 'totalRecord'=>count($dataFinal)], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get status proyek, please try again later!','code'=>400], 400); - } - - } - - public function curvaS(Request $request) - { - $dataPayload = $request->all(); - $dataMaxVersionGantt = []; - foreach ($dataPayload['project_id'] as $val) { - $dataMaxVersionGantt[] = $this->getMaxVersionGantt($val); - } - $dataFinal=[]; - foreach ($dataMaxVersionGantt as $val) { - $data = Activity::select('m_activity.id', 'm_activity.proyek_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.persentase_progress', 'm_activity.persentase_bobot', 'm_activity.bobot_planning', 'm_activity.biaya_actual', 'mp.nama as proyek_name')->join("m_proyek as mp", "m_activity.proyek_id", "=", "mp.id")->where('proyek_id', $val['proyek_id'])->where('version_gantt_id', $val['last_version_gantt'])->whereNull('parent_id')->orderBy('id', 'asc')->get(); - $totalCostPlanning = Activity::where('proyek_id', $val['proyek_id'])->where('version_gantt_id', $val['last_version_gantt'])->whereNull('parent_id')->sum('rencana_biaya'); - $dataBobotPlan =[]; - for ($i=0; $i < count($data); $i++) { - $tmpp = 0; - $tmpa = 0; - $tmpbc = 0; - $tmpac = 0; - for ($x=$i; $x >= 0 ; $x--) { - $tmpp += $data[$x]['bobot_planning']; - $tmpa += ($data[$x]['persentase_progress'] * $data[$x]['bobot_planning'])/100; - $tmpbc += ((($data[$x]['persentase_progress'] * $data[$x]['bobot_planning'])/100)*$totalCostPlanning)/100; - $tmpac += $data[$x]['biaya_actual']; - } - - $data[$i]['cal_bobot_p'] = round($tmpp,2); - if($i > 0 ){ - if($data[$i-1]['cal_bobot_a'] != null){ - if($data[$i-1]['cal_bobot_a'] == round($tmpa,2)){ - $data[$i]['cal_bobot_a'] = null; - }else{ - $data[$i]['cal_bobot_a'] = round($tmpa,2); - } - }else{ - $data[$i]['cal_bobot_a'] = null; - } - }else{ - $data[$i]['cal_bobot_a'] = round($tmpa,2); - } - $data[$i]['cal_budget_cost'] = round($tmpbc,2); - - if($i > 0 ){ - if($data[$i-1]['cal_actual_cost'] != null){ - if($data[$i-1]['cal_actual_cost'] == round($tmpac,2)){ - $data[$i]['cal_actual_cost'] = null; - }else{ - $data[$i]['cal_actual_cost'] = round($tmpac,2); - } - }else{ - $data[$i]['cal_actual_cost'] = null; - } - }else{ - $data[$i]['cal_actual_cost'] = round($tmpac,2); - } - } - - $dataFinal[] = array("proyek_id" => $val['proyek_id'], "proyek_name" => isset($data) && count($data) > 0 ? $data[0]['proyek_name'] : "-", "version_gantt_id" => $val['last_version_gantt'], "data" => $data); - - } - - if($dataPayload){ - return response()->json(['status'=>'success','code'=>200, 'data'=>$dataFinal, 'totalRecord'=>1], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list role, please try again later!','code'=>400], 400); - } - } -} \ No newline at end of file + public function costPlanningActual(Request $request) + { + $dataPayload = $request->all(); + $dataMaxVersionGantt = []; + foreach ($dataPayload['project_id'] as $val) { + $dataMaxVersionGantt[] = $this->getMaxVersionGantt($val); + } + + $dataFinal=[]; + foreach ($dataMaxVersionGantt as $val) { + $data = Activity::select('m_activity.id', 'm_activity.proyek_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.rencana_biaya', 'm_activity.biaya_actual', 'mp.nama as proyek_name')->join("m_proyek as mp", "m_activity.proyek_id", "=", "mp.id")->where('proyek_id', $val['proyek_id'])->where('version_gantt_id', $val['last_version_gantt'])->whereNull('parent_id')->orderBy('id', 'asc')->get(); + $dataFinal[] = array("proyek_id" => $val['proyek_id'], "proyek_name" => isset($data) && count($data) > 0 ? $data[0]['proyek_name'] : "-", "version_gantt_id" => $val['last_version_gantt'], "data" => $data); + } + + if(!$dataFinal) + return response()->json(['status'=>'failed','message'=>'Data not found','code'=> 404], 404); + + return response()->json(['status'=>'success','code'=>200,'data'=>$dataFinal, 'totalRecord'=>1], 200); + } + + public function getMaxVersionGantt($id){ + $data = Activity::select(Activity::raw('MAX(version_gantt_id) as last_version_gantt'))->where("proyek_id", $id)->first(); + return array("last_version_gantt"=>$data->last_version_gantt, "proyek_id" => $id, "proyek_name" => $data->proyek_name); + } + + public function percentagePlanningActual(Request $request) + { + $dataPayload = $request->all(); + $dataMaxVersionGantt = []; + foreach ($dataPayload['project_id'] as $val) { + $dataMaxVersionGantt[] = $this->getMaxVersionGantt($val); + } + $dataFinal=[]; + foreach ($dataMaxVersionGantt as $val) { + $data = Activity::select('m_activity.id', 'm_activity.proyek_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.persentase_progress', 'm_activity.persentase_bobot', 'm_activity.bobot_planning', 'mp.nama as proyek_name')->join("m_proyek as mp", "m_activity.proyek_id", "=", "mp.id")->where('proyek_id', $val['proyek_id'])->where('version_gantt_id', $val['last_version_gantt'])->whereNull('parent_id')->orderBy('id', 'asc')->get(); + $dataFinal[] = array("proyek_id" => $val['proyek_id'], "proyek_name" => isset($data) && count($data) > 0 ? $data[0]['proyek_name'] : "-", "version_gantt_id" => $val['last_version_gantt'], "data" => $data); + } + + if(!$dataFinal) + return response()->json(['status'=>'failed','message'=>'failed get list role, please try again later!','code'=>400], 400); + + return response()->json(['status'=>'success','code'=>200,'data'=>$dataFinal, 'totalRecord'=>1], 200); + } + + public function list() + { + $data = Role::all(); + $countData = $data->count(); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'failed get list role, please try again later!','code'=>400], 400); + + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + } + + public function getActivityByProjectId($projectId) { + $output = []; + $data = Activity::select('id')->where('proyek_id', $projectId)->get(); + foreach ($data as $actData) { + $output[] = $actData->id; + } + return $output; + } + + /* + const statusProyek = [ + { + "id": "1", + "proyek_name": "Pembuatan Aplikasi Survey Covid Varian Baru", // ambil dari m_proyek + "total_task": 80, // ambil dari m_activity -> SUM(jumlah_pekerjaan) where proyek_id berdasarkan proyek_id terpilih + "task_on_progress": 60, // ambil dari report_activity -> SUM(job_count_report) where activity_id berdasarkan activity_id terpilih + "day_left": 7, // ambil dari m_proyek, cari sisa hari (end_date - hari ini) + "percentage": 75 // (task_on_progress / total_task * 100) + }, + { + "id": "2", + "proyek_name": "Pembangunan Jembatan Layang", + "total_task": 70, // SELECT SUM(jumlah_pekerjaan) FROM public.m_activity WHERE proyek_id IN (11); + "task_on_progress": 70, // SELECT SUM(job_count_report) FROM public.report_activity WHERE activity_id IN (349, 355); + "day_left": 0, + "percentage": 100 + }, + ... + ] + */ + public function statusProyek(Request $request) { + $dataPayload = $request->all(); + $reqProject = $dataFinal = []; + + if (!isset($dataPayload['project_id'])) + return response()->json(['status'=>'failed','message'=>'Undefined project_id','code'=>400], 400); + + foreach ($dataPayload['project_id'] as $val) { + $prj["project_id"] = $val; + $prj["activity_id"] = $this->getActivityByProjectId($val); + $reqProject[] = $prj; + } + + if (count($reqProject) > 0) { + $row = []; + + for ($i=0; $i < count($reqProject); $i++) { + $dataMaxVersionGantt = Activity::select(Activity::raw('MAX(version_gantt_id) as last_version_gantt'))->where("proyek_id", $reqProject[$i]['project_id'])->first(); + $last_version_gantt = $dataMaxVersionGantt->last_version_gantt; + $queryProject = Project::select('id', 'nama', 'mulai_proyek', 'akhir_proyek')->where('id',$reqProject[$i]['project_id'])->first(); + $sum_jumlah_pekerjaan = Activity::where('proyek_id', $reqProject[$i]['project_id'])->where('version_gantt_id', $last_version_gantt)->sum("jumlah_pekerjaan"); + $count_activity = Activity::where('proyek_id', $reqProject[$i]['project_id'])->where('version_gantt_id', $last_version_gantt)->count("id"); + $count_activity_done = Activity::where('proyek_id', $reqProject[$i]['project_id'])->where('persentase_progress', '100')->where('version_gantt_id', $last_version_gantt)->count("id"); + $count_progress_percentage = Activity::where('proyek_id', $reqProject[$i]['project_id'])->whereNull('parent_id')->where('version_gantt_id', $last_version_gantt)->count("persentase_progress"); + $progress_actual = Activity::select('id', 'bobot_planning', 'persentase_progress')->where('proyek_id', $reqProject[$i]['project_id'])->whereNull('parent_id')->where('version_gantt_id', $last_version_gantt)->get(); + $current_progress = 0; + + foreach($progress_actual as $objRow) { + $current_progress += ($objRow->bobot_planning * $objRow->persentase_progress) / 100; + } + if (count($reqProject[$i]['activity_id']) > 0) { + for ($j=0; $j < count($reqProject[$i]['activity_id']); $j++) { + $sum_job_count_report = ReportActivity::whereIn('activity_id', $reqProject[$i]['activity_id'])->sum("job_count_report"); + } + } + if (!isset($queryProject->id)) + return response()->json(['status'=>'failed','message'=>'Project with id='.$reqProject[$i]['project_id'].' is not found!','code'=>400], 400); + + $now = time(); + $akhir_proyek = strtotime($queryProject->akhir_proyek); + $datediff = $akhir_proyek - $now; + + $mulai_proyek = strtotime($queryProject->mulai_proyek); + $total_kontrak = $akhir_proyek - $mulai_proyek; + + $row["id"] = $queryProject->id; + $row["proyek_name"] = $queryProject->nama; + $row["mulai_proyek"] = $queryProject->mulai_proyek; + $row["akhir_proyek"] = $queryProject->akhir_proyek; + $row["total_kontrak"] = round($total_kontrak / (60 * 60 * 24)); + $row["total_task"] = $sum_jumlah_pekerjaan; + $row["task_on_progress"] = $sum_job_count_report; + $row["count_activity"] = $count_activity; + $row["count_activity_done"] = $count_activity_done; + $row["day_left"] = round($datediff / (60 * 60 * 24)); + $row["percentage"] = round($current_progress,3); + $row["count_progress_percentage"] = $count_progress_percentage; + + $dataFinal[] = $row; + } + } + + if(empty($dataFinal)) + return response()->json(['status'=>'failed','message'=>'failed get status proyek, please try again later!','code'=>400], 400); + + return response()->json(['status'=>'success','code'=>200,'data'=>$dataFinal, 'totalRecord'=>count($dataFinal)], 200); + } + + public function curvaS(Request $request) + { + $dataPayload = $request->all(); + $dataMaxVersionGantt = []; + $dataFinal=[]; + + foreach ($dataPayload['project_id'] as $val) { + $dataMaxVersionGantt[] = $this->getMaxVersionGantt($val); + } + + foreach ($dataMaxVersionGantt as $val) { + $data = Activity::select('m_activity.id', 'm_activity.proyek_id', 'm_activity.name', 'm_activity.kode_sortname', 'm_activity.persentase_progress', 'm_activity.persentase_bobot', 'm_activity.bobot_planning', 'm_activity.biaya_actual', 'mp.nama as proyek_name')->join("m_proyek as mp", "m_activity.proyek_id", "=", "mp.id")->where('proyek_id', $val['proyek_id'])->where('version_gantt_id', $val['last_version_gantt'])->whereNull('parent_id')->orderBy('id', 'asc')->get(); + $totalCostPlanning = Activity::where('proyek_id', $val['proyek_id'])->where('version_gantt_id', $val['last_version_gantt'])->whereNull('parent_id')->sum('rencana_biaya'); + + for ($i=0; $i < count($data); $i++) { + $tmpp = $tmpa = $tmpbc = $tmpac = 0; + for ($x=$i; $x >= 0 ; $x--) { + $tmpp += $data[$x]['bobot_planning']; + $tmpa += ($data[$x]['persentase_progress'] * $data[$x]['bobot_planning'])/100; + $tmpbc += ((($data[$x]['persentase_progress'] * $data[$x]['bobot_planning'])/100)*$totalCostPlanning)/100; + $tmpac += $data[$x]['biaya_actual']; + } + + $data[$i]['cal_bobot_p'] = round($tmpp,2); + + if($i > 0 ){ + if($data[$i-1]['cal_bobot_a'] != null){ + if($data[$i-1]['cal_bobot_a'] == round($tmpa,2)){ + $data[$i]['cal_bobot_a'] = null; + }else{ + $data[$i]['cal_bobot_a'] = round($tmpa,2); + } + }else{ + $data[$i]['cal_bobot_a'] = null; + } + if($data[$i-1]['cal_actual_cost'] != null){ + if($data[$i-1]['cal_actual_cost'] == round($tmpac,2)){ + $data[$i]['cal_actual_cost'] = null; + }else{ + $data[$i]['cal_actual_cost'] = round($tmpac,2); + } + }else{ + $data[$i]['cal_actual_cost'] = null; + } + }else{ + $data[$i]['cal_bobot_a'] = round($tmpa,2); + $data[$i]['cal_actual_cost'] = round($tmpac,2); + } + $data[$i]['cal_budget_cost'] = round($tmpbc,2); + } + + $dataFinal[] = array("proyek_id" => $val['proyek_id'], "proyek_name" => isset($data) && count($data) > 0 ? $data[0]['proyek_name'] : "-", "version_gantt_id" => $val['last_version_gantt'], "data" => $data); + } + + if(!$dataFinal) + return response()->json(['status'=>'failed','message'=>'failed get list role, please try again later!','code'=>400], 400); + + return response()->json(['status'=>'success','code'=>200, 'data'=>$dataFinal, 'totalRecord'=>1], 200); + } +} diff --git a/app/Http/Controllers/DivisiController.php b/app/Http/Controllers/DivisiController.php index 864f0eb..aa265d8 100644 --- a/app/Http/Controllers/DivisiController.php +++ b/app/Http/Controllers/DivisiController.php @@ -6,82 +6,81 @@ use Illuminate\Http\Request; use App\Models\Divisi; class DivisiController extends Controller -{ - public function add(Request $request){ - $this->validate($request, [ - 'name' => 'required', - 'description' => 'required' - ]); - $data = $request->all(); - $data['created_by'] = $this->currentName; - - $result = Divisi::create($data); - if($result){ - return response()->json(['status'=>'success','message'=>'Master divisi successfull created','code'=>200]); - }else{ - return response()->json(['status'=>'failed','message'=>'Master divisi failed created','code'=>400]); - } - } - - public function update(Request $request, $id){ - - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - } - $data = Divisi::find($id); - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'Data Master divisi not found!','code'=>400], 400); - die(); - } - - if($result){ - return response()->json(['status'=>'success','message'=>'Master divisi successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'Master divisi failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = Divisi::find($id); - - if($data){ - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data Master divisi not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'Master divisi successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'Master divisi failed deleted!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_divisi'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function list() - { - $data = Divisi::all(); - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list tools request, please try again later!','code'=>400], 400); - } - } +{ + public function add(Request $request){ + $this->validate($request, [ + 'name' => 'required', + 'description' => 'required' + ]); + + $data = $request->all(); + $data['created_by'] = $this->currentName; + + $result = Divisi::create($data); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'Failed to add data','code'=> 500]); + + return response()->json(['status'=>'success','message'=>'Data created!','code'=>200]); + } + + public function update(Request $request, $id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $data = Divisi::find($id); + + if(!$data) + return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); + + $result = $data->update($request->all()); + + if(!$result) + return response()->json(['status'=>'failed','message'=> 'Update failed!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=>'Data added!','code'=>200], 200); + } + + public function delete($id) + { + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $data = Divisi::find($id); + + if(!$data) + return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); + + $delete = $data->delete(); + + + if(!$delete) + return response()->json(['status'=>'failed','message'=> 'Delete failed!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=> 'Data deleted!','code'=> 200], 200); + } + + public function search(Request $request) + { + $payload = $request->all(); + + $dataBuilder = $this->setUpPayload($payload, 'm_divisi'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function list() + { + $data = Divisi::all(); + $countData = $data->count(); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + } } diff --git a/app/Http/Controllers/ProjectController.php b/app/Http/Controllers/ProjectController.php index 437871c..5402bc8 100644 --- a/app/Http/Controllers/ProjectController.php +++ b/app/Http/Controllers/ProjectController.php @@ -14,12 +14,8 @@ use App\Models\ProjectCharter; use App\Models\ProjectApproval; use App\Models\ProjectMileStone; use App\Models\ProjectParticipants; -use App\Models\UserToVersionGantt; -use App\Models\RequestMaterial; use App\Models\ShowHideColumn; -use App\Models\ToolsProject; use App\Models\VersionGantt; -use App\Models\MaterialProject; use App\Models\Image; use App\Models\CommentActivity; use App\Models\Link; @@ -30,214 +26,205 @@ use App\Models\OfficeHours; class ProjectController extends Controller { - public function add(Request $request) - { - $this->validate($request, [ - 'nama' => 'required', - 'mulai_proyek' => 'required', - 'akhir_proyek' => 'required', - 'rencana_biaya' => 'required', - 'type_proyek_id' => 'required' - ]); - - $data = $request->all(); - - $data['created_by'] = $this->currentName; - - $result = Project::create($data); - - if($result){ - $this->createOfficeHours($result->id); - $dataResultInsert = Project::where('nama', $data['nama'])->where('mulai_proyek', $data['mulai_proyek'])->first(); - return response()->json(['status'=>'success','message'=>'add data project successfully!', 'data_result' =>$dataResultInsert, 'code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'add data project failed!','code'=>400], 400); - } - } - - public function edit($id){ - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); - } - - $result = Project::find($id); - - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data project, please try again later!','code'=>400], 400); - } - } - - public function update(Request $request, $id) - { - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - } - - $data = Project::find($id); - - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data project not found!','code'=>400], 400); - die(); - } - - - if($result){ - return response()->json(['status'=>'success','message'=>'data project successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data project failed updated!','code'=>400], 400); - } - } - - private function createOfficeHours($proyek_id) - { - $dataCreate = array( - "proyek_id"=>$proyek_id, - "monday_start"=> "08:00:00", - "monday_end"=> "16:00:00", - "tuesday_start"=> "08:00:00", - "tuesday_end"=> "16:00:00", - "wednesday_start"=> "08:00:00", - "wednesday_end"=> "16:00:00", - "thursday_start"=> "08:00:00", - "thursday_end"=> "16:00:00", - "friday_start"=> "08:00:00", - "friday_end"=> "16:00:00", - "saturday_start"=> "08:00:00", - "saturday_end"=> "16:00:00", - "sunday_start"=> "08:00:00", - "sunday_end"=> "16:00:00", - "created_by"=> $this->currentName - ); - - OfficeHours::create($dataCreate); - - return true; - } - - public function delete($id) - { - $data = Project::find($id); - - if($data){ - $this->deleteRelative($id); - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data project not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'data project successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data project failed deleted!','code'=>400], 400); - } - } - - private function deleteRelative($project_id) - { - UserToProyek::where('proyek_id', $project_id)->delete(); - UserToActivity::where('proyek_id', $project_id)->delete(); - AssignMaterial::where('proyek_id', $project_id)->delete(); - ProjectCharter::where('proyek_id', $project_id)->delete(); - ProjectApproval::where('proyek_id', $project_id)->delete(); - ProjectMileStone::where('proyek_id', $project_id)->delete(); - ProjectParticipants::where('proyek_id', $project_id)->delete(); - $this->deleteVersionGantt($project_id); - $this->deleteDokumenProject($project_id); - } - - private function deleteVersionGantt($project_id) - { - $dataVg = VersionGantt::where("proyek_id", $project_id)->pluck("id"); - $vhIds = $dataVg->all(); - $activity = Activity::whereIn("version_gantt_id", $vhIds)->pluck('id'); - $activityIds = $activity->all(); - $dataRa = ReportActivity::whereIn("activity_id", $activityIds)->get(); - foreach ($dataRa as $ra) { - $images = Image::where("ref_id", $ra->id)->where("category", "report_activity")->get(); - foreach ($images as $image) { - if(file_exists($this->pathImage.$image->image)){ - unlink($this->pathImage.$image->image); - } - } - Image::where("ref_id", $ra->id)->where("category", "report_activity")->delete(); - } - $dataAd = ActivityDokumen::whereIn("activity_id", $activityIds)->get(); - foreach ($dataAd as $ad) { - if(file_exists($this->pathActivityDocument.$ad->file)){ - unlink($this->pathActivityDocument.$ad->file); - } - } - ActivityDokumen::whereIn("activity_id", $activityIds)->delete(); - CommentActivity::whereIn("activity_id", $activityIds)->delete(); - Holiday::where("proyek_id", $project_id)->delete(); - VersionGantt::where("proyek_id", $project_id)->delete(); - Link::whereIn("version_gantt_id", $vhIds)->delete(); - ShowHideColumn::whereIn("version_gantt_id", $vhIds)->delete(); - Activity::whereIn("version_gantt_id", $vhIds)->delete(); - ReportActivity::whereIn("activity_id", $activityIds)->delete(); - } - - private function deleteDokumenProject($project_id) - { - $dataDokumen = DokumenProject::where("type_dokumen", "project-document-out-folder")->where('ref_id', $project_id)->get(); - - foreach ($dataDokumen as $dokumen) { - if(file_exists($this->pathDocument.$dokumen->file)){ - unlink($this->pathDocument.$dokumen->file); - } - } - DokumenProject::where("type_dokumen", "project-document-out-folder")->where('ref_id', $project_id)->delete(); - - $dataFolder = FolderDocumentProyek::where('proyek_id', $project_id)->pluck("id"); - $ref_ids = $dataFolder->all(); - $dataDokumen = DokumenProject::where("type_dokumen", "project-document-in-folder")->whereIn('ref_id', $ref_ids)->get(); - foreach ($dataDokumen as $dokumen) { - if(file_exists($this->pathDocument.$dokumen->file)){ - unlink($this->pathDocument.$dokumen->file); - } - } - - DokumenProject::where("type_dokumen", "project-document-in-folder")->whereIn('ref_id', $ref_ids)->delete(); - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_proyek'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function list() - { - $data = Project::all(); - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list project, please try again later!','code'=>400], 400); - } - } - - public function getListProjectTask($id){ - $data = UserToActivity::select("assign_hr_to_activity.user_id as user_id","m_proyek.*")->where("assign_hr_to_activity.user_id", $id)->join('m_proyek', 'assign_hr_to_activity.proyek_id', '=', 'm_proyek.id') - ->groupBy("m_proyek.proyek_id")->get(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list project, please try again later!','code'=>400], 400); - } - } + + public function add(Request $request) + { + $this->validate($request, [ + 'nama' => 'required', + 'mulai_proyek' => 'required', + 'akhir_proyek' => 'required', + 'rencana_biaya' => 'required', + 'type_proyek_id' => 'required' + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + + $result = Project::create($data); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=> 500], 500); + + $this->createOfficeHours($result->id); + $dataResultInsert = Project::where('nama', $data['nama'])->where('mulai_proyek', $data['mulai_proyek'])->first(); + + return response()->json(['status'=>'success','message'=>'Data added!', 'data_result' =>$dataResultInsert, 'code'=> 200], 200); + } + + public function edit($id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $result = Project::find($id); + + if(!$result) + return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); + + return response()->json(['status'=>'success','code'=> 200,'data'=>$result], 200); + } + + public function update(Request $request, $id) + { + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $data = Project::find($id); + + if(!$data) + return response()->json(['status'=>'failed','message'=> 'Data not found!','code'=> 404], 404); + + $result = $data->update($request->all()); + + if(!$result) + return response()->json(['status'=>'failed','message'=> 'Failed to update!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=>'Data updated!','code' => 200], 200); + } + + private function createOfficeHours($proyek_id) + { + $dataCreate = array( + "proyek_id"=>$proyek_id, + "monday_start"=> "08:00:00", + "monday_end"=> "16:00:00", + "tuesday_start"=> "08:00:00", + "tuesday_end"=> "16:00:00", + "wednesday_start"=> "08:00:00", + "wednesday_end"=> "16:00:00", + "thursday_start"=> "08:00:00", + "thursday_end"=> "16:00:00", + "friday_start"=> "08:00:00", + "friday_end"=> "16:00:00", + "saturday_start"=> "08:00:00", + "saturday_end"=> "16:00:00", + "sunday_start"=> "08:00:00", + "sunday_end"=> "16:00:00", + "created_by"=> $this->currentName + ); + + OfficeHours::create($dataCreate); + + return true; + } + + public function delete($id) + { + $data = Project::find($id); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + + $this->deleteRelative($id); + + if(!$data->delete()) + return response()->json(['status'=>'failed','message'=>'Delete failed!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=>'Data deleted!','code'=>200], 200); + } + + private function deleteRelative($project_id) + { + UserToProyek::where('proyek_id', $project_id)->delete(); + UserToActivity::where('proyek_id', $project_id)->delete(); + AssignMaterial::where('proyek_id', $project_id)->delete(); + ProjectCharter::where('proyek_id', $project_id)->delete(); + ProjectApproval::where('proyek_id', $project_id)->delete(); + ProjectMileStone::where('proyek_id', $project_id)->delete(); + ProjectParticipants::where('proyek_id', $project_id)->delete(); + $this->deleteVersionGantt($project_id); + $this->deleteDokumenProject($project_id); + } + + private function deleteVersionGantt($project_id) + { + $dataVg = VersionGantt::where("proyek_id", $project_id)->pluck("id"); + $vhIds = $dataVg->all(); + $activity = Activity::whereIn("version_gantt_id", $vhIds)->pluck('id'); + $activityIds = $activity->all(); + $dataRa = ReportActivity::whereIn("activity_id", $activityIds)->get(); + foreach ($dataRa as $ra) { + $images = Image::where("ref_id", $ra->id)->where("category", "report_activity")->get(); + foreach ($images as $image) { + if(file_exists($this->pathImage.$image->image)){ + unlink($this->pathImage.$image->image); + } + } + Image::where("ref_id", $ra->id)->where("category", "report_activity")->delete(); + } + $dataAd = ActivityDokumen::whereIn("activity_id", $activityIds)->get(); + foreach ($dataAd as $ad) { + if(file_exists($this->pathActivityDocument.$ad->file)){ + unlink($this->pathActivityDocument.$ad->file); + } + } + ActivityDokumen::whereIn("activity_id", $activityIds)->delete(); + CommentActivity::whereIn("activity_id", $activityIds)->delete(); + Holiday::where("proyek_id", $project_id)->delete(); + VersionGantt::where("proyek_id", $project_id)->delete(); + Link::whereIn("version_gantt_id", $vhIds)->delete(); + ShowHideColumn::whereIn("version_gantt_id", $vhIds)->delete(); + Activity::whereIn("version_gantt_id", $vhIds)->delete(); + ReportActivity::whereIn("activity_id", $activityIds)->delete(); + } + + private function deleteDokumenProject($project_id) + { + $dataDokumen = DokumenProject::where("type_dokumen", "project-document-out-folder")->where('ref_id', $project_id)->get(); + + foreach ($dataDokumen as $dokumen) { + if(file_exists($this->pathDocument.$dokumen->file)){ + unlink($this->pathDocument.$dokumen->file); + } + } + DokumenProject::where("type_dokumen", "project-document-out-folder")->where('ref_id', $project_id)->delete(); + + $dataFolder = FolderDocumentProyek::where('proyek_id', $project_id)->pluck("id"); + $ref_ids = $dataFolder->all(); + $dataDokumen = DokumenProject::where("type_dokumen", "project-document-in-folder")->whereIn('ref_id', $ref_ids)->get(); + foreach ($dataDokumen as $dokumen) { + if(file_exists($this->pathDocument.$dokumen->file)){ + unlink($this->pathDocument.$dokumen->file); + } + } + + DokumenProject::where("type_dokumen", "project-document-in-folder")->whereIn('ref_id', $ref_ids)->delete(); + } + + public function search(Request $request) + { + $payload = $request->all(); + + $dataBuilder = $this->setUpPayload($payload, 'm_proyek'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function list() + { + $data = Project::all(); + $countData = $data->count(); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + } + + public function getListProjectTask($id){ + $data = UserToActivity::select("assign_hr_to_activity.user_id as user_id","m_proyek.*") + ->where("assign_hr_to_activity.user_id", $id) + ->join('m_proyek', 'assign_hr_to_activity.proyek_id', '=', 'm_proyek.id') + ->groupBy("m_proyek.proyek_id") + ->get(); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + + return response()->json(['status'=>'success','code'=>200,'data'=>$data], 200); + } } diff --git a/app/Http/Controllers/ProjectDokumenController.php b/app/Http/Controllers/ProjectDokumenController.php index 9b1ab7c..466f09b 100644 --- a/app/Http/Controllers/ProjectDokumenController.php +++ b/app/Http/Controllers/ProjectDokumenController.php @@ -7,93 +7,94 @@ use App\Models\DokumenProject; class ProjectDokumenController extends Controller { - public function dokumenByProyekId($id){ - if($id && $id!="" && (int)$id > 0){ - $dataDokumen = DokumenProject::where("ref_id", $id)->get(); - - return response()->json(['status'=>'success','data'=>$dataDokumen,'code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'project id is required!','code'=>400], 400); - } - } - - public function delete($id) - { - if($id && $id!="" && (int)$id > 0){ - $dokumen = DokumenProject::find($id); - if($dokumen){ - if(file_exists($this->pathDocument.$dokumen->file)){ - unlink($this->pathDocument.$dokumen->file); - } - $dokumen->delete(); - return response()->json(['status'=>'success','message'=>'Dokumen deleted successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'Dokumen not found!','code'=>400], 400); - } - }else{ - return response()->json(['status'=>'failed','message'=>'Id is required!','code'=>400], 400); - } - } - - public function uploadProjectDokumen(Request $request) - { - if($request->hasFile('dokumen')){ - $dokumen = $request->file('dokumen'); - $ref_id = $request->ref_id; - $extension = $dokumen->extension(); - $name = $dokumen->getClientOriginalName(); - - $result = $dokumen->move($this->pathDocument, $name); - if($result){ - $data = [ - 'ref_id' => (int)$ref_id, - 'file' => $name, - 'type_dokumen' => isset($request->type_dokumen) ? $request->type_dokumen : 'project-document' // project-document-in-folder / project-document-out-folder - ]; - - $result = DokumenProject::create($data); - - if($result){ - return response()->json(['status'=>'success','message'=>'file upload is successfully!','code'=>200], 200); - }else{ - unlink($this->pathDocument.$name); - return response()->json(['status'=>'failed','message'=>'file upload is failed!','code'=>400], 400); - } - - }else{ - return response()->json(['status'=>'failed','message'=>'file upload is failed!','code'=>400], 400); - } - }else{ - return response()->json(['status'=>'failed','message'=>'file is required!','code'=>400], 400); - } - } - - public function searchDocProject(Request $request){ - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'document_project'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function downloadDokumen($id) - { - if($id && $id!="" && (int)$id > 0){ - $dokumen = DokumenProject::find($id); - if($dokumen){ - if(file_exists($this->pathDocument.$dokumen->file)){ - $pathToFile = $this->pathDocument.$dokumen->file; - return response()->download($pathToFile); - }else{ - return response()->json(['status'=>'failed','message'=>'Dokumen not found!','code'=>400], 400); - } - }else{ - return response()->json(['status'=>'failed','message'=>'Dokumen not found!','code'=>400], 400); - } - }else{ - return response()->json(['status'=>'failed','message'=>'Id is required!','code'=>400], 400); - } - } + public function dokumenByProyekId($id){ + if(empty($id) || !is_int((int)$id)) { + return response()->json(['status'=>'failed','message'=>'project id is required!','code'=>400], 400); + } + + $document = DokumenProject::where("ref_id", $id)->get(); + + if(count($document) == 0) + return response()->json(['status'=>'','message'=>'Data not found!' ,'code'=>404], 404); + + return response()->json(['status'=>'success','data'=> $document ,'code'=>200], 200); + } + + public function delete($id) + { + if(empty($id) || !is_int((int)$id)) { + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + } + + $document = DokumenProject::find($id); + if(!$document){ + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>400], 400); + } + + if(file_exists($this->pathDocument.$document->file)){ + unlink($this->pathDocument.$document->file); + } + + $document->delete(); + + return response()->json(['status'=>'success','message'=>'Data deleted!','code'=>200], 200); + } + + public function uploadProjectDokumen(Request $request) + { + if($request->hasFile('dokumen')){ + $document = $request->file('dokumen'); + $ref_id = $request->ref_id; + $name = $document->getClientOriginalName(); + + $result = $document->move($this->pathDocument, $name); + if($result){ + $data = [ + 'ref_id' => (int)$ref_id, + 'file' => $name, + 'type_dokumen' => isset($request->type_dokumen) ? $request->type_dokumen : 'project-document' + ]; + + $result = DokumenProject::create($data); + + if(!$result){ + unlink($this->pathDocument.$name); + return response()->json(['status'=>'failed','message'=>'Upload failed!','code'=> 500], 500); + } + return response()->json(['status'=>'success','message'=>'Upload successful!','code'=>200], 200); + + } + return response()->json(['status'=>'failed','message'=>'Upload failed!','code'=> 500], 500); + } + return response()->json(['status'=>'failed','message'=>'File is required!','code'=>400], 400); + } + + public function searchDocProject(Request $request){ + $payload = $request->all(); + + $dataBuilder = $this->setUpPayload($payload, 'document_project'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function downloadDokumen($id) + { + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'Id is required!','code'=>400], 400); + + $document = DokumenProject::find($id); + + if(!$document) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + + if(!file_exists($this->pathDocument.$document->file)) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + + $pathToFile = $this->pathDocument.$document->file; + return response()->download($pathToFile); + } } diff --git a/app/Http/Controllers/RoleController.php b/app/Http/Controllers/RoleController.php index a1787a8..b420107 100644 --- a/app/Http/Controllers/RoleController.php +++ b/app/Http/Controllers/RoleController.php @@ -4,105 +4,98 @@ namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Role; + class RoleController extends Controller { - public function add(Request $request) - { - $this->validate($request, [ - 'name' => 'required', - 'description' => 'required' - ]); - - $data = $request->all(); - - $data['created_by'] = $this->currentName; - - $result = Role::create($data); - - if($result){ - return response()->json(['status'=>'success','message'=>'add data role successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'add data role failed!','code'=>400], 400); - } - } - - public function edit($id){ - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); - } - - $result = Role::find($id); - - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data role, please try again later!','code'=>400], 400); - } - } - - public function update(Request $request, $id) - { - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - } - - $data = Role::find($id); - - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data role not found!','code'=>400], 400); - die(); - } - - - if($result){ - return response()->json(['status'=>'success','message'=>'data role successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data role failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = Role::find($id); - - if($data){ - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data role not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'data role successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'data role failed deleted!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_roles'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function list() - { - $data = Role::all(); - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list role, please try again later!','code'=>400], 400); - } - } + + public function add(Request $request) + { + $this->validate($request, [ + 'name' => 'required', + 'description' => 'required' + ]); + + $data = $request->all(); + + $data['created_by'] = $this->currentName; + + $result = Role::create($data); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=>500], 500); + + return response()->json(['status'=>'success','message'=>'Data added!','code'=>200], 200); + } + + public function edit( $id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $result = Role::find($id); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>404], 404); + + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + } + + public function update(Request $request, $id) + { + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $data = Role::find($id); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>404], 404); + + $result = $data->update($request->all()); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'Failed to update the data!','code'=>500], 500); + + return response()->json(['status'=>'success','message'=>'Data updated!','code'=>200], 200); + } + + public function delete($id) + { + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $data = Role::find($id); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>404], 404); + + $delete = $data->delete(); + + if(!$delete) + return response()->json(['status'=>'failed','message'=>'Failed to delete!','code'=>500], 500); + + return response()->json(['status'=>'success','message'=>'Data deleted!','code'=>200], 200); + } + + public function search(Request $request) + { + $payload = $request->all(); + + $dataBuilder = $this->setUpPayload($payload, 'm_roles'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function list() + { + $data = Role::all(); + $countData = $data->count(); + + if(!$data) + return response()->json(['status'=>'failed','message'=>'failed get list role, please try again later!','code'=>400], 400); + + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + } } From dbc542131885199753bddbf720220bf1853a1483 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Sun, 10 Jul 2022 02:42:58 +0700 Subject: [PATCH 06/19] implement remember me --- app/Http/Controllers/AuthController.php | 129 ++++++++++++------------ 1 file changed, 67 insertions(+), 62 deletions(-) diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index f50d5c2..8dabcfd 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -10,66 +10,71 @@ use App\Models\Role; class AuthController extends Controller { - public function __construct() - { - $this->middleware('auth:api', ['except' => ['login']]); - } - - public function login(Request $request) - { - $username = $request->username; - $password = $request->password; - $is_mobile = $request->is_mobile; - - if(empty($username) || empty($password)){ - return response()->json(['status'=>'error','message'=>'You must fill all the fields'], 400); - } - - $user = User::where('username', $username)->where('password', md5($password))->first(); - - if($is_mobile){ - $fcm_token = $request->fcm_token; - - if(!$fcm_token || $fcm_token==""){ - return response()->json(['status'=>'error','message'=>'FCM Token is required'], 400); - die(); - } - - $dataUpdateFcm = array( - "fcm_token"=>$fcm_token - ); - - $hr = User::find($user->id); - - if($hr){ - $hr->update($dataUpdateFcm); - } - } - - $dataRole = Role::find($user->role_id); - - if($dataRole){ - $user->role = $dataRole; - } - - - if (! $token =Auth::login($user)) { - return response()->json(['error' => 'Unauthorized'], 401); - } - - return $this->respondWithToken($token, $user); - } - - protected function respondWithToken($token, $user) - { - return response()->json([ - 'code' => 200, - 'data' => array( - 'data_user' => $user, - 'access_token' => $token, - 'token_type' => 'bearer', - 'expires_in' => auth()->factory()->getTTL() * 360 - ), - ]); - } + public function __construct() + { + $this->middleware('auth:api', ['except' => ['login']]); + } + + public function login(Request $request) + { + $username = $request->username; + $password = $request->password; + $remember = $request->remember; + $is_mobile = $request->is_mobile; + + if(empty($username) || empty($password)){ + return response()->json(['status'=>'error','message'=>'You must fill all the fields'], 400); + } + + $user = User::where('username', $username)->where('password', md5($password))->first(); + + if($is_mobile){ + $fcm_token = $request->fcm_token; + + if(!$fcm_token || $fcm_token==""){ + return response()->json(['status'=>'error','message'=>'FCM Token is required'], 400); + die(); + } + + $dataUpdateFcm = array( + "fcm_token"=>$fcm_token + ); + + $hr = User::find($user->id); + + if($hr){ + $hr->update($dataUpdateFcm); + } + } + + + $dataRole = Role::find($user->role_id); + + if($dataRole){ + $user->role = $dataRole; + } + + + if (! $token =Auth::login($user)) { + return response()->json(['error' => 'Unauthorized'], 401); + } + + return $this->respondWithToken($token, $user, $remember); + } + + protected function respondWithToken($token, $user, $remember) + { + $ttl = 60; + if($remember) + $ttl = 10080; + return response()->json([ + 'code' => 200, + 'data' => array( + 'data_user' => $user, + 'access_token' => $token, + 'token_type' => 'bearer', + 'expires_in' => auth()->factory()->getTTL() * $ttl, + ), + ]); + } } From bdba1a23478419b3254dde8bb754fa14da178b8c Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Sun, 10 Jul 2022 22:03:26 +0700 Subject: [PATCH 07/19] remove unused codes --- app/Http/Controllers/ActivityController.php | 436 ++++---------------- 1 file changed, 73 insertions(+), 363 deletions(-) diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index 84e8788..da5c268 100644 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -11,7 +11,6 @@ use App\Models\UserToActivity; use App\Models\CommentActivity; use App\Models\AssignMaterial; use App\Models\AssignTools; -use App\Models\OfficeHours; use App\Models\VersionGantt; use App\Models\Holiday; use App\Models\ReportActivity; @@ -33,7 +32,7 @@ class ActivityController extends Controller } return response()->json(['status'=>'success','data'=>$dataGantt,'code'=>200], 200); - } + } private function getDataActivity($id) { @@ -52,7 +51,7 @@ class ActivityController extends Controller }else{ $data = Activity::where('version_gantt_id', $id)->whereNull('parent_id')->orderBy('id', 'asc')->get(); } - + foreach($data as $objRow){ $objRow->text = $objRow->name; if($objRow->parent_id){ @@ -153,14 +152,14 @@ class ActivityController extends Controller $dataPlan = AssignMaterial::where('activity_id', $id)->get(); $tmpPercentage1 = []; if(!$dataPlan->isEmpty()){ - foreach ($dataPlan as $value) { + foreach ($dataPlan as $value) { $qty_plan = $value->qty_planning; $status_activity = $value->status_activity; $getDataVolActual = ReportActivityMaterial::where('assign_material_id', '=', $value->id)->sum("qty"); $percentage1 = ($getDataVolActual * 100) / $qty_plan; if($status_activity == 'done'){ $tmpPercentage1[] = 100; - } + } else{ $tmpPercentage1[] = $percentage1 >= 100 ? 90 : $percentage1; } @@ -169,7 +168,7 @@ class ActivityController extends Controller $totalPercentage = array_sum($tmpPercentage1) > 0 ? array_sum($tmpPercentage1) / count($tmpPercentage1) : 0; }else{ - + $totalPercentage = 0; } return $totalPercentage; @@ -343,7 +342,7 @@ class ActivityController extends Controller } if($data){ $upactual = false; - $result = $data->update($dataUpdate); + $result = $data->update($dataUpdate); if($result){ if($parent && (int)$parent > 0){ $this->updateCostPlanning($parent); @@ -376,8 +375,8 @@ class ActivityController extends Controller return response()->json(['status'=>'failed','message'=>'data activity not found!','code'=>400], 400); die(); } - - + + if($result){ return response()->json(['status'=>'success','message'=>'data activity successfully updated!','code'=>200], 200); }else{ @@ -427,7 +426,7 @@ class ActivityController extends Controller return response()->json(['status'=>'failed', 'action'=>'error','message'=>'data activity not found!','code'=>400], 400); die(); } - + if($delete){ return response()->json(['status'=>'success', "action"=>"deleted",'message'=>'data activity successfully deleted!','code'=>200], 200); @@ -507,7 +506,7 @@ class ActivityController extends Controller { $biayaActual = Activity::where("parent_id", $id)->sum("biaya_actual"); $dataActivity = Activity::find($id); - + $dataUpdate = array( "biaya_actual" => $biayaActual, "updated_by" => $this->currentName @@ -534,136 +533,21 @@ class ActivityController extends Controller public function calculateAllCost($activity_id, $proyek_id) { - $humanCostPlanning = $this->calculateHuman($activity_id, $proyek_id); $materialCostPlanning = 0; $toolsCostPlanning = 0; - $allCost = $humanCostPlanning + $materialCostPlanning + $toolsCostPlanning; + $allCost = $materialCostPlanning + $toolsCostPlanning; return $allCost; } - private function calculateHuman($activity_id, $proyek_id) - { - $dataHuman = UserToActivity::select("ahp.standart_rate as standart_rate","ahp.max_used as max_used", "ahp.cost_per_used as cost_per_used", "ahp.uom_standart_rate as uom_standart_rate")->leftJoin("assign_hr_to_proyek as ahp", "assign_hr_to_activity.user_id", "=", "ahp.user_id") - ->where("assign_hr_to_activity.activity_id", $activity_id)->where("assign_hr_to_activity.proyek_id", $proyek_id) - ->where("ahp.proyek_id", $proyek_id) - ->get(); - - $totalCost = 0; - foreach ($dataHuman as $human) { - $uom = $human->uom_standart_rate; - $totalCost += $this->calculateHumanCost($human, $activity_id); - } - - return $totalCost; - } - - private function calculateHumanCost($human, $activity_id) - { - $activity = Activity::find($activity_id); - $duration = $activity->duration; - $standarRate = $human->standart_rate; - $maxUsed = $human->max_used/100; - $totalCost = ($standarRate*$duration)*$maxUsed; - return $totalCost; - } - - private function calculateHumanDay($human, $activity_id) - { - $activity = Activity::find($activity_id); - $duration = $activity->duration; - $standarRate = $human->standart_rate; - $maxUsed = $human->max_used/100; - $totalCost = ($standarRate*$duration)*$maxUsed; - return $totalCost; - } - - private function calculateHumanHours($human, $activity_id, $proyek_id) - { - $hours = OfficeHours::where("proyek_id", $proyek_id)->first(); - $activity = Activity::find($activity_id); - $ganttId = $activity->version_gantt_id; - $verGantt = VersionGantt::find($ganttId); - $holiday = Holiday::where("version_gantt_id", $ganttId)->where("proyek_id", $proyek_id)->pluck("date"); - $dateHoliday = $holiday->all(); - $configOff = $verGantt->config_dayoff; - if($configOff && $configOff!= ""){ - $dayOff = explode(",", $verGantt->config_dayoff); - $dayOff = array_map( - function($value) { return (int)$value; }, - $dayOff - ); - }else{ - $dayOff = []; - } - $begin = new \DateTime($activity->start_date); - $end = new \DateTime($activity->end_date); - $end = $end->modify( '+1 day' ); - $interval = \DateInterval::createFromDateString('1 day'); - $period = new \DatePeriod($begin, $interval, $end); - $totalCost = 0; - foreach ($period as $dt) { - $weekDay = $dt->format("w"); - $currentDay = $dt->format("Y-m-d"); - if(!in_array($weekDay, $dayOff) && !in_array($currentDay, $dateHoliday)) - { - $totalHours = $this->getHourInDay($hours, $weekDay); - $standarRate = $human->standart_rate; - $maxUsed = $human->max_used/100; - $totalCost += ($standarRate*$totalHours)*$maxUsed; - } - } - return $totalCost; - } - - private function getHourInDay($hours, $day) - { - $totalHours = 0; - switch ($day) { - case 1: - $totalHours = ceil(abs(((strtotime($hours->monday_end)-strtotime($hours->monday_start))/60)/60)); - break; - case 2: - $totalHours = ceil(abs(((strtotime($hours->tuesday_end)-strtotime($hours->tuesday_start))/60)/60)); - break; - case 3: - $totalHours = ceil(abs(((strtotime($hours->wednesday_end)-strtotime($hours->wednesday_start))/60)/60)); - break; - case 4: - $totalHours = ceil(abs(((strtotime($hours->thursday_end)-strtotime($hours->thursday_start))/60)/60)); - break; - case 5: - $totalHours = ceil(abs(((strtotime($hours->friday_end)-strtotime($hours->friday_start))/60)/60)); - break; - case 6: - $totalHours = ceil(abs(((strtotime($hours->saturday_end)-strtotime($hours->saturday_start))/60)/60)); - break; - default: - $totalHours = ceil(abs(((strtotime($hours->sunday_end)-strtotime($hours->sunday_start))/60)/60)); - break; - } - return $totalHours; - } - - private function calculateMaterial($activity_id, $proyek_id) - { - $totalCost = AssignMaterial::selectRaw("ISNULL(qty_planning,0)*ISNULL(budget,0) as totalCost")->where("proyek_id", $proyek_id)->where("activity_id", $activity_id)->sum("totalCost"); - return $totalCost; - } - - private function calculateTools($activity_id, $proyek_id) - { - - } - public function getPercentagePerDay(Request $request) - { + { $dataPayload = $request->all(); $allGantt = []; foreach ($dataPayload['project_id'] as $val) { $allGantt[] = $this->getMaxVersionGantt($val); } - + $dataFinal=[]; foreach ($allGantt as $val) { $dataProject = Project::find($val['proyek_id']); @@ -699,7 +583,7 @@ class ActivityController extends Controller $minDate = Activity::whereNull('parent_id')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->min("start_date"); $maxDate = Activity::whereNull('parent_id')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->max("end_date"); } - + $begin = new \DateTime($minDate); $end = new \DateTime($maxDate); $end = $end->modify( '+1 day' ); @@ -712,14 +596,14 @@ class ActivityController extends Controller }else{ $totalRencanaBudget = Activity::select(DB::raw('sum(cast(rencana_biaya as integer))'))->whereNull('parent_id')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->first(); } - + $totalRencanaBudget = $totalRencanaBudget->sum; $currentPercentage = 0; $dataDate = []; $dataPercen = []; foreach ($period as $dt) { $weekDay = $dt->format("w"); - $currentDate = $dt->format("Y-m-d"); + $currentDate = $dt->format("Y-m-d"); if(!in_array($weekDay, $dayOff) && !in_array($currentDate, $dateHoliday)) { $totalPercentage = 0; @@ -730,7 +614,7 @@ class ActivityController extends Controller }else{ $dataActivity = Activity::whereRaw("'".$currentDate."' BETWEEN DATE(m_activity.start_date) AND DATE(m_activity.end_date)")->whereNull('parent_id')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->get(); } - + foreach ($dataActivity as $activity) { $duration = $activity->duration; if($totalRencanaBudget > 0 && $duration > 0){ @@ -764,12 +648,12 @@ class ActivityController extends Controller public function getCalculateCurvaS(Request $request) // for adw (plan & actual == date) - { + { $dataPayload = $request->all(); $allGantt = []; if(isset($dataPayload['gannt_id'])){ $allGantt = $dataPayload['gannt_id']; - }else{ + }else{ foreach ($dataPayload['project_id'] as $val) { $allGantt[] = $this->getMaxVersionGantt($val); } @@ -790,7 +674,7 @@ class ActivityController extends Controller ->where("ama.proyek_id", $keyGantt['proyek_id']) ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') ->where('a.version_gantt_id', '=', $keyGantt['last_gantt_id']) - ->min("plan_date"); + ->min("plan_date"); $maxDate = DB::table('assign_material_to_activity as ama') ->where("ama.proyek_id", $keyGantt['proyek_id']) @@ -804,7 +688,7 @@ class ActivityController extends Controller $interval = \DateInterval::createFromDateString('1 day'); $period = new \DatePeriod($begin, $interval, $end); $arr_ActualM = []; - $tempDate = []; + $tempDate = []; $tempPercentage = []; $tempTtlPercentPlan=0; $tempTtlPercentActual=0; @@ -814,12 +698,12 @@ class ActivityController extends Controller $currentProgressActivity = 0; $currentBCWP = 0; $budgetControlBCWP = 0; - - foreach ($period as $dt) { + + foreach ($period as $dt) { $dataPlanM = DB::table('assign_material_to_activity as ama') ->select('ama.activity_id', 'ama.qty_planning', 'ama.plan_date', 'ama.start_activity', 'a.bobot_planning', 'a.biaya_actual', 'a.duration', 'a.persentase_progress') ->join('m_activity as a', 'a.id', '=', 'ama.activity_id') - ->where('ama.proyek_id', '=', $keyGantt['proyek_id']) + ->where('ama.proyek_id', '=', $keyGantt['proyek_id']) ->where('a.version_gantt_id', '=', $keyGantt['last_gantt_id']) ->whereDate('ama.plan_date', $dt->format("Y-m-d")) ->get(); @@ -833,7 +717,7 @@ class ActivityController extends Controller $dataTempPlan = []; $x = 0; $sumPercentagePlan=0; - $totalACWP = isset($totalACWP) ? $totalACWP : 0; + $totalACWP = isset($totalACWP) ? $totalACWP : 0; $totalBCWP = isset($totalBCWP) ? $totalBCWP : 0; foreach ($dataPlanM as $keyPlanM) { @@ -845,13 +729,13 @@ class ActivityController extends Controller $dataTempPlan [$x]['activity_id'] = $keyPlanM->activity_id; $dataTempPlan [$x]['qty_plan'] = $keyPlanM->qty_planning; $dataTempPlan [$x]['plan_date'] = $keyPlanM->plan_date; - $dataTempPlan [$x]['start_activity'] = $keyPlanM->start_activity; - $dataTempPlan [$x]['bobot_planning'] = $keyPlanM->bobot_planning; + $dataTempPlan [$x]['start_activity'] = $keyPlanM->start_activity; + $dataTempPlan [$x]['bobot_planning'] = $keyPlanM->bobot_planning; $dataTempPlan [$x]['ttl_plan'] = $sumVolPlan->ttl_qty_plan; $dataTempPlan [$x]['biaya_actual'] = $keyPlanM->biaya_actual; $dataTempPlan [$x]['duration'] = $keyPlanM->duration; - $dataTempPlan [$x]['persentase_progress'] = $keyPlanM->persentase_progress; - $dataTempPlan [$x]['percentage'] = ($keyPlanM->qty_planning/$sumVolPlan->ttl_qty_plan)*$keyPlanM->bobot_planning; + $dataTempPlan [$x]['persentase_progress'] = $keyPlanM->persentase_progress; + $dataTempPlan [$x]['percentage'] = ($keyPlanM->qty_planning/$sumVolPlan->ttl_qty_plan)*$keyPlanM->bobot_planning; $sumPercentagePlan+=($keyPlanM->qty_planning/$sumVolPlan->ttl_qty_plan)*$keyPlanM->bobot_planning; $totalBCWP += (((($keyPlanM->persentase_progress*$keyPlanM->bobot_planning)/100)/$keyPlanM->duration)* $totalRencanaBudget)/100; $dataTempPlan [$x]['totalBCWP'] = $totalBCWP; @@ -869,34 +753,34 @@ class ActivityController extends Controller ->first(); $dataTempReport [$w]['activity_id'] = $keyActualM->activity_id; $dataTempReport [$w]['qty'] = $keyActualM->qty; - $dataTempReport [$w]['report_date'] = $keyActualM->report_date; + $dataTempReport [$w]['report_date'] = $keyActualM->report_date; $dataTempReport [$w]['bobot_planning'] = $keyActualM->bobot_planning; - $dataTempReport [$w]['ttl_plan'] = $sumVolActual->ttl_qty_plan; + $dataTempReport [$w]['ttl_plan'] = $sumVolActual->ttl_qty_plan; $dataTempReport [$w]['biaya_actual'] = $keyActualM->biaya_actual; $dataTempReport [$w]['duration'] = $keyActualM->duration; - $dataTempReport [$w]['persentase_progress'] = $keyActualM->persentase_progress; + $dataTempReport [$w]['persentase_progress'] = $keyActualM->persentase_progress; $dataTempReport [$w]['percentage'] = ($keyActualM->qty/$sumVolActual->ttl_qty_plan)*$keyActualM->bobot_planning; - $sumPercentageActual+=($keyActualM->qty/$sumVolActual->ttl_qty_plan)*$keyActualM->bobot_planning; - $totalACWP += $keyActualM->biaya_actual/$keyActualM->duration; - $dataTempReport [$w]['totalacwp'] = $totalACWP; + $sumPercentageActual+=($keyActualM->qty/$sumVolActual->ttl_qty_plan)*$keyActualM->bobot_planning; + $totalACWP += $keyActualM->biaya_actual/$keyActualM->duration; + $dataTempReport [$w]['totalacwp'] = $totalACWP; $w++; - } - + } + $arr_ActualM[] = array( 'date'=>$dt->format("Y-m-d"), 'percentPlan'=>$sumPercentagePlan, 'percentActual'=>$sumPercentageActual, 'plan'=>$dataTempPlan, - 'actual'=>$dataTempReport, - ); - if(isset($dataPayload['period']) && $dataPayload['period'] == 'week'){ - if($dt->format("w")==1){ + 'actual'=>$dataTempReport, + ); + if(isset($dataPayload['period']) && $dataPayload['period'] == 'week'){ + if($dt->format("w")==1){ if($totalACWP > 0 ){ $budgetControlACWP = $currentACWP + $totalACWP; - } + } if($totalBCWP > 0 ){ $budgetControlBCWP = $currentBCWP + $totalBCWP; - } + } $tempTtlPercentPlan+= $sumPercentagePlan; $tempTtlPercentActual+= $sumPercentageActual; @@ -916,34 +800,39 @@ class ActivityController extends Controller $tempTtlPercentPlan = 0; $tempTtlPercentActual = 0; } - }else{ + }else{ $tempPercentage[] = array(round($sumPercentagePlan,2), round($sumPercentageActual,2)); $tempDate[] = array($dt->format("Y-m-d"), 0, 0); } } if(round($totalACWP,0) > $totalRencanaBudget){ - $estimatedCost = round($totalACWP,0)+0; + $estimatedCost = round($totalACWP,0)+0; }else{ - $estimatedCost = ($totalRencanaBudget+0); + $estimatedCost = ($totalRencanaBudget+0); } $costDeviation = $totalRencanaBudget - $estimatedCost; + if($costDeviation > 0){ + $potential = "SAVING"; + } else { + $potential = $costDeviation == 0 ? "ON BUDGET" : "OVERRUN"; + } $dataResponse = array( "date" =>$tempDate, "percentage" =>$tempPercentage, "data_details" =>$arr_ActualM, - "budget_control" =>array("current_budget"=> $totalRencanaBudget, - "acwp" => round($totalACWP,0), - "bcwp" => round($totalBCWP,0), - "rem_to_complete" => ($totalRencanaBudget - round($totalACWP,0)), - "add_cost_to_complete" => 0, - "estimated_at_completion" => $estimatedCost, - "cost_deviation" => $costDeviation, - "potential" => $costDeviation > 0 ? "SAVING" : $costDeviation == 0 ? "ON BUDGET" : "OVERRUN" + "budget_control" =>array("current_budget"=> $totalRencanaBudget, + "acwp" => round($totalACWP,0), + "bcwp" => round($totalBCWP,0), + "rem_to_complete" => ($totalRencanaBudget - round($totalACWP,0)), + "add_cost_to_complete" => 0, + "estimated_at_completion" => $estimatedCost, + "cost_deviation" => $costDeviation, + "potential" => $potential, ) ); - + $dataFinal[] = array( "proyek_name"=> $dataProject->nama, "data"=>$dataResponse, @@ -952,196 +841,17 @@ class ActivityController extends Controller } return response()->json(['status'=>'success','code'=>200, 'data' => $dataFinal], 200); - - } - public function getCalculateCurvaSBackup(Request $request) - { - $dataPayload = $request->all(); - $allGantt = []; - foreach ($dataPayload['project_id'] as $val) { - $allGantt[] = $this->getMaxVersionGantt($val); - } - - $dataFinal=[]; - foreach ($allGantt as $val) { - $dataProject = Project::find($val['proyek_id']); - $holidays = Holiday::where("version_gantt_id", $val['last_gantt_id'])->where("proyek_id", $val['proyek_id'])->get(); - $dateHoliday = []; //$holiday->all(); - foreach ($holidays as $holiday) { - $startH = new \DateTime($holiday->date); - $endH = clone $startH; - $endH->modify('+'.$holiday->duration.' day'); - $intervalH = \DateInterval::createFromDateString('1 day'); - $periodH = new \DatePeriod($startH, $intervalH, $endH); - foreach ($periodH as $dt) { - $dateHoliday[] = $dt->format("Y-m-d"); - } - } - $verGantt = VersionGantt::find($val['last_gantt_id']); - $configOff = $verGantt->config_dayoff; - if($configOff && $configOff!= ""){ - $dayOff = explode(",", $verGantt->config_dayoff); - $dayOff = array_map( - function($value) { return (int)$value; }, - $dayOff - ); - }else{ - $dayOff = []; - } - $checkHeader = Activity::where('type_activity', 'header')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->count(); - if($checkHeader > 0){ - $dataHeader = Activity::where('type_activity', 'header')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->first(); - $minDate = Activity::where('parent_id', $dataHeader->id)->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->min("start_date"); - $maxDate = Activity::where('parent_id', $dataHeader->id)->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->max("end_date"); - }else{ - $minDate = Activity::whereNull('parent_id')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->min("start_date"); - $maxDate = Activity::whereNull('parent_id')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->max("end_date"); - } - - $begin = new \DateTime($minDate); - $end = new \DateTime($maxDate); - $end2 = new \DateTime($maxDate); - $end2 = $end2->modify( '-1 day' ); - $interval = \DateInterval::createFromDateString('1 day'); - $period = new \DatePeriod($begin, $interval, $end); - $dataHeader = Activity::where('type_activity', 'header')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->first(); - if($dataHeader){ - $totalRencanaBudget = Activity::select(DB::raw('sum(cast(rencana_biaya as bigint))'))->where('parent_id', $dataHeader->id)->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->first(); - }else{ - $totalRencanaBudget = Activity::select(DB::raw('sum(cast(rencana_biaya as bigint))'))->whereNull('parent_id')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->first(); - } - - - $totalRencanaBudget = $totalRencanaBudget->sum; - $currentPercentage = 0; - $currentACWP = 0; - $budgetControlACWP = 0; - $currentProgressActivity = 0; - $currentBCWP = 0; - $budgetControlBCWP = 0; - $dataDate = []; - $dataPercen = []; - $testdata = []; - $countWeek = 0; - foreach ($period as $dt) { - $weekDay = $dt->format("w"); - $currentDate = $dt->format("Y-m-d"); - $testdata[] = array('weekday' => $weekDay, 'date' =>$currentDate, 'dayof' => $dayOff); - - $totalPercentage = isset($totalPercentage) ? $totalPercentage : 0; - $totalACWP = isset($totalACWP) ? $totalACWP : 0; - $totalProgressActivity = isset($totalProgressActivity) ? $totalProgressActivity : 0; - $totalBCWP = isset($totalBCWP) ? $totalBCWP : 0; - - if(!in_array($weekDay, $dayOff) && !in_array($currentDate, $dateHoliday)) - { - $dataActivity = Activity::whereRaw("'".$currentDate."' BETWEEN DATE(m_activity.start_date) AND DATE(m_activity.end_date) - INTERVAL '1 DAY'")->where('type_activity', 'task')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->get(); - foreach ($dataActivity as $activity) { - - $duration = $activity->duration; - if($totalRencanaBudget > 0 && $duration > 0){ - $totalPercentage += $activity->bobot_planning/$duration; - if($activity->biaya_actual > 0 && $activity->persentase_progress){ - $totalACWP += $activity->biaya_actual/$duration; - $totalProgressActivity += (($activity->persentase_progress*$activity->bobot_planning)/100)/$duration; - $totalBCWP += (((($activity->persentase_progress*$activity->bobot_planning)/100)/$duration)* $totalRencanaBudget)/100; - } - } - } - - - } - - if($currentDate == $end2->format('Y-m-d')){ - $currentPercentage = round(($currentPercentage + $totalPercentage), 0); - if($totalACWP > 0 ){ - $budgetControlACWP = $currentACWP + $totalACWP; - } - if($totalBCWP > 0 ){ - $budgetControlBCWP = $currentBCWP + $totalBCWP; - } - $currentACWP = $totalACWP == 0 ? null : $currentACWP + $totalACWP; - $currentProgressActivity = $totalProgressActivity == 0 ? null : round(($currentProgressActivity + $totalProgressActivity),0); - - $currentBCWP = $totalBCWP == 0 ? null :$currentBCWP + $totalBCWP; - $currentPercentage = $currentPercentage > 100 ? 100 : $currentPercentage; - $currentProgressActivity = $currentProgressActivity > 100 ? 100 : $currentProgressActivity; - - - $dataDate[] = array($currentDate, round($currentBCWP,0), round($currentACWP,0)); - $dataPercen[] = array($currentPercentage, $currentProgressActivity); - - $totalPercentage = 0; - $totalACWP = 0; - $totalProgressActivity = 0; - $totalBCWP = 0; - }else if($weekDay == "0"){ - $currentPercentage = round(($currentPercentage + $totalPercentage), 0); - if($totalACWP > 0 ){ - $budgetControlACWP = $currentACWP + $totalACWP; - } - if($totalBCWP > 0 ){ - $budgetControlBCWP = $currentBCWP + $totalBCWP; - } - $currentACWP = $totalACWP == 0 ? null : $currentACWP + $totalACWP; - $currentProgressActivity = $totalProgressActivity == 0 ? null : round(($currentProgressActivity + $totalProgressActivity),0); - - $currentBCWP = $totalBCWP == 0 ? null :$currentBCWP + $totalBCWP; - $currentPercentage = $currentPercentage > 100 ? 100 : $currentPercentage; - $currentProgressActivity = $currentProgressActivity > 100 ? 100 : $currentProgressActivity; - - - $dataDate[] = array($currentDate, round($currentBCWP,0), round($currentACWP,0)); - $dataPercen[] = array($currentPercentage, $currentProgressActivity); - - $totalPercentage = 0; - $totalACWP = 0; - $totalProgressActivity = 0; - $totalBCWP = 0; - } - } - if(round($budgetControlACWP,0) > $totalRencanaBudget){ - $estimatedCost = round($budgetControlACWP,0)+0; - }else{ - $estimatedCost = ($totalRencanaBudget+0); - } - $costDeviation = $totalRencanaBudget - $estimatedCost; - - $dataResponse = array( - "date" =>$dataDate, - "percentage" =>$dataPercen, - "budget_control" =>array("current_budget"=> $totalRencanaBudget, - "acwp" => round($budgetControlACWP,0), - "bcwp" => round($budgetControlBCWP,0), - "rem_to_complete" => ($totalRencanaBudget - round($budgetControlACWP,0)), - "add_cost_to_complete" => 0, - "estimated_at_completion" => $estimatedCost, - "cost_deviation" => $costDeviation, - "potential" => $costDeviation > 0 ? "SAVING" : $costDeviation == 0 ? "ON BUDGET" : "OVERRUN" - ) - ); - $dataFinal[] = array( - "proyek_name"=> $dataProject->nama, - "data"=>$dataResponse - ); - } - - if($dataFinal){ - return response()->json(['status'=>'success','code'=>200,'data'=>$dataFinal, 'test' => array('current'=>$currentDate,'max' =>$end2->format('Y-m-d')), 'totalRecord'=>1], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list percentage day, please try again later!','code'=>400], 400); - } } public function getCalculateCurvaSDays(Request $request) - { + { $dataPayload = $request->all(); $allGantt = []; foreach ($dataPayload['project_id'] as $val) { $allGantt[] = $this->getMaxVersionGantt($val); } - + $dataFinal=[]; foreach ($allGantt as $val) { $dataProject = Project::find($val['proyek_id']); @@ -1176,7 +886,7 @@ class ActivityController extends Controller $minDate = Activity::whereNull('parent_id')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->min("start_date"); $maxDate = Activity::whereNull('parent_id')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->max("end_date"); } - + $begin = new \DateTime($minDate); $end = new \DateTime($maxDate); $interval = \DateInterval::createFromDateString('1 day'); @@ -1187,7 +897,7 @@ class ActivityController extends Controller }else{ $totalRencanaBudget = Activity::select(DB::raw('sum(cast(rencana_biaya as integer))'))->whereNull('parent_id')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->first(); } - + $totalRencanaBudget = $totalRencanaBudget->sum; $currentPercentage = 0; $currentACWP = 0; @@ -1196,7 +906,7 @@ class ActivityController extends Controller $dataDate = []; $dataPercen = []; $testdata = []; - foreach ($period as $dt) { + foreach ($period as $dt) { $weekDay = $dt->format("w"); $currentDate = $dt->format("Y-m-d"); $testdata[] = array('weekday' => $weekDay, 'date' =>$currentDate); @@ -1208,19 +918,19 @@ class ActivityController extends Controller $totalBCWP = 0; $dataActivity = Activity::whereRaw("'".$currentDate."' BETWEEN DATE(m_activity.start_date) AND DATE(m_activity.end_date) - INTERVAL '1 DAY'")->where('type_activity', 'task')->where("proyek_id", $val['proyek_id'])->where("version_gantt_id", $val['last_gantt_id'])->get(); foreach ($dataActivity as $activity) { - + $duration = $activity->duration; - if($totalRencanaBudget > 0 && $duration > 0){ + if($totalRencanaBudget > 0 && $duration > 0){ $totalPercentage += $activity->bobot_planning/$duration; if($activity->biaya_actual > 0 && $activity->persentase_progress){ $totalACWP += $activity->biaya_actual/$duration; $totalProgressActivity += (($activity->persentase_progress*$activity->bobot_planning)/100)/$duration; $totalBCWP += (((($activity->persentase_progress*$activity->bobot_planning)/100)/$duration)* $totalRencanaBudget)/100; } - } + } } - - $currentPercentage = round(($currentPercentage + $totalPercentage), 0); + + $currentPercentage = round(($currentPercentage + $totalPercentage), 0); $currentACWP = $totalACWP == 0 ? null : $currentACWP + $totalACWP; $currentProgressActivity = $totalProgressActivity == 0 ? null : round(($currentProgressActivity + $totalProgressActivity),0); $currentBCWP = $totalBCWP == 0 ? null :$currentBCWP + $totalBCWP; @@ -1230,7 +940,7 @@ class ActivityController extends Controller $dataDate[] = array($currentDate, $currentBCWP, $currentACWP); $dataPercen[] = array($currentPercentage, $currentProgressActivity); - }else{ + }else{ $dataDate[] = $currentDate; $dataPercen[] = array($currentPercentage,$currentProgressActivity); } @@ -1286,7 +996,7 @@ class ActivityController extends Controller foreach($activities as $activity) { $activity_id = $activity->id; - $countReports = ReportActivity::where('activity_id', $activity_id)->count(); + $countReports = ReportActivity::where('activity_id', $activity_id)->count(); if ($countReports === 1) { $dataReports = ReportActivity::where('activity_id', $activity_id)->orderBy('report_date')->get(); foreach($dataReports as $dr) { @@ -1318,4 +1028,4 @@ class ActivityController extends Controller return response()->json(['status'=>'success','message'=>'Synchronize to report success!','code'=>200], 200); } -} \ No newline at end of file +} From 2c153cf22fd5111cd6715355da9c7ce8ce907053 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Sun, 10 Jul 2022 22:05:17 +0700 Subject: [PATCH 08/19] implement calculation on boot model --- app/Models/AssignMaterial.php | 20 ++++++++++++++++++ app/Models/UserToActivity.php | 39 ++++++++++++++++++++++++++++++++--- 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/app/Models/AssignMaterial.php b/app/Models/AssignMaterial.php index 4a5706d..381ac6a 100644 --- a/app/Models/AssignMaterial.php +++ b/app/Models/AssignMaterial.php @@ -3,6 +3,8 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; +use App\Models\RequestMaterial; +use App\Models\Activity; class AssignMaterial extends Model { @@ -14,4 +16,22 @@ class AssignMaterial extends Model protected $fillable = [ 'proyek_id', 'activity_id', 'material_id', 'qty_planning', 'budget', 'plan_date','created_at', 'created_by', 'updated_at', 'updated_by' ]; + + public static function boot() { + parent::boot(); + + static::created(function($data) { + $activity = Activity::find($data->activity_id); + $material = RequestMaterial::where("id", $data->material_id)->first(); + $activity->rencana_biaya += $activity->rencana_biaya + ($material->price * $data->qty_planning); + $activity->save(); + }); + + static::deleted(function($data) { + $activity = Activity::where('id', $data->activity_id)->first(); + $activity->rencana_biaya -= $data->budget * $data->qty_planning; + $activity->save(); + }); + + } } diff --git a/app/Models/UserToActivity.php b/app/Models/UserToActivity.php index c2cc069..3dac828 100644 --- a/app/Models/UserToActivity.php +++ b/app/Models/UserToActivity.php @@ -3,6 +3,7 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; +use App\Models\Activity; class UserToActivity extends Model { @@ -17,9 +18,41 @@ class UserToActivity extends Model 'version_gantt_id', 'role_proyek_id', 'activity_id', - 'created_at', - 'created_by', - 'updated_at', + 'created_at', + 'created_by', + 'updated_at', 'updated_by' ]; + + public static function boot() { + parent::boot(); + + static::created(function($data) { + $activity = Activity::find($data->activity_id); + $getWorkingHours = UserToProyek::where('user_id', $data->user_id)->where('proyek_id', $activity->proyek_id)->first(); + + $salary = ($getWorkingHours->standart_rate * $activity->duration) * ($getWorkingHours->max_used / 100); + + if($getWorkingHours->uom_standart_rate == "Hour") + $salary = ($getWorkingHours->standart_rate * 8) * $activity->duration * ($getWorkingHours->max_used / 100); + + $activity->rencana_biaya += $salary; + $activity->save(); + }); + + static::deleted(function($data) { + $activity = Activity::find($data->activity_id); + + $getWorkingHours = UserToProyek::where('user_id', $data->user_id)->where('proyek_id', $activity->proyek_id)->first(); + $salary = ($getWorkingHours->standart_rate * $activity->duration) * ($getWorkingHours->max_used / 100); + if($getWorkingHours->uom_standart_rate == "Hour"){ + $salary = ($getWorkingHours->standart_rate * 8) * $activity->duration * ($getWorkingHours->max_used / 100); + } + + $activity->rencana_biaya -= $salary; + $activity->save(); + }); + + } + } From e547e8025049592d8f9d048bbdfa0b5b0e26153a Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Sun, 10 Jul 2022 22:06:29 +0700 Subject: [PATCH 09/19] clean codes & move logics to model --- .../Controllers/AssignMaterialController.php | 433 +++++++----------- 1 file changed, 167 insertions(+), 266 deletions(-) diff --git a/app/Http/Controllers/AssignMaterialController.php b/app/Http/Controllers/AssignMaterialController.php index c656867..7460da9 100644 --- a/app/Http/Controllers/AssignMaterialController.php +++ b/app/Http/Controllers/AssignMaterialController.php @@ -4,277 +4,178 @@ namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\AssignMaterial; -use App\Models\MaterialResource; use App\Models\RequestMaterial; -use App\Models\Activity; use App\Models\ReportActivityMaterial; use Datatables; class AssignMaterialController extends Controller { - public function add_backup(Request $request){ - $this->validate($request, [ - 'activity_id' => 'required', - 'material_id' => 'required', - 'qty_planning' => 'required', - 'budget' => 'required' - ]); - $checkStock = MaterialResource::where("id", $request->material_id)->first(); - $currentStock = $checkStock->qty; - if((int)$currentStock < (int)$request->qty_planning){ - return response()->json(['status'=>'failed','message'=>'Not enough stock in warehouse!','code'=>400]); - die(); - } - - - - $data = $request->all(); - - $data['created_by'] = $this->currentName; - - $result = AssignMaterial::create($data); - if($result){ - $checkStock = MaterialResource::find($request->material_id); - $newStock = (int)$checkStock->qty - (int)$request->qty_planning; - $dataUpdate = array( - "qty"=>$newStock, - "updated_by"=>$this->currentName - ); - $checkStock->update($dataUpdate); - - return response()->json(['status'=>'success','message'=>'Assign material successfull created','code'=>200]); - }else{ - return response()->json(['status'=>'failed','message'=>'Assign material failed created','code'=>400]); - } - } - - public function add(Request $request){ - $this->validate($request, [ - 'activity_id' => 'required', - 'material_id' => 'required', - 'qty_planning' => 'required' - ]); - - $checkStock = RequestMaterial::where("id", $request->material_id)->first(); - $currentStock = $checkStock->qty; - $price = $checkStock->price; - if((int)$currentStock < (int)$request->qty_planning){ - return response()->json(['status'=>'failed','message'=>'Not enough stock !','code'=>400]); - die(); - } - - $data = $request->all(); - - $data['created_by'] = $this->currentName; - $data['budget'] = $price; - - $result = AssignMaterial::create($data); - if($result){ - - $updateActivity = Activity::find($request->activity_id); - if($updateActivity){ - $costPlanOld = $updateActivity==null? 0 : (int)$updateActivity->rencana_biaya; - $costPlanNew = $costPlanOld + ($price*$request->qty_planning); - $updateActivity->rencana_biaya = $costPlanNew; - $updateActivity->save(); - return response()->json(['status'=>'success','message'=>'Assign material successfull created, and update cost plan success '.$costPlanNew,'code'=>200]); - }else{ - return response()->json(['status'=>'success','message'=>'Assign material successfull created','code'=>200]); - } - }else{ - return response()->json(['status'=>'failed','message'=>'Assign material failed created','code'=>400]); - } - } - - private function updateFromAdd($data){ - $assignMaterial = AssignMaterial::where("activity_id", $data->activity_id)->where("material_id", $data->material_id)->first(); - - $newQty = (int)$assignMaterial->qty_planning + (int)$data->qty_planning; - - $newBudget = $assignMaterial->budget > $data->budget ? $assignMaterial->budget : $data->budget; - - $dataUpdate = array( - "qty_planning"=>$newQty, - "budget"=>$newBudget, - "updated_by"=>$this->currentName - ); - - $dataWillUpdate = AssignMaterial::where("activity_id", $data->activity_id)->where("material_id", $data->material_id); - - return $dataWillUpdate->update($dataUpdate); - } - - public function update(Request $request, $id){ - - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - } - $data = AssignMaterial::find($id); - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'Data Assign material not found!','code'=>400], 400); - die(); - } - - if($result){ - return response()->json(['status'=>'success','message'=>'Assign material successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'Assign material failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = AssignMaterial::find($id); - - if($data){ - $id = $data->material_id; - $stock = $data->qty_planning; - $materialResource = MaterialResource::find($id); - if($materialResource){ - $oldStock = $materialResource->qty; - $newStock = $oldStock + $stock; - $dataUpdate = array( - "qty"=>$newStock, - "updated_by"=>$this->currentName - ); - $materialResource->update($dataUpdate); - } - $activity = Activity::where('id', $data->activity_id)->first(); - $activity->rencana_biaya -= $data->budget * $data->qty_planning; - $activity->save(); - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'Data Assign material not found!','code'=>400], 400); - die(); - } - - if($delete){ - return response()->json(['status'=>'success','message'=>'Assign material successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'Assign material failed deleted!','code'=>400], 400); - } - } - - public function edit($id){ - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); - } - - $result = AssignMaterial::find($id); - - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data Assign material, please try again later!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'assign_material_to_activity'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function list() - { - $data = AssignMaterial::all(); - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get Assign material, please try again later!','code'=>400], 400); - } - } - - public function datatables(Request $request){ - $id_activity = $request->query('idact'); - $data = AssignMaterial::select("assign_material_to_activity.*","m.description as material_name", "m.uom as uom")->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id")->where('assign_material_to_activity.activity_id', $id_activity)->get(); - return Datatables::of($data) - ->addIndexColumn() - ->addColumn('action', function($row){ - $actionBtn = ''; - return $actionBtn; - }) - ->rawColumns(['action'])->make(true); - } - - public function datatablesForReportActivity(Request $request){ - $id_activity = $request->query('idact'); - $data = AssignMaterial::select(AssignMaterial::raw('SUM(qty_planning) as qty_planning'), "m.description as material_name", "assign_material_to_activity.activity_id as activity_id") - ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") - ->groupBy("m.description") - ->groupBy("assign_material_to_activity.activity_id") - ->where("assign_material_to_activity.activity_id", $id_activity)->get(); - return Datatables::of($data) - ->addIndexColumn() - ->addColumn('qty_sum', function($row){ - $val_qty_act = AssignMaterial::select(ReportActivityMaterial::raw('SUM(ram.qty) as qty_sum'),"m.description as material_name1") - ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") - ->join("report_activity_material as ram", "ram.assign_material_id", "=", "assign_material_to_activity.id") - ->groupBy("m.description") - ->where("m.description", strval($row->material_name)) - ->where("ram.activity_id", $row->activity_id)->first(); - return $val_qty_act ? $val_qty_act->qty_sum : '-'; - }) - ->addColumn('status_activity', function($row){ - $val_status = AssignMaterial::select("status_activity") - ->join('m_req_material as m', 'm.id', '=', 'assign_material_to_activity.material_id') - ->where('m.description', '=', $row->material_name) - ->where("assign_material_to_activity.activity_id", $row->activity_id)->first(); - return $val_status ? $val_status->status_activity : null; - }) - ->addColumn('start_activity', function($row){ - $val_start = AssignMaterial::select("start_activity") - ->join('m_req_material as m', 'm.id', '=', 'assign_material_to_activity.material_id') - ->where('m.description', '=', $row->material_name) - ->where("assign_material_to_activity.activity_id", $row->activity_id)->first(); - return $val_start ? $val_start->start_activity : null; - }) - ->addColumn('finish_activity', function($row){ - $val_finish = AssignMaterial::select("finish_activity") - ->join('m_req_material as m', 'm.id', '=', 'assign_material_to_activity.material_id') - ->where('m.description', '=', $row->material_name) - ->where("assign_material_to_activity.activity_id", $row->activity_id)->first(); - return $val_finish ? $val_finish->finish_activity : null; - }) - ->addColumn('uom', function($row){ - $val_uom = RequestMaterial::select("uom") - ->where('description', '=', $row->material_name)->first(); - return $val_uom ? $val_uom->uom : null; - }) - ->addColumn('action', function($row){ - $actionBtn = ''; - $actionBtn .= ''; - return $actionBtn; - }) - ->rawColumns(['action'])->make(true); - } - - public function ForReportActivityByMaterial(Request $request){ - $id_activity = $request->idact; - $data = AssignMaterial::select("assign_material_to_activity.*","m.description as material_name", "m.uom as uom") - ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") - ->where('assign_material_to_activity.activity_id', $id_activity)->get(); - foreach ($data as $key) { - # code... - - $val_qty_sum = ReportActivityMaterial::where('assign_material_id', '=', $key->id)->sum("qty"); - } - $countData = $data->count(); - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get Assign material, please try again later!','code'=>400], 400); - } - } + public function add(Request $request){ + $this->validate($request, [ + 'activity_id' => 'required', + 'material_id' => 'required', + 'qty_planning' => 'required' + ]); + + $checkStock = RequestMaterial::where("id", $request->material_id)->first(); + $currentStock = $checkStock->qty; + $price = $checkStock->price; + if((int)$currentStock < (int)$request->qty_planning){ + return response()->json(['status'=>'failed','message'=>'Stock is not enough!','code'=> 500]); + } + + $data = $request->all(); + $data['created_by'] = $this->currentName; + $data['budget'] = $price; + + $result = AssignMaterial::create($data); + if(!$result) + return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=> 500]); + + return response()->json(['status'=>'success','message'=>'Data added!', 'code'=>200]); + + } + + public function update(Request $request, $id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $data = AssignMaterial::find($id); + if(!$data) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + + $result = $data->update($request->all()); + + if($result) + return response()->json(['status'=>'success','message'=> 'Data updated!','code'=> 200], 200); + + return response()->json(['status'=>'failed','message'=>'Failed to update!','code'=> 500], 500); + } + + public function delete($id) + { + $data = AssignMaterial::where('id', $id)->first(); + + if($data->delete()) + return response()->json(['status'=>'success','message'=>'Data deleted!','code'=> 200], 200); + + return response()->json(['status'=>'failed','message'=>'Failed to delete!','code'=> 500], 500); + } + + public function edit($id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $result = AssignMaterial::find($id); + + if($result) + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'assign_material_to_activity'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function list() + { + $data = AssignMaterial::all(); + $countData = $data->count(); + + if($data) + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + + return response()->json(['status'=>'failed','message'=>'Failed to get the data!','code'=> 500], 500); + } + + public function datatables(Request $request){ + $id_activity = $request->query('idact'); + $data = AssignMaterial::select("assign_material_to_activity.*","m.description as material_name", "m.uom as uom")->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id")->where('assign_material_to_activity.activity_id', $id_activity)->get(); + return Datatables::of($data) + ->addIndexColumn() + ->addColumn('action', function($row){ + $actionBtn = ''; + return $actionBtn; + }) + ->rawColumns(['action'])->make(true); + } + + public function datatablesForReportActivity(Request $request){ + $id_activity = $request->query('idact'); + $data = AssignMaterial::select(AssignMaterial::raw('SUM(qty_planning) as qty_planning'), "m.description as material_name", "assign_material_to_activity.activity_id as activity_id") + ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") + ->groupBy("m.description") + ->groupBy("assign_material_to_activity.activity_id") + ->where("assign_material_to_activity.activity_id", $id_activity)->get(); + return Datatables::of($data) + ->addIndexColumn() + ->addColumn('qty_sum', function($row){ + $val_qty_act = AssignMaterial::select(ReportActivityMaterial::raw('SUM(ram.qty) as qty_sum'),"m.description as material_name1") + ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") + ->join("report_activity_material as ram", "ram.assign_material_id", "=", "assign_material_to_activity.id") + ->groupBy("m.description") + ->where("m.description", strval($row->material_name)) + ->where("ram.activity_id", $row->activity_id)->first(); + return $val_qty_act ? $val_qty_act->qty_sum : '-'; + }) + ->addColumn('status_activity', function($row){ + $val_status = AssignMaterial::select("status_activity") + ->join('m_req_material as m', 'm.id', '=', 'assign_material_to_activity.material_id') + ->where('m.description', '=', $row->material_name) + ->where("assign_material_to_activity.activity_id", $row->activity_id)->first(); + return $val_status ? $val_status->status_activity : null; + }) + ->addColumn('start_activity', function($row){ + $val_start = AssignMaterial::select("start_activity") + ->join('m_req_material as m', 'm.id', '=', 'assign_material_to_activity.material_id') + ->where('m.description', '=', $row->material_name) + ->where("assign_material_to_activity.activity_id", $row->activity_id)->first(); + return $val_start ? $val_start->start_activity : null; + }) + ->addColumn('finish_activity', function($row){ + $val_finish = AssignMaterial::select("finish_activity") + ->join('m_req_material as m', 'm.id', '=', 'assign_material_to_activity.material_id') + ->where('m.description', '=', $row->material_name) + ->where("assign_material_to_activity.activity_id", $row->activity_id)->first(); + return $val_finish ? $val_finish->finish_activity : null; + }) + ->addColumn('uom', function($row){ + $val_uom = RequestMaterial::select("uom") + ->where('description', '=', $row->material_name)->first(); + return $val_uom ? $val_uom->uom : null; + }) + ->addColumn('action', function($row){ + $actionBtn = ''; + $actionBtn .= ''; + return $actionBtn; + }) + ->rawColumns(['action'])->make(true); + } + + public function ForReportActivityByMaterial(Request $request){ + $id_activity = $request->idact; + $data = AssignMaterial::select("assign_material_to_activity.*","m.description as material_name", "m.uom as uom") + ->join("m_req_material as m", "m.id", "=", "assign_material_to_activity.material_id") + ->where('assign_material_to_activity.activity_id', $id_activity)->get(); + foreach ($data as $key) { + # code... + + $val_qty_sum = ReportActivityMaterial::where('assign_material_id', '=', $key->id)->sum("qty"); + } + $countData = $data->count(); + if($data){ + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get Assign material, please try again later!','code'=>400], 400); + } + } } From 7ce1b8647f96f8dcd4f8bcfc6a6810e244835cd3 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Sun, 10 Jul 2022 22:09:00 +0700 Subject: [PATCH 10/19] WIP: increase token TTL --- app/Http/Controllers/AuthController.php | 29 ++++++++++--------------- 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/app/Http/Controllers/AuthController.php b/app/Http/Controllers/AuthController.php index 8dabcfd..67ad016 100644 --- a/app/Http/Controllers/AuthController.php +++ b/app/Http/Controllers/AuthController.php @@ -4,6 +4,7 @@ namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Hash; use App\Models\User; use App\Models\Role; @@ -22,19 +23,16 @@ class AuthController extends Controller $remember = $request->remember; $is_mobile = $request->is_mobile; - if(empty($username) || empty($password)){ + if(empty($username) || empty($password)) return response()->json(['status'=>'error','message'=>'You must fill all the fields'], 400); - } $user = User::where('username', $username)->where('password', md5($password))->first(); if($is_mobile){ $fcm_token = $request->fcm_token; - if(!$fcm_token || $fcm_token==""){ + if(!$fcm_token || $fcm_token=="") return response()->json(['status'=>'error','message'=>'FCM Token is required'], 400); - die(); - } $dataUpdateFcm = array( "fcm_token"=>$fcm_token @@ -42,31 +40,26 @@ class AuthController extends Controller $hr = User::find($user->id); - if($hr){ + if($hr) $hr->update($dataUpdateFcm); - } } - $dataRole = Role::find($user->role_id); - if($dataRole){ + if($dataRole) $user->role = $dataRole; - } - - if (! $token =Auth::login($user)) { + if (! $token =Auth::login($user)) return response()->json(['error' => 'Unauthorized'], 401); - } - return $this->respondWithToken($token, $user, $remember); - } - - protected function respondWithToken($token, $user, $remember) - { $ttl = 60; if($remember) $ttl = 10080; + + // todo : change existing md5 hashed function to laravel's originally bcrypt + /* $token = auth()->setTTL($ttl)->attempt(['username' => $username, 'password' => Hash::make($password)]); */ + /* dd(response()->json(['code'=>'200', 'token' => $token, 'ttl' => $ttl])); */ + return response()->json([ 'code' => 200, 'data' => array( From 49d0ee74977af7b710d07e7ad2ff1993d0adc138 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Sun, 10 Jul 2022 22:09:15 +0700 Subject: [PATCH 11/19] clean codes & move logics to model --- .../Controllers/UserToActivityController.php | 344 ++++++++---------- 1 file changed, 143 insertions(+), 201 deletions(-) diff --git a/app/Http/Controllers/UserToActivityController.php b/app/Http/Controllers/UserToActivityController.php index 4de32b5..2b9b403 100644 --- a/app/Http/Controllers/UserToActivityController.php +++ b/app/Http/Controllers/UserToActivityController.php @@ -4,209 +4,151 @@ namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\UserToActivity; -use App\Models\ReportActivity; use App\Models\Activity; -use App\Models\Image; -use App\Models\UserToProyek; use Datatables; class UserToActivityController extends Controller -{ - public function add(Request $request){ - $this->validate($request, [ - 'activity_id' => 'required', - 'user_id' => 'required' - ]); - $data = $request->all(); - $data['created_by'] = $this->currentName; - - $result = UserToActivity::create($data); - if($result){ - $updateActivity = Activity::find($request->activity_id); - $getWorkingHours = UserToProyek::where('user_id', $request->user_id)->first(); - if($updateActivity && $getWorkingHours){ - $costPlanOld = $updateActivity==null? 0 : (int)$updateActivity->rencana_biaya; - if($getWorkingHours->uom_standart_rate == "Day"){ - $costUser = $getWorkingHours->standart_rate * $updateActivity->duration; - }else if($getWorkingHours->uom_standart_rate == "Hour"){ - $costUser = ($getWorkingHours->standart_rate * 8) * $updateActivity->duration; // assumption standart working is 8 hours - } - $costPlanNew = $costPlanOld + $costUser; - $updateActivity->rencana_biaya = $costPlanNew; - $updateActivity->save(); - return response()->json(['status'=>'success','message'=>'user to activity gantt Project successfull created, and cost plant successfull update '.$costPlanNew,'code'=>200]); - }else{ - return response()->json(['status'=>'success','message'=>'user to activity gantt Project successfull created','code'=>200]); - } - }else{ - return response()->json(['status'=>'failed','message'=>'user to activity gantt Project failed created','code'=>400]); - } - } - - public function addMultiple(Request $request){ - $users_id = $request->user_id; - - $data = UserToActivity::where("activity_id", $request->activity_id); - - if($data){ - $data->delete(); - } - - if(is_array($users_id) && count($users_id) > 0){ - $countRes = 0; - foreach($users_id as $item){ - - $dataInsert = array( - "user_id" => $item, - "activity_id" => $request->activity_id, - "role_proyek_id" => $request->role_proyek_id, - "proyek_id" => $request->proyek_id, - "created_by" => $this->currentName - ); - - $result = UserToActivity::create($dataInsert); - - if($result){ - $countRes++; - }else{ - $countRes--; - } - } - - if($countRes > 0){ - $allCost = $this->calculateAllCost($request->activity_id, $request->proyek_id); - $dataUpdateCost = array( - "rencana_biaya"=>$allCost, - "updated_by"=> $this->currentName - ); - $actUpdate = Activity::find($request->activity_id); - if($actUpdate){ - $actUpdate->update($dataUpdateCost); - if($actUpdate->parent_id){ - $this->updatedCostPlanning($actUpdate->parent_id); - } - } - - return response()->json(['status'=>'success' ,'message'=>'user to activity gantt Project successfull created','code'=>200]); - }else{ - return response()->json(['status'=>'success' ,'message'=>'user to activity gantt Project failed created','code'=>400]); - } - }else{ - return response()->json(['status'=>'success' ,'message'=>'user to activity gantt Project successfull created','code'=>200]); - } - - } - - public function update(Request $request, $id){ - - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - } - $data = UserToActivity::find($id); - if($data){ - $result = $data->update($request->all()); - }else{ - return response()->json(['status'=>'failed','message'=>'data user to activity gantt Project not found!','code'=>400], 400); - die(); - } - - if($result){ - return response()->json(['status'=>'success','message'=>'user to activity gantt Project successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'user to activity gantt Project failed updated!','code'=>400], 400); - } - } - - public function delete($id) - { - $data = UserToActivity::find($id); - if($data){ - $userId = $data->user_id; - $activityId = $data->activity_id; - $delete = $data->delete(); - if($delete){ - $this->deleteRelative($activityId, $userId); - } - }else{ - return response()->json(['status'=>'failed','message'=>'data user to activity gantt Project not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'user to activity gantt Project successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'user to activity gantt Project failed deleted!','code'=>400], 400); - } - } - - private function deleteRelative($id, $userId) - { - $dataRa = ReportActivity::where("activity_id", $id)->where("user_id", $userId)->get(); - foreach ($dataRa as $ra) { - $image = Image::where("ref_id", $ra->id)->where("category", "report_activity")->get(); - foreach ($image as $value) { - if(file_exists($this->pathImage.$value->image)){ - unlink($this->pathImage.$value->image); - } - } - - Image::where("ref_id", $ra->id)->where("category", "report_activity")->delete(); - } - ReportActivity::where("activity_id", $id)->where("user_id", $userId)->delete(); - } - - public function edit($id){ - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); - } - - $result = UserToActivity::find($id); - - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data tools resource, please try again later!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'assign_hr_to_activity'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function list() - { - $data = UserToActivity::all(); - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list user to activity gantt, please try again later!','code'=>400], 400); - } - } - - public function datatables(Request $request){ - $id_activity = $request->query('idact'); - $data = UserToActivity::select("assign_hr_to_activity.id as id", "u.name as user_name", "mrp.name as role_name") - ->join("m_role_proyek as mrp", "mrp.id", "=", "assign_hr_to_activity.role_proyek_id") - ->join("m_users as u", "u.id", "=", "assign_hr_to_activity.user_id") - ->where('assign_hr_to_activity.activity_id', $id_activity) - ->get(); - return Datatables::of($data) - ->addIndexColumn() - ->addColumn('action', function($row){ - $actionBtn = ''; - return $actionBtn; - }) - ->rawColumns(['action'])->make(true); - } +{ + public function add(Request $request){ + $this->validate($request, [ + 'activity_id' => 'required', + 'user_id' => 'required' + ]); + + $data = $request->all(); + $data['created_by'] = $this->currentName; + + if(!UserToActivity::create($data)) + return response()->json(['status'=>'failed','message'=>'Failed to add data!','code'=> 500]); + + return response()->json(['status'=>'success','message'=>'Data added!', 'code'=> 200]); + } + + public function addMultiple(Request $request){ + $users_id = $request->user_id; + + $data = UserToActivity::where("activity_id", $request->activity_id); + if($data){ + $data->delete(); + } + + if(is_array($users_id) && count($users_id) > 0){ + $countRes = 0; + foreach($users_id as $item){ + $dataInsert = array( + "user_id" => $item, + "activity_id" => $request->activity_id, + "role_proyek_id" => $request->role_proyek_id, + "proyek_id" => $request->proyek_id, + "created_by" => $this->currentName + ); + $result = UserToActivity::create($dataInsert); + if($result){ + $countRes++; + }else{ + $countRes--; + } + } + + if($countRes == 0) + return response()->json(['status'=>'failed' ,'message'=>'Failed to add data!','code'=> 500]); + + $allCost = $this->calculateAllCost($request->activity_id, $request->proyek_id); + $dataUpdateCost = array( + "rencana_biaya"=>$allCost, + "updated_by"=> $this->currentName + ); + $actUpdate = Activity::find($request->activity_id); + if($actUpdate){ + $actUpdate->update($dataUpdateCost); + if($actUpdate->parent_id){ + $this->updatedCostPlanning($actUpdate->parent_id); + } + } + return response()->json(['status'=>'success' ,'message'=>'Data added!','code'=>200]); + }else{ + return response()->json(['status'=>'success' ,'message'=>'Data added!','code'=>200]); + } + + } + + public function update(Request $request, $id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $data = UserToActivity::find($id); + if(!$data) + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + + if(!$data->update($request->all())); + return response()->json(['status'=>'failed','message'=>'Failed to update!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=>'Data updated!','code'=>200], 200); + } + + public function delete($id) + { + $data = UserToActivity::find($id); + if(!$data) + return response()->json(['status'=>'failed','message'=>'data user to activity gantt Project not found!','code'=>400], 400); + + if($data->delete()){ + return response()->json(['status'=>'success','message'=>'Data deleted!','code'=>200], 200); + } + + return response()->json(['status'=>'failed','message'=>'Failed to delete!','code'=> 500], 500); + } + + public function edit($id){ + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + die(); + } + + $result = UserToActivity::find($id); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'failed get data tools resource, please try again later!','code'=>400], 400); + + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'assign_hr_to_activity'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function list() + { + $data = UserToActivity::all(); + $countData = $data->count(); + + if($data){ + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'failed get list user to activity gantt, please try again later!','code'=>400], 400); + } + } + + public function datatables(Request $request){ + $id_activity = $request->query('idact'); + $data = UserToActivity::select("assign_hr_to_activity.id as id", "u.name as user_name", "mrp.name as role_name") + ->join("m_role_proyek as mrp", "mrp.id", "=", "assign_hr_to_activity.role_proyek_id") + ->join("m_users as u", "u.id", "=", "assign_hr_to_activity.user_id") + ->where('assign_hr_to_activity.activity_id', $id_activity) + ->get(); + return Datatables::of($data) + ->addIndexColumn() + ->addColumn('action', function($row){ + $actionBtn = ''; + return $actionBtn; + }) + ->rawColumns(['action'])->make(true); + } } From 7864a24801c77007481a279de7e31916eb5bd010 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Sun, 10 Jul 2022 22:09:30 +0700 Subject: [PATCH 12/19] clean codes --- app/Http/Controllers/Controller.php | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 842dd77..cefe1a4 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -10,7 +10,7 @@ class Controller extends BaseController protected $pathImage = "assets/image/"; protected $pathDocument = "assets/file/project/"; protected $pathActivityDocument = "assets/file/activity/"; - protected $listJoinAll = ['first', 'second', 'third', 'fourth', 'fifth', + protected $listJoinAll = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth']; protected $currentDate; protected $currentName; @@ -35,14 +35,14 @@ class Controller extends BaseController if($condition){ if(isset($condition['joins'])){ $selectColumn = []; - $no = 0; + $no = 0; foreach($condition['joins'] as $join){ $tableJoin = isset($join['name1']) ? $join['name1'] : $alias; $tableName = $join['name']; $columnJoin = $join['column_join']; // foreign key table sini $columnSelf = isset($join['column_self']) ? $join['column_self'] : "id"; // primary key table lawan $columnResult = $join['column_results']; - + foreach($columnResult as $sColumn){ $builder = $builder->addSelect($tableName.".".$sColumn." as join_".$this->listJoinAll[$no]."_".$sColumn); } @@ -50,7 +50,7 @@ class Controller extends BaseController $no++; } } - + if(isset($condition['columns'])){ $listWhere = $condition['columns']; @@ -71,7 +71,7 @@ class Controller extends BaseController if(isset($condition['group_column'])){ $builder = $this->groupWhere($builder, $condition['group_column'], $alias); } - + $data['count'] = clone $builder; if(isset($condition['paging'])){ @@ -225,7 +225,7 @@ class Controller extends BaseController ->where("assign_hr_to_activity.activity_id", $activity_id)->where("assign_hr_to_activity.proyek_id", $proyek_id) ->where("ahp.proyek_id", $proyek_id) ->get(); - + $totalCost = 0; foreach ($dataHuman as $human) { $uom = $human->uom_standart_rate; @@ -242,7 +242,7 @@ class Controller extends BaseController $standarRate = $human->standart_rate; $maxUsed = $human->max_used/100; $totalCost = ($standarRate*$duration)*$maxUsed; - return $totalCost; + return $totalCost; } private function calculateMaterialCost($activity_id, $proyek_id) @@ -251,11 +251,6 @@ class Controller extends BaseController return $totalCost; } - private function calculateToolsCost($activity_id, $proyek_id) - { - - } - protected function updatedCostPlanning($id) { $sumBiaya = Activity::select(DB::raw('sum(cast(rencana_biaya as double precision))'))->where("parent_id", $id)->first(); @@ -272,4 +267,4 @@ class Controller extends BaseController } } } -} \ No newline at end of file +} From fa2a66893642ded26a12eb61002ec46fe19eed80 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Mon, 11 Jul 2022 04:07:42 +0700 Subject: [PATCH 13/19] cast number to float --- app/Models/AssignMaterial.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/app/Models/AssignMaterial.php b/app/Models/AssignMaterial.php index 381ac6a..dc29bd9 100644 --- a/app/Models/AssignMaterial.php +++ b/app/Models/AssignMaterial.php @@ -15,6 +15,12 @@ class AssignMaterial extends Model protected $fillable = [ 'proyek_id', 'activity_id', 'material_id', 'qty_planning', 'budget', 'plan_date','created_at', 'created_by', 'updated_at', 'updated_by' + ]; + + protected $casts = [ + 'id' => 'integer', + 'price' => 'float', + 'qty_planning' => 'float', ]; public static function boot() { @@ -23,13 +29,13 @@ class AssignMaterial extends Model static::created(function($data) { $activity = Activity::find($data->activity_id); $material = RequestMaterial::where("id", $data->material_id)->first(); - $activity->rencana_biaya += $activity->rencana_biaya + ($material->price * $data->qty_planning); + $activity->rencana_biaya += floatval($material->price) * floatval($data->qty_planning); $activity->save(); }); static::deleted(function($data) { $activity = Activity::where('id', $data->activity_id)->first(); - $activity->rencana_biaya -= $data->budget * $data->qty_planning; + $activity->rencana_biaya -= floatval($data->budget) * floatval($data->qty_planning); $activity->save(); }); From bba8c5df6d1710824552973d6bf69d7149d9a0b9 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Mon, 11 Jul 2022 04:07:58 +0700 Subject: [PATCH 14/19] ada jwt config file --- config/jwt.php | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 config/jwt.php diff --git a/config/jwt.php b/config/jwt.php new file mode 100644 index 0000000..dfe274b --- /dev/null +++ b/config/jwt.php @@ -0,0 +1,5 @@ + env('API_NOMINATIM', 'https://nominatim.oslogdev.com') + ]; +?> From f68b8e7502a8c771f622cff488d33baa1ce309f9 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Mon, 11 Jul 2022 18:52:21 +0700 Subject: [PATCH 15/19] update cast type data --- app/Models/AssignMaterial.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Models/AssignMaterial.php b/app/Models/AssignMaterial.php index dc29bd9..f7abd89 100644 --- a/app/Models/AssignMaterial.php +++ b/app/Models/AssignMaterial.php @@ -19,7 +19,7 @@ class AssignMaterial extends Model protected $casts = [ 'id' => 'integer', - 'price' => 'float', + 'budget' => 'float', 'qty_planning' => 'float', ]; From c0d7e250d1d181a20f46267c27daca275535b44e Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Mon, 11 Jul 2022 20:23:59 +0700 Subject: [PATCH 16/19] add logger for activity material --- activity_log.txt | 10 ++++++++++ app/Models/AssignMaterial.php | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100755 activity_log.txt diff --git a/activity_log.txt b/activity_log.txt new file mode 100755 index 0000000..adef32d --- /dev/null +++ b/activity_log.txt @@ -0,0 +1,10 @@ +2022-07-11 20:20:30: Project Plan +Added: (10000 * 5), Cost plan old: 0 | 50000_ +Data type (double * double), double | double +Data type origin (double * NULL), string | double +------ +2022-07-11 20:21:26: Project Plan +Deleted: (10000 * 5), Cost plan old: 50000 | -0_ +Data type (double * double), double | double +Data type origin (double * double), string | double +------ diff --git a/app/Models/AssignMaterial.php b/app/Models/AssignMaterial.php index f7abd89..7060c5c 100644 --- a/app/Models/AssignMaterial.php +++ b/app/Models/AssignMaterial.php @@ -5,6 +5,7 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Models\RequestMaterial; use App\Models\Activity; +use Carbon\Carbon; class AssignMaterial extends Model { @@ -29,14 +30,32 @@ class AssignMaterial extends Model static::created(function($data) { $activity = Activity::find($data->activity_id); $material = RequestMaterial::where("id", $data->material_id)->first(); + $old = $activity->rencana_biaya; $activity->rencana_biaya += floatval($material->price) * floatval($data->qty_planning); $activity->save(); + + $msg = Carbon::now()->toDateTimeString() . ": ".$activity->id." ".$activity->name.PHP_EOL; + $msg .= "Added: ".$material->desc." (".floatval($material->price)." * ".floatval($data->qty_planning)."), Cost plan old: ".$old." | +".$activity->rencana_biayaPHP_EOL; + $msg .= "Data type (".gettype(floatval($material->price))." * ".gettype(floatval($material->qty_planning))."), ".gettype(floatval($old))." | ".gettype(floatval($activity->rencana_biaya)).PHP_EOL; + $msg .= "Data type origin (".gettype($material->price)." * ".gettype($material->qty_planning)."), ".gettype($old)." | ".gettype($activity->rencana_biaya).PHP_EOL; + $msg .= "------".PHP_EOL; + file_put_contents('activity_log.txt', $msg, FILE_APPEND | LOCK_EX); + }); static::deleted(function($data) { $activity = Activity::where('id', $data->activity_id)->first(); + $old = $activity->rencana_biaya; $activity->rencana_biaya -= floatval($data->budget) * floatval($data->qty_planning); $activity->save(); + $material = RequestMaterial::where("id", $data->material_id)->first(); + + $msg = Carbon::now()->toDateTimeString() . ": ".$activity->id." ".$activity->name.PHP_EOL; + $msg .= "Deleted: ".$material->desc." (".floatval($data->budget)." * ".floatval($data->qty_planning)."), Cost plan old: ".$old." | -".$activity->rencana_biaya.PHP_EOL; + $msg .= "Data type (".gettype(floatval($data->budget))." * ".gettype(floatval($data->qty_planning))."), ".gettype(floatval($old))." | ".gettype(floatval($activity->rencana_biaya)).PHP_EOL; + $msg .= "Data type origin (".gettype($data->budget)." * ".gettype($data->qty_planning)."), ".gettype($old)." | ".gettype($activity->rencana_biaya).PHP_EOL; + $msg .= "------".PHP_EOL; + file_put_contents('activity_log.txt', $msg, FILE_APPEND | LOCK_EX); }); } From 4e644e517519fab42862ae6ada88f83ec86071af Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Mon, 11 Jul 2022 20:24:06 +0700 Subject: [PATCH 17/19] cast data type --- app/Models/RequestMaterial.php | 36 ++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/app/Models/RequestMaterial.php b/app/Models/RequestMaterial.php index 4686317..df32ec2 100644 --- a/app/Models/RequestMaterial.php +++ b/app/Models/RequestMaterial.php @@ -11,23 +11,29 @@ class RequestMaterial extends Model const CREATED_AT = 'created_at'; const UPDATED_AT = 'updated_at'; + protected $casts = [ + 'id' => 'integer', + 'price' => 'float', + 'qty' => 'float', + ]; + protected $fillable = [ - 'description', - 'required_date', - 'qty', - 'uom', - 'qty_received', - 'fom_date', - 'pr_date', - 'po_date', - 'received_date', - 'delivery_date', - 'status', + 'description', + 'required_date', + 'qty', + 'uom', + 'qty_received', + 'fom_date', + 'pr_date', + 'po_date', + 'received_date', + 'delivery_date', + 'status', 'proyek_id', - 'created_at', - 'created_by', - 'updated_at', - 'updated_by', + 'created_at', + 'created_by', + 'updated_at', + 'updated_by', 'price' ]; } From 10eea7064579a88fb8cd027618d47588e2c08f29 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Tue, 12 Jul 2022 00:14:22 +0700 Subject: [PATCH 18/19] calc update --- activity_log.txt | 18 +- .../Controllers/RequestMaterialController.php | 305 +++++++++--------- app/Models/AssignMaterial.php | 2 +- 3 files changed, 159 insertions(+), 166 deletions(-) diff --git a/activity_log.txt b/activity_log.txt index adef32d..1c6c2d1 100755 --- a/activity_log.txt +++ b/activity_log.txt @@ -1,10 +1,20 @@ -2022-07-11 20:20:30: Project Plan -Added: (10000 * 5), Cost plan old: 0 | 50000_ +2022-07-12 00:13:26: 1379 Penentuan harga project +Added: (10000000 * 1), Cost plan old: 0 | +10000000 Data type (double * double), double | double Data type origin (double * NULL), string | double ------ -2022-07-11 20:21:26: Project Plan -Deleted: (10000 * 5), Cost plan old: 50000 | -0_ +2022-07-12 00:13:32: 1378 Contract Management +Deleted: (10000000 * 1), Cost plan old: 20000000 | -10000000 +Data type (double * double), double | double +Data type origin (double * double), string | double +------ +2022-07-12 00:13:38: 1377 Brainstorming peningkatan layanan masyarakat +Deleted: (10000000 * 1), Cost plan old: 20000000 | -10000000 +Data type (double * double), double | double +Data type origin (double * double), string | double +------ +2022-07-12 00:13:47: 1379 Penentuan harga project +Deleted: (10000000 * 1), Cost plan old: 10000000 | -0 Data type (double * double), double | double Data type origin (double * double), string | double ------ diff --git a/app/Http/Controllers/RequestMaterialController.php b/app/Http/Controllers/RequestMaterialController.php index 7a45ab5..2360ec1 100644 --- a/app/Http/Controllers/RequestMaterialController.php +++ b/app/Http/Controllers/RequestMaterialController.php @@ -8,165 +8,148 @@ use App\Models\MaterialResource; class RequestMaterialController extends Controller { - public function add(Request $request){ - - $this->validate($request, [ - 'proyek_id' => 'required', - 'description' => 'required', - 'required_date' => 'required', - 'qty' => 'required', - 'uom' => 'required', - 'fom_date' => 'required', - ]); - - $data = $request->all(); - - $data['status'] = "fom"; - $data['created_by'] = $this->currentName; - - $result = RequestMaterial::create($data); - - if($result){ - return response()->json(['status'=>'success','message'=>'request material successfully!', 'data'=>$result, 'code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'request material failed!','code'=>400], 400); - } - } - - public function edit($id){ - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); - } - - $result = RequestMaterial::find($id); - - if($result){ - return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get data request material, please try again later!','code'=>400], 400); - } - } - - - - - - - - public function delete($id) - { - $data = RequestMaterial::find($id); - - if($data){ - $delete = $data->delete(); - }else{ - return response()->json(['status'=>'failed','message'=>'data request material not found!','code'=>400], 400); - die(); - } - - - if($delete){ - return response()->json(['status'=>'success','message'=>'request material successfully deleted!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'request material failed deleted!','code'=>400], 400); - } - } - - public function search(Request $request) - { - $payload = $request->all(); - $dataBuilder = $this->setUpPayload($payload, 'm_req_material'); - $builder = $dataBuilder['builder']; - $countBuilder = $dataBuilder['count']; - $dataGet = $builder->get(); - $totalRecord = $countBuilder->count(); - return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); - } - - public function list() - { - $data = RequestMaterial::all(); - $countData = $data->count(); - - if($data){ - return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'failed get list request material, please try again later!','code'=>400], 400); - } - } - - public function update(Request $request, $id) - { - $dataForm = $request->all(); - if(!$id || (int) $id < 0 || $id==""){ - return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); - } - $data = RequestMaterial::find($id); - if($data){ - if(!isset($dataForm['status'])){ - $resultUpdate = $data->update($request->all()); - if($resultUpdate){ - return response()->json(['status'=>'success','message'=>'request material successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'request material failed updated!','code'=>400], 400); - } - die(); - } - if($dataForm['status']=="receipt to warehouse"){ - $dataM = MaterialResource::where('name', 'ilike', $data->description)->first(); - if($dataM){ - $result = $data->update($request->all()); - $payloadMQty = $dataM->qty + $data->qty_received; - $resultUpdateM = MaterialResource::where('id', $dataM->id)->update(['qty' => $payloadMQty]); - return response()->json(['status'=>'success', 'code'=>200], 200); - }else{ - $result = $data->update($request->all()); - $dataPayloadM = array( - "name" => $dataForm['description'], - "uom" => $dataForm['uom'], - "unit_price" => 0, - "description" => $dataForm['description'], - "qty" => $data->qty_received, - "status" => "Barang tersedia", - "created_by" => $this->currentName - ); - $result = MaterialResource::create($dataPayloadM); - if($result){ - return response()->json(['status'=>'success','message'=>'add data material resource successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'add data material resource failed!','code'=>400], 400); - } - } - - }else if($dataForm['status']=="receipt to site"){ - $result = $data->update($request->all()); - $dataM = MaterialResource::where('name', 'ilike', $data->description)->first(); - if($dataM){ - $result = $data->update($request->all()); - $payloadMQty = $dataM->qty - $data->qty_received; - - if($payloadMQty < 0){ - return response()->json(['status'=>'failed','message'=>'update status receipt to site request material resource failed, because material is not exist in warehouse!','code'=>400], 400); - die(); - } - $resultUpdateM = MaterialResource::where('id', $dataM->id)->update(['qty' => $payloadMQty]); - return response()->json(['status'=>'success', 'message'=>'request material status receipt to site successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'update status receipt to site request material resource failed, because material is not exist in warehouse!','code'=>400], 400); - } - }else{ - $resultUpdate = $data->update($request->all()); - if($resultUpdate){ - return response()->json(['status'=>'success','message'=>'request material successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'request material failed updated!','code'=>400], 400); - } - } - }else{ - return response()->json(['status'=>'failed','message'=>'data request material not found!','code'=>400], 400); - die(); - } - } + public function add(Request $request){ + $this->validate($request, [ + 'proyek_id' => 'required', + 'description' => 'required', + 'required_date' => 'required', + 'qty' => 'required', + 'uom' => 'required', + 'fom_date' => 'required', + ]); + + $data = $request->all(); + + $data['status'] = "fom"; + $data['created_by'] = $this->currentName; + + $result = RequestMaterial::create($data); + + if(!$result) + return response()->json(['status'=>'failed','message'=>'Failed to add!','code'=> 500], 500); + + return response()->json(['status'=>'success','message'=>'Data added!', 'data'=>$result, 'code'=>200], 200); + } + + public function edit($id){ + if(empty($id) || !is_int((int)$id)) + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + + $result = RequestMaterial::find($id); + + if($result) + return response()->json(['status'=>'success','code'=>200,'data'=>$result], 200); + + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=> 404], 404); + } + + public function delete($id) + { + $data = RequestMaterial::find($id); + + if($data) + $delete = $data->delete(); + return response()->json(['status'=>'failed','message'=>'Data not found!','code'=>404], 404); + + if($delete) + return response()->json(['status'=>'success','message'=>'Data deleted!','code'=>200], 200); + + return response()->json(['status'=>'failed','message'=>'Failed to delete!','code'=> 500], 500); + } + + public function search(Request $request) + { + $payload = $request->all(); + $dataBuilder = $this->setUpPayload($payload, 'm_req_material'); + $builder = $dataBuilder['builder']; + $countBuilder = $dataBuilder['count']; + $dataGet = $builder->get(); + $totalRecord = $countBuilder->count(); + return response()->json(['status'=>'success','code'=>200,'data'=>$dataGet, 'totalRecord'=>$totalRecord], 200); + } + + public function list() + { + $data = RequestMaterial::all(); + $countData = $data->count(); + + if($data) + return response()->json(['status'=>'success','code'=>200,'data'=>$data, 'totalRecord'=>$countData], 200); + + return response()->json(['status'=>'failed','message'=>'failed get list request material, please try again later!','code'=>400], 400); + } + + public function update(Request $request, $id) + { + $dataForm = $request->all(); + if(!$id || (int) $id < 0 || $id==""){ + return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); + die(); + } + $data = RequestMaterial::find($id); + if($data){ + if(!isset($dataForm['status'])){ + $resultUpdate = $data->update($request->all()); + if($resultUpdate){ + return response()->json(['status'=>'success','message'=>'request material successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'request material failed updated!','code'=>400], 400); + } + die(); + } + if($dataForm['status']=="receipt to warehouse"){ + $dataM = MaterialResource::where('name', 'ilike', $data->description)->first(); + if($dataM){ + $result = $data->update($request->all()); + $payloadMQty = $dataM->qty + $data->qty_received; + $resultUpdateM = MaterialResource::where('id', $dataM->id)->update(['qty' => $payloadMQty]); + return response()->json(['status'=>'success', 'code'=>200], 200); + }else{ + $result = $data->update($request->all()); + $dataPayloadM = array( + "name" => $dataForm['description'], + "uom" => $dataForm['uom'], + "unit_price" => 0, + "description" => $dataForm['description'], + "qty" => $data->qty_received, + "status" => "Barang tersedia", + "created_by" => $this->currentName + ); + $result = MaterialResource::create($dataPayloadM); + if($result){ + return response()->json(['status'=>'success','message'=>'add data material resource successfully!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'add data material resource failed!','code'=>400], 400); + } + } + + }else if($dataForm['status']=="receipt to site"){ + $result = $data->update($request->all()); + $dataM = MaterialResource::where('name', 'ilike', $data->description)->first(); + if($dataM){ + $result = $data->update($request->all()); + $payloadMQty = $dataM->qty - $data->qty_received; + + if($payloadMQty < 0){ + return response()->json(['status'=>'failed','message'=>'update status receipt to site request material resource failed, because material is not exist in warehouse!','code'=>400], 400); + die(); + } + $resultUpdateM = MaterialResource::where('id', $dataM->id)->update(['qty' => $payloadMQty]); + return response()->json(['status'=>'success', 'message'=>'request material status receipt to site successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'update status receipt to site request material resource failed, because material is not exist in warehouse!','code'=>400], 400); + } + }else{ + $resultUpdate = $data->update($request->all()); + if($resultUpdate){ + return response()->json(['status'=>'success','message'=>'request material successfully updated!','code'=>200], 200); + }else{ + return response()->json(['status'=>'failed','message'=>'request material failed updated!','code'=>400], 400); + } + } + }else{ + return response()->json(['status'=>'failed','message'=>'data request material not found!','code'=>400], 400); + die(); + } + } } diff --git a/app/Models/AssignMaterial.php b/app/Models/AssignMaterial.php index 7060c5c..297b525 100644 --- a/app/Models/AssignMaterial.php +++ b/app/Models/AssignMaterial.php @@ -35,7 +35,7 @@ class AssignMaterial extends Model $activity->save(); $msg = Carbon::now()->toDateTimeString() . ": ".$activity->id." ".$activity->name.PHP_EOL; - $msg .= "Added: ".$material->desc." (".floatval($material->price)." * ".floatval($data->qty_planning)."), Cost plan old: ".$old." | +".$activity->rencana_biayaPHP_EOL; + $msg .= "Added: ".$material->desc." (".floatval($material->price)." * ".floatval($data->qty_planning)."), Cost plan old: ".$old." | +".$activity->rencana_biaya.PHP_EOL; $msg .= "Data type (".gettype(floatval($material->price))." * ".gettype(floatval($material->qty_planning))."), ".gettype(floatval($old))." | ".gettype(floatval($activity->rencana_biaya)).PHP_EOL; $msg .= "Data type origin (".gettype($material->price)." * ".gettype($material->qty_planning)."), ".gettype($old)." | ".gettype($activity->rencana_biaya).PHP_EOL; $msg .= "------".PHP_EOL; From 82e1bd33aedbbd1fccab75b455aa7aa908eefb54 Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Tue, 12 Jul 2022 02:34:31 +0700 Subject: [PATCH 19/19] cleanse code --- .../Controllers/RequestMaterialController.php | 122 ++++++++---------- 1 file changed, 57 insertions(+), 65 deletions(-) diff --git a/app/Http/Controllers/RequestMaterialController.php b/app/Http/Controllers/RequestMaterialController.php index 2360ec1..474e2af 100644 --- a/app/Http/Controllers/RequestMaterialController.php +++ b/app/Http/Controllers/RequestMaterialController.php @@ -82,74 +82,66 @@ class RequestMaterialController extends Controller public function update(Request $request, $id) { $dataForm = $request->all(); - if(!$id || (int) $id < 0 || $id==""){ + if(empty($id) || !is_int((int)$id)) return response()->json(['status'=>'failed','message'=>'id is required!','code'=>400], 400); - die(); + + $reqMaterial = RequestMaterial::find($id); + if(!$reqMaterial) + return response()->json(['status'=>'failed','message'=>'data request material not found!','code'=>400], 400); + + if(!isset($dataForm['status'])){ + if(!$reqMaterial->update($request->all())) + return response()->json(['status'=>'failed','message'=>'request material failed updated!','code'=>400], 400); + return response()->json(['status'=>'success','message'=>'request material successfully updated!','code'=>200], 200); } - $data = RequestMaterial::find($id); - if($data){ - if(!isset($dataForm['status'])){ - $resultUpdate = $data->update($request->all()); - if($resultUpdate){ - return response()->json(['status'=>'success','message'=>'request material successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'request material failed updated!','code'=>400], 400); - } - die(); - } - if($dataForm['status']=="receipt to warehouse"){ - $dataM = MaterialResource::where('name', 'ilike', $data->description)->first(); - if($dataM){ - $result = $data->update($request->all()); - $payloadMQty = $dataM->qty + $data->qty_received; - $resultUpdateM = MaterialResource::where('id', $dataM->id)->update(['qty' => $payloadMQty]); - return response()->json(['status'=>'success', 'code'=>200], 200); - }else{ - $result = $data->update($request->all()); - $dataPayloadM = array( - "name" => $dataForm['description'], - "uom" => $dataForm['uom'], - "unit_price" => 0, - "description" => $dataForm['description'], - "qty" => $data->qty_received, - "status" => "Barang tersedia", - "created_by" => $this->currentName - ); - $result = MaterialResource::create($dataPayloadM); - if($result){ - return response()->json(['status'=>'success','message'=>'add data material resource successfully!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'add data material resource failed!','code'=>400], 400); - } - } - - }else if($dataForm['status']=="receipt to site"){ - $result = $data->update($request->all()); - $dataM = MaterialResource::where('name', 'ilike', $data->description)->first(); - if($dataM){ - $result = $data->update($request->all()); - $payloadMQty = $dataM->qty - $data->qty_received; - - if($payloadMQty < 0){ - return response()->json(['status'=>'failed','message'=>'update status receipt to site request material resource failed, because material is not exist in warehouse!','code'=>400], 400); - die(); - } - $resultUpdateM = MaterialResource::where('id', $dataM->id)->update(['qty' => $payloadMQty]); - return response()->json(['status'=>'success', 'message'=>'request material status receipt to site successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'update status receipt to site request material resource failed, because material is not exist in warehouse!','code'=>400], 400); - } - }else{ - $resultUpdate = $data->update($request->all()); - if($resultUpdate){ - return response()->json(['status'=>'success','message'=>'request material successfully updated!','code'=>200], 200); - }else{ - return response()->json(['status'=>'failed','message'=>'request material failed updated!','code'=>400], 400); - } + + if($dataForm['status']=="receipt to warehouse"){ + $materialResource = MaterialResource::where('name', 'ilike', $reqMaterial->description)->first(); + if($materialResource){ + $reqMaterial->update($request->all()); + $payloadMQty = $materialResource->qty + $reqMaterial->qty_received; + MaterialResource::where('id', $materialResource->id)->update(['qty' => $payloadMQty]); + return response()->json(['status'=>'success', 'code'=>200], 200); } - }else{ - return response()->json(['status'=>'failed','message'=>'data request material not found!','code'=>400], 400); - die(); + + $reqMaterial->update($request->all()); + + $preparedMaterialResource = array( + "name" => $dataForm['description'], + "uom" => $dataForm['uom'], + "unit_price" => 0, + "description" => $dataForm['description'], + "qty" => $reqMaterial->qty_received, + "status" => "Barang tersedia", + "created_by" => $this->currentName + ); + + if(!MaterialResource::create($preparedMaterialResource )) + return response()->json(['status'=>'failed','message'=>'add data material resource failed!','code'=>400], 400); + + return response()->json(['status'=>'success','message'=>'add data material resource successfully!','code'=>200], 200); + } + + if($dataForm['status']=="receipt to site"){ + $reqMaterial->update($request->all()); + + $materialResource = MaterialResource::where('name', 'ilike', $reqMaterial->description)->first(); + if(!$materialResource) + return response()->json(['status'=>'failed','message'=>'update status receipt to site request material resource failed, because material is not exist in warehouse!','code'=>400], 400); + + $reqMaterial->update($request->all()); + $payloadMQty = $materialResource->qty - $reqMaterial->qty_received; + + if($payloadMQty < 0) + return response()->json(['status'=>'failed','message'=>'update status receipt to site request material resource failed, because material is not exist in warehouse!','code'=>400], 400); + + MaterialResource::where('id', $materialResource->id)->update(['qty' => $payloadMQty]); + return response()->json(['status'=>'success', 'message'=>'request material status receipt to site successfully updated!','code'=>200], 200); } + + if(!$reqMaterial->update($request->all())) + return response()->json(['status'=>'failed','message'=>'request material failed updated!','code'=>400], 400); + + return response()->json(['status'=>'success','message'=>'request material successfully updated!','code'=>200], 200); } }